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

1.465   ! dtucker     1: /* $OpenBSD: sshd.c,v 1.464 2016/01/29 02:54:45 dtucker 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.454     markus     80: #include "match.h"
1.1       deraadt    81: #include "servconf.h"
                     82: #include "uidswap.h"
1.33      markus     83: #include "compat.h"
1.155     markus     84: #include "cipher.h"
1.415     markus     85: #include "digest.h"
1.343     deraadt    86: #include "key.h"
1.98      markus     87: #include "kex.h"
                     88: #include "myproposal.h"
1.108     markus     89: #include "authfile.h"
1.154     markus     90: #include "pathnames.h"
1.155     markus     91: #include "atomicio.h"
                     92: #include "canohost.h"
1.343     deraadt    93: #include "hostfile.h"
1.155     markus     94: #include "auth.h"
1.404     markus     95: #include "authfd.h"
1.294     djm        96: #include "msg.h"
1.186     markus     97: #include "dispatch.h"
1.206     stevesk    98: #include "channels.h"
1.230     provos     99: #include "session.h"
1.231     provos    100: #include "monitor_mm.h"
                    101: #include "monitor.h"
1.343     deraadt   102: #ifdef GSSAPI
                    103: #include "ssh-gss.h"
                    104: #endif
1.231     provos    105: #include "monitor_wrap.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.463     markus    416:        if (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.463     markus    426:                if (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.460     djm       602:        /* Demote the child */
                    603:        if (getuid() == 0 || geteuid() == 0) {
                    604:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                    605:                        fatal("Privilege separation user %s does not exist",
                    606:                            SSH_PRIVSEP_USER);
                    607:                explicit_bzero(pw->pw_passwd, strlen(pw->pw_passwd));
                    608:                endpwent();
                    609:
                    610:                /* Change our root directory */
                    611:                if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    612:                        fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    613:                            strerror(errno));
                    614:                if (chdir("/") == -1)
                    615:                        fatal("chdir(\"/\"): %s", strerror(errno));
                    616:
                    617:                /*
                    618:                 * Drop our privileges
                    619:                 * NB. Can't use setusercontext() after chroot.
                    620:                 */
                    621:                debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    622:                    (u_int)pw->pw_gid);
                    623:                gidset[0] = pw->pw_gid;
                    624:                if (setgroups(1, gidset) < 0)
                    625:                        fatal("setgroups: %.100s", strerror(errno));
                    626:                permanently_set_uid(pw);
                    627:        }
1.231     provos    628: }
                    629:
1.278     markus    630: static int
                    631: privsep_preauth(Authctxt *authctxt)
1.237     markus    632: {
1.432     djm       633:        int status, r;
1.237     markus    634:        pid_t pid;
1.384     djm       635:        struct ssh_sandbox *box = NULL;
1.237     markus    636:
                    637:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   638:        pmonitor = monitor_init();
1.237     markus    639:        /* Store a pointer to the kex for later rekeying */
1.434     markus    640:        pmonitor->m_pkex = &active_state->kex;
1.237     markus    641:
1.393     djm       642:        if (use_privsep == PRIVSEP_ON)
1.384     djm       643:                box = ssh_sandbox_init();
1.237     markus    644:        pid = fork();
                    645:        if (pid == -1) {
                    646:                fatal("fork of unprivileged child failed");
                    647:        } else if (pid != 0) {
1.245     mpech     648:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    649:
1.392     markus    650:                pmonitor->m_pid = pid;
1.432     djm       651:                if (have_agent) {
                    652:                        r = ssh_get_authentication_socket(&auth_sock);
                    653:                        if (r != 0) {
                    654:                                error("Could not get agent socket: %s",
                    655:                                    ssh_err(r));
                    656:                                have_agent = 0;
                    657:                        }
                    658:                }
1.384     djm       659:                if (box != NULL)
                    660:                        ssh_sandbox_parent_preauth(box, pid);
1.278     markus    661:                monitor_child_preauth(authctxt, pmonitor);
1.237     markus    662:
                    663:                /* Sync memory */
1.242     mouring   664:                monitor_sync(pmonitor);
1.237     markus    665:
                    666:                /* Wait for the child's exit status */
1.384     djm       667:                while (waitpid(pid, &status, 0) < 0) {
1.386     djm       668:                        if (errno == EINTR)
                    669:                                continue;
                    670:                        pmonitor->m_pid = -1;
                    671:                        fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384     djm       672:                }
1.386     djm       673:                privsep_is_preauth = 0;
                    674:                pmonitor->m_pid = -1;
1.384     djm       675:                if (WIFEXITED(status)) {
                    676:                        if (WEXITSTATUS(status) != 0)
                    677:                                fatal("%s: preauth child exited with status %d",
                    678:                                    __func__, WEXITSTATUS(status));
                    679:                } else if (WIFSIGNALED(status))
                    680:                        fatal("%s: preauth child terminated by signal %d",
                    681:                            __func__, WTERMSIG(status));
                    682:                if (box != NULL)
                    683:                        ssh_sandbox_parent_finish(box);
                    684:                return 1;
1.237     markus    685:        } else {
                    686:                /* child */
1.383     djm       687:                close(pmonitor->m_sendfd);
                    688:                close(pmonitor->m_log_recvfd);
1.237     markus    689:
1.383     djm       690:                /* Arrange for logging to be sent to the monitor */
                    691:                set_log_handler(mm_log_handler, pmonitor);
1.237     markus    692:
1.460     djm       693:                privsep_preauth_child();
1.238     stevesk   694:                setproctitle("%s", "[net]");
1.384     djm       695:                if (box != NULL)
                    696:                        ssh_sandbox_child(box);
                    697:
                    698:                return 0;
1.237     markus    699:        }
                    700: }
                    701:
1.233     markus    702: static void
1.237     markus    703: privsep_postauth(Authctxt *authctxt)
1.231     provos    704: {
                    705:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    706:                /* File descriptor passing is broken or root login */
                    707:                use_privsep = 0;
1.315     djm       708:                goto skip;
1.231     provos    709:        }
1.234     markus    710:
1.231     provos    711:        /* New socket pair */
1.242     mouring   712:        monitor_reinit(pmonitor);
1.231     provos    713:
1.242     mouring   714:        pmonitor->m_pid = fork();
                    715:        if (pmonitor->m_pid == -1)
1.231     provos    716:                fatal("fork of unprivileged child failed");
1.242     mouring   717:        else if (pmonitor->m_pid != 0) {
1.364     markus    718:                verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.307     otto      719:                buffer_clear(&loginmsg);
1.242     mouring   720:                monitor_child_postauth(pmonitor);
1.231     provos    721:
                    722:                /* NEVERREACHED */
                    723:                exit(0);
                    724:        }
                    725:
1.383     djm       726:        /* child */
                    727:
1.242     mouring   728:        close(pmonitor->m_sendfd);
1.383     djm       729:        pmonitor->m_sendfd = -1;
1.231     provos    730:
                    731:        /* Demote the private keys to public keys. */
                    732:        demote_sensitive_data();
1.354     djm       733:
1.231     provos    734:        /* Drop privileges */
                    735:        do_setusercontext(authctxt->pw);
                    736:
1.315     djm       737:  skip:
1.231     provos    738:        /* It is safe now to apply the key state */
1.242     mouring   739:        monitor_apply_keystate(pmonitor);
1.312     markus    740:
                    741:        /*
                    742:         * Tell the packet layer that authentication was successful, since
                    743:         * this information is not part of the key state.
                    744:         */
                    745:        packet_set_authenticated();
1.231     provos    746: }
                    747:
1.200     itojun    748: static char *
1.134     markus    749: list_hostkey_types(void)
                    750: {
1.223     markus    751:        Buffer b;
1.281     jakob     752:        const char *p;
                    753:        char *ret;
1.134     markus    754:        int i;
1.373     djm       755:        Key *key;
1.223     markus    756:
                    757:        buffer_init(&b);
1.217     deraadt   758:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       759:                key = sensitive_data.host_keys[i];
1.443     djm       760:                if (key == NULL)
1.404     markus    761:                        key = sensitive_data.host_pubkeys[i];
1.456     djm       762:                if (key == NULL || key->type == KEY_RSA1)
1.134     markus    763:                        continue;
1.454     markus    764:                /* Check that the key is accepted in HostkeyAlgorithms */
                    765:                if (match_pattern_list(sshkey_ssh_name(key),
                    766:                    options.hostkeyalgorithms, 0) != 1) {
                    767:                        debug3("%s: %s key not permitted by HostkeyAlgorithms",
                    768:                            __func__, sshkey_ssh_name(key));
                    769:                        continue;
                    770:                }
1.214     deraadt   771:                switch (key->type) {
1.134     markus    772:                case KEY_RSA:
                    773:                case KEY_DSA:
1.378     djm       774:                case KEY_ECDSA:
1.412     markus    775:                case KEY_ED25519:
1.223     markus    776:                        if (buffer_len(&b) > 0)
                    777:                                buffer_append(&b, ",", 1);
                    778:                        p = key_ssh_name(key);
                    779:                        buffer_append(&b, p, strlen(p));
1.461     markus    780:
                    781:                        /* for RSA we also support SHA2 signatures */
                    782:                        if (key->type == KEY_RSA) {
                    783:                                p = ",rsa-sha2-512,rsa-sha2-256";
                    784:                                buffer_append(&b, p, strlen(p));
                    785:                        }
1.134     markus    786:                        break;
                    787:                }
1.373     djm       788:                /* If the private key has a cert peer, then list that too */
                    789:                key = sensitive_data.host_certificates[i];
                    790:                if (key == NULL)
                    791:                        continue;
                    792:                switch (key->type) {
                    793:                case KEY_RSA_CERT:
                    794:                case KEY_DSA_CERT:
1.378     djm       795:                case KEY_ECDSA_CERT:
1.412     markus    796:                case KEY_ED25519_CERT:
1.373     djm       797:                        if (buffer_len(&b) > 0)
                    798:                                buffer_append(&b, ",", 1);
                    799:                        p = key_ssh_name(key);
                    800:                        buffer_append(&b, p, strlen(p));
                    801:                        break;
                    802:                }
1.134     markus    803:        }
1.223     markus    804:        buffer_append(&b, "\0", 1);
1.281     jakob     805:        ret = xstrdup(buffer_ptr(&b));
1.223     markus    806:        buffer_free(&b);
1.281     jakob     807:        debug("list_hostkey_types: %s", ret);
                    808:        return ret;
1.134     markus    809: }
                    810:
1.373     djm       811: static Key *
1.440     djm       812: get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
1.134     markus    813: {
                    814:        int i;
1.373     djm       815:        Key *key;
1.250     deraadt   816:
1.217     deraadt   817:        for (i = 0; i < options.num_host_key_files; i++) {
1.375     djm       818:                switch (type) {
                    819:                case KEY_RSA_CERT:
                    820:                case KEY_DSA_CERT:
1.378     djm       821:                case KEY_ECDSA_CERT:
1.412     markus    822:                case KEY_ED25519_CERT:
1.373     djm       823:                        key = sensitive_data.host_certificates[i];
1.375     djm       824:                        break;
                    825:                default:
1.373     djm       826:                        key = sensitive_data.host_keys[i];
1.404     markus    827:                        if (key == NULL && !need_private)
                    828:                                key = sensitive_data.host_pubkeys[i];
1.375     djm       829:                        break;
                    830:                }
1.440     djm       831:                if (key != NULL && key->type == type &&
                    832:                    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
1.373     djm       833:                        return need_private ?
                    834:                            sensitive_data.host_keys[i] : key;
1.134     markus    835:        }
                    836:        return NULL;
1.96      markus    837: }
                    838:
1.231     provos    839: Key *
1.440     djm       840: get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       841: {
1.440     djm       842:        return get_hostkey_by_type(type, nid, 0, ssh);
1.373     djm       843: }
                    844:
                    845: Key *
1.440     djm       846: get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       847: {
1.440     djm       848:        return get_hostkey_by_type(type, nid, 1, ssh);
1.373     djm       849: }
                    850:
                    851: Key *
1.231     provos    852: get_hostkey_by_index(int ind)
                    853: {
                    854:        if (ind < 0 || ind >= options.num_host_key_files)
                    855:                return (NULL);
                    856:        return (sensitive_data.host_keys[ind]);
                    857: }
                    858:
1.404     markus    859: Key *
1.435     markus    860: get_hostkey_public_by_index(int ind, struct ssh *ssh)
1.404     markus    861: {
                    862:        if (ind < 0 || ind >= options.num_host_key_files)
                    863:                return (NULL);
                    864:        return (sensitive_data.host_pubkeys[ind]);
                    865: }
                    866:
1.231     provos    867: int
1.442     djm       868: get_hostkey_index(Key *key, int compare, struct ssh *ssh)
1.231     provos    869: {
                    870:        int i;
1.250     deraadt   871:
1.231     provos    872:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       873:                if (key_is_cert(key)) {
1.442     djm       874:                        if (key == sensitive_data.host_certificates[i] ||
                    875:                            (compare && sensitive_data.host_certificates[i] &&
                    876:                            sshkey_equal(key,
                    877:                            sensitive_data.host_certificates[i])))
1.373     djm       878:                                return (i);
                    879:                } else {
1.442     djm       880:                        if (key == sensitive_data.host_keys[i] ||
                    881:                            (compare && sensitive_data.host_keys[i] &&
                    882:                            sshkey_equal(key, sensitive_data.host_keys[i])))
1.373     djm       883:                                return (i);
1.442     djm       884:                        if (key == sensitive_data.host_pubkeys[i] ||
                    885:                            (compare && sensitive_data.host_pubkeys[i] &&
                    886:                            sshkey_equal(key, sensitive_data.host_pubkeys[i])))
1.404     markus    887:                                return (i);
1.373     djm       888:                }
1.231     provos    889:        }
                    890:        return (-1);
                    891: }
                    892:
1.439     djm       893: /* Inform the client of all hostkeys */
                    894: static void
                    895: notify_hostkeys(struct ssh *ssh)
                    896: {
                    897:        struct sshbuf *buf;
                    898:        struct sshkey *key;
                    899:        int i, nkeys, r;
                    900:        char *fp;
1.446     dtucker   901:
                    902:        /* Some clients cannot cope with the hostkeys message, skip those. */
                    903:        if (datafellows & SSH_BUG_HOSTKEYS)
                    904:                return;
1.439     djm       905:
                    906:        if ((buf = sshbuf_new()) == NULL)
                    907:                fatal("%s: sshbuf_new", __func__);
                    908:        for (i = nkeys = 0; i < options.num_host_key_files; i++) {
                    909:                key = get_hostkey_public_by_index(i, ssh);
                    910:                if (key == NULL || key->type == KEY_UNSPEC ||
                    911:                    key->type == KEY_RSA1 || sshkey_is_cert(key))
                    912:                        continue;
                    913:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    914:                    SSH_FP_DEFAULT);
                    915:                debug3("%s: key %d: %s %s", __func__, i,
                    916:                    sshkey_ssh_name(key), fp);
                    917:                free(fp);
1.442     djm       918:                if (nkeys == 0) {
                    919:                        packet_start(SSH2_MSG_GLOBAL_REQUEST);
1.444     djm       920:                        packet_put_cstring("hostkeys-00@openssh.com");
1.442     djm       921:                        packet_put_char(0); /* want-reply */
                    922:                }
                    923:                sshbuf_reset(buf);
                    924:                if ((r = sshkey_putb(key, buf)) != 0)
1.439     djm       925:                        fatal("%s: couldn't put hostkey %d: %s",
                    926:                            __func__, i, ssh_err(r));
1.442     djm       927:                packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
1.439     djm       928:                nkeys++;
                    929:        }
1.442     djm       930:        debug3("%s: sent %d hostkeys", __func__, nkeys);
1.439     djm       931:        if (nkeys == 0)
                    932:                fatal("%s: no hostkeys", __func__);
                    933:        packet_send();
1.442     djm       934:        sshbuf_free(buf);
1.439     djm       935: }
                    936:
1.124     markus    937: /*
                    938:  * returns 1 if connection should be dropped, 0 otherwise.
                    939:  * dropping starts at connection #max_startups_begin with a probability
                    940:  * of (max_startups_rate/100). the probability increases linearly until
                    941:  * all connections are dropped for startups > max_startups
                    942:  */
1.200     itojun    943: static int
1.124     markus    944: drop_connection(int startups)
                    945: {
1.303     mickey    946:        int p, r;
1.124     markus    947:
                    948:        if (startups < options.max_startups_begin)
                    949:                return 0;
                    950:        if (startups >= options.max_startups)
                    951:                return 1;
                    952:        if (options.max_startups_rate == 100)
                    953:                return 1;
                    954:
                    955:        p  = 100 - options.max_startups_rate;
                    956:        p *= startups - options.max_startups_begin;
1.303     mickey    957:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    958:        p += options.max_startups_rate;
1.356     djm       959:        r = arc4random_uniform(100);
1.124     markus    960:
1.304     djm       961:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    962:        return (r < p) ? 1 : 0;
                    963: }
                    964:
1.215     markus    965: static void
                    966: usage(void)
                    967: {
1.290     markus    968:        fprintf(stderr, "%s, %s\n",
1.426     markus    969:            SSH_VERSION,
                    970: #ifdef WITH_OPENSSL
                    971:            SSLeay_version(SSLEAY_VERSION)
                    972: #else
                    973:            "without OpenSSL"
                    974: #endif
                    975:        );
1.289     markus    976:        fprintf(stderr,
1.373     djm       977: "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1.399     dtucker   978: "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
                    979: "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
                    980: "            [-u len]\n"
1.289     markus    981:        );
1.215     markus    982:        exit(1);
                    983: }
                    984:
1.294     djm       985: static void
                    986: send_rexec_state(int fd, Buffer *conf)
                    987: {
                    988:        Buffer m;
                    989:
                    990:        debug3("%s: entering fd = %d config len %d", __func__, fd,
                    991:            buffer_len(conf));
                    992:
                    993:        /*
                    994:         * Protocol from reexec master to child:
                    995:         *      string  configuration
                    996:         *      u_int   ephemeral_key_follows
                    997:         *      bignum  e               (only if ephemeral_key_follows == 1)
                    998:         *      bignum  n                       "
                    999:         *      bignum  d                       "
                   1000:         *      bignum  iqmp                    "
                   1001:         *      bignum  p                       "
                   1002:         *      bignum  q                       "
                   1003:         */
                   1004:        buffer_init(&m);
                   1005:        buffer_put_cstring(&m, buffer_ptr(conf));
                   1006:
1.426     markus   1007: #ifdef WITH_SSH1
1.298     deraadt  1008:        if (sensitive_data.server_key != NULL &&
1.294     djm      1009:            sensitive_data.server_key->type == KEY_RSA1) {
                   1010:                buffer_put_int(&m, 1);
                   1011:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
                   1012:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
                   1013:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
                   1014:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                   1015:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
                   1016:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
                   1017:        } else
1.426     markus   1018: #endif
1.294     djm      1019:                buffer_put_int(&m, 0);
                   1020:
                   1021:        if (ssh_msg_send(fd, 0, &m) == -1)
                   1022:                fatal("%s: ssh_msg_send failed", __func__);
                   1023:
                   1024:        buffer_free(&m);
                   1025:
                   1026:        debug3("%s: done", __func__);
                   1027: }
                   1028:
                   1029: static void
                   1030: recv_rexec_state(int fd, Buffer *conf)
                   1031: {
                   1032:        Buffer m;
                   1033:        char *cp;
                   1034:        u_int len;
                   1035:
                   1036:        debug3("%s: entering fd = %d", __func__, fd);
                   1037:
                   1038:        buffer_init(&m);
                   1039:
                   1040:        if (ssh_msg_recv(fd, &m) == -1)
                   1041:                fatal("%s: ssh_msg_recv failed", __func__);
                   1042:        if (buffer_get_char(&m) != 0)
                   1043:                fatal("%s: rexec version mismatch", __func__);
                   1044:
                   1045:        cp = buffer_get_string(&m, &len);
                   1046:        if (conf != NULL)
                   1047:                buffer_append(conf, cp, len + 1);
1.402     djm      1048:        free(cp);
1.294     djm      1049:
                   1050:        if (buffer_get_int(&m)) {
1.426     markus   1051: #ifdef WITH_SSH1
1.294     djm      1052:                if (sensitive_data.server_key != NULL)
                   1053:                        key_free(sensitive_data.server_key);
                   1054:                sensitive_data.server_key = key_new_private(KEY_RSA1);
                   1055:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
                   1056:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
                   1057:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
                   1058:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                   1059:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
                   1060:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1.427     djm      1061:                if (rsa_generate_additional_parameters(
                   1062:                    sensitive_data.server_key->rsa) != 0)
                   1063:                        fatal("%s: rsa_generate_additional_parameters "
                   1064:                            "error", __func__);
1.426     markus   1065: #endif
1.294     djm      1066:        }
                   1067:        buffer_free(&m);
                   1068:
                   1069:        debug3("%s: done", __func__);
                   1070: }
                   1071:
1.345     djm      1072: /* Accept a connection from inetd */
                   1073: static void
                   1074: server_accept_inetd(int *sock_in, int *sock_out)
                   1075: {
                   1076:        int fd;
                   1077:
                   1078:        startup_pipe = -1;
                   1079:        if (rexeced_flag) {
                   1080:                close(REEXEC_CONFIG_PASS_FD);
                   1081:                *sock_in = *sock_out = dup(STDIN_FILENO);
                   1082:                if (!debug_flag) {
                   1083:                        startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                   1084:                        close(REEXEC_STARTUP_PIPE_FD);
                   1085:                }
                   1086:        } else {
                   1087:                *sock_in = dup(STDIN_FILENO);
                   1088:                *sock_out = dup(STDOUT_FILENO);
                   1089:        }
                   1090:        /*
                   1091:         * We intentionally do not close the descriptors 0, 1, and 2
                   1092:         * as our code for setting the descriptors won't work if
                   1093:         * ttyfd happens to be one of those.
                   1094:         */
                   1095:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1096:                dup2(fd, STDIN_FILENO);
                   1097:                dup2(fd, STDOUT_FILENO);
1.403     dtucker  1098:                if (!log_stderr)
                   1099:                        dup2(fd, STDERR_FILENO);
                   1100:                if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1.345     djm      1101:                        close(fd);
                   1102:        }
                   1103:        debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
                   1104: }
                   1105:
                   1106: /*
                   1107:  * Listen for TCP connections
                   1108:  */
                   1109: static void
                   1110: server_listen(void)
                   1111: {
                   1112:        int ret, listen_sock, on = 1;
                   1113:        struct addrinfo *ai;
                   1114:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   1115:
                   1116:        for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                   1117:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1118:                        continue;
                   1119:                if (num_listen_socks >= MAX_LISTEN_SOCKS)
                   1120:                        fatal("Too many listen sockets. "
                   1121:                            "Enlarge MAX_LISTEN_SOCKS");
                   1122:                if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
                   1123:                    ntop, sizeof(ntop), strport, sizeof(strport),
                   1124:                    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
                   1125:                        error("getnameinfo failed: %.100s",
1.352     dtucker  1126:                            ssh_gai_strerror(ret));
1.345     djm      1127:                        continue;
                   1128:                }
                   1129:                /* Create socket for listening. */
1.370     dtucker  1130:                listen_sock = socket(ai->ai_family, ai->ai_socktype,
                   1131:                    ai->ai_protocol);
1.345     djm      1132:                if (listen_sock < 0) {
                   1133:                        /* kernel may not support ipv6 */
                   1134:                        verbose("socket: %.100s", strerror(errno));
                   1135:                        continue;
                   1136:                }
                   1137:                if (set_nonblock(listen_sock) == -1) {
                   1138:                        close(listen_sock);
                   1139:                        continue;
                   1140:                }
                   1141:                /*
                   1142:                 * Set socket options.
                   1143:                 * Allow local port reuse in TIME_WAIT.
                   1144:                 */
                   1145:                if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1146:                    &on, sizeof(on)) == -1)
                   1147:                        error("setsockopt SO_REUSEADDR: %s", strerror(errno));
                   1148:
                   1149:                debug("Bind to port %s on %s.", strport, ntop);
                   1150:
                   1151:                /* Bind the socket to the desired port. */
                   1152:                if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1153:                        error("Bind to port %s on %s failed: %.200s.",
                   1154:                            strport, ntop, strerror(errno));
                   1155:                        close(listen_sock);
                   1156:                        continue;
                   1157:                }
                   1158:                listen_socks[num_listen_socks] = listen_sock;
                   1159:                num_listen_socks++;
                   1160:
                   1161:                /* Start listening on the port. */
                   1162:                if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
                   1163:                        fatal("listen on [%s]:%s: %.100s",
                   1164:                            ntop, strport, strerror(errno));
                   1165:                logit("Server listening on %s port %s.", ntop, strport);
                   1166:        }
                   1167:        freeaddrinfo(options.listen_addrs);
                   1168:
                   1169:        if (!num_listen_socks)
                   1170:                fatal("Cannot bind any address.");
                   1171: }
                   1172:
                   1173: /*
                   1174:  * The main TCP accept loop. Note that, for the non-debug case, returns
                   1175:  * from this function are in a forked subprocess.
                   1176:  */
                   1177: static void
                   1178: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
                   1179: {
                   1180:        fd_set *fdset;
                   1181:        int i, j, ret, maxfd;
                   1182:        int key_used = 0, startups = 0;
                   1183:        int startup_p[2] = { -1 , -1 };
                   1184:        struct sockaddr_storage from;
                   1185:        socklen_t fromlen;
                   1186:        pid_t pid;
                   1187:
                   1188:        /* setup fd set for accept */
                   1189:        fdset = NULL;
                   1190:        maxfd = 0;
                   1191:        for (i = 0; i < num_listen_socks; i++)
                   1192:                if (listen_socks[i] > maxfd)
                   1193:                        maxfd = listen_socks[i];
                   1194:        /* pipes connected to unauthenticated childs */
                   1195:        startup_pipes = xcalloc(options.max_startups, sizeof(int));
                   1196:        for (i = 0; i < options.max_startups; i++)
                   1197:                startup_pipes[i] = -1;
                   1198:
                   1199:        /*
                   1200:         * Stay listening for connections until the system crashes or
                   1201:         * the daemon is killed with a signal.
                   1202:         */
                   1203:        for (;;) {
                   1204:                if (received_sighup)
                   1205:                        sighup_restart();
1.462     mmcc     1206:                free(fdset);
1.458     deraadt  1207:                fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1.345     djm      1208:                    sizeof(fd_mask));
                   1209:
                   1210:                for (i = 0; i < num_listen_socks; i++)
                   1211:                        FD_SET(listen_socks[i], fdset);
                   1212:                for (i = 0; i < options.max_startups; i++)
                   1213:                        if (startup_pipes[i] != -1)
                   1214:                                FD_SET(startup_pipes[i], fdset);
                   1215:
                   1216:                /* Wait in select until there is a connection. */
                   1217:                ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1218:                if (ret < 0 && errno != EINTR)
                   1219:                        error("select: %.100s", strerror(errno));
                   1220:                if (received_sigterm) {
                   1221:                        logit("Received signal %d; terminating.",
                   1222:                            (int) received_sigterm);
                   1223:                        close_listen_socks();
1.430     djm      1224:                        if (options.pid_file != NULL)
                   1225:                                unlink(options.pid_file);
1.382     djm      1226:                        exit(received_sigterm == SIGTERM ? 0 : 255);
1.345     djm      1227:                }
                   1228:                if (key_used && key_do_regen) {
                   1229:                        generate_ephemeral_server_key();
                   1230:                        key_used = 0;
                   1231:                        key_do_regen = 0;
                   1232:                }
                   1233:                if (ret < 0)
                   1234:                        continue;
                   1235:
                   1236:                for (i = 0; i < options.max_startups; i++)
                   1237:                        if (startup_pipes[i] != -1 &&
                   1238:                            FD_ISSET(startup_pipes[i], fdset)) {
                   1239:                                /*
                   1240:                                 * the read end of the pipe is ready
                   1241:                                 * if the child has closed the pipe
                   1242:                                 * after successful authentication
                   1243:                                 * or if the child has died
                   1244:                                 */
                   1245:                                close(startup_pipes[i]);
                   1246:                                startup_pipes[i] = -1;
                   1247:                                startups--;
                   1248:                        }
                   1249:                for (i = 0; i < num_listen_socks; i++) {
                   1250:                        if (!FD_ISSET(listen_socks[i], fdset))
                   1251:                                continue;
                   1252:                        fromlen = sizeof(from);
                   1253:                        *newsock = accept(listen_socks[i],
                   1254:                            (struct sockaddr *)&from, &fromlen);
                   1255:                        if (*newsock < 0) {
1.398     markus   1256:                                if (errno != EINTR && errno != EWOULDBLOCK &&
                   1257:                                    errno != ECONNABORTED)
1.389     djm      1258:                                        error("accept: %.100s",
                   1259:                                            strerror(errno));
                   1260:                                if (errno == EMFILE || errno == ENFILE)
                   1261:                                        usleep(100 * 1000);
1.345     djm      1262:                                continue;
                   1263:                        }
                   1264:                        if (unset_nonblock(*newsock) == -1) {
                   1265:                                close(*newsock);
                   1266:                                continue;
                   1267:                        }
                   1268:                        if (drop_connection(startups) == 1) {
                   1269:                                debug("drop connection #%d", startups);
                   1270:                                close(*newsock);
                   1271:                                continue;
                   1272:                        }
                   1273:                        if (pipe(startup_p) == -1) {
                   1274:                                close(*newsock);
                   1275:                                continue;
                   1276:                        }
                   1277:
                   1278:                        if (rexec_flag && socketpair(AF_UNIX,
                   1279:                            SOCK_STREAM, 0, config_s) == -1) {
                   1280:                                error("reexec socketpair: %s",
                   1281:                                    strerror(errno));
                   1282:                                close(*newsock);
                   1283:                                close(startup_p[0]);
                   1284:                                close(startup_p[1]);
                   1285:                                continue;
                   1286:                        }
                   1287:
                   1288:                        for (j = 0; j < options.max_startups; j++)
                   1289:                                if (startup_pipes[j] == -1) {
                   1290:                                        startup_pipes[j] = startup_p[0];
                   1291:                                        if (maxfd < startup_p[0])
                   1292:                                                maxfd = startup_p[0];
                   1293:                                        startups++;
                   1294:                                        break;
                   1295:                                }
                   1296:
                   1297:                        /*
                   1298:                         * Got connection.  Fork a child to handle it, unless
                   1299:                         * we are in debugging mode.
                   1300:                         */
                   1301:                        if (debug_flag) {
                   1302:                                /*
                   1303:                                 * In debugging mode.  Close the listening
                   1304:                                 * socket, and start processing the
                   1305:                                 * connection without forking.
                   1306:                                 */
                   1307:                                debug("Server will not fork when running in debugging mode.");
                   1308:                                close_listen_socks();
                   1309:                                *sock_in = *newsock;
                   1310:                                *sock_out = *newsock;
                   1311:                                close(startup_p[0]);
                   1312:                                close(startup_p[1]);
                   1313:                                startup_pipe = -1;
                   1314:                                pid = getpid();
                   1315:                                if (rexec_flag) {
                   1316:                                        send_rexec_state(config_s[0],
                   1317:                                            &cfg);
                   1318:                                        close(config_s[0]);
                   1319:                                }
                   1320:                                break;
                   1321:                        }
                   1322:
                   1323:                        /*
                   1324:                         * Normal production daemon.  Fork, and have
                   1325:                         * the child process the connection. The
                   1326:                         * parent continues listening.
                   1327:                         */
                   1328:                        if ((pid = fork()) == 0) {
                   1329:                                /*
                   1330:                                 * Child.  Close the listening and
                   1331:                                 * max_startup sockets.  Start using
                   1332:                                 * the accepted socket. Reinitialize
                   1333:                                 * logging (since our pid has changed).
                   1334:                                 * We break out of the loop to handle
                   1335:                                 * the connection.
                   1336:                                 */
                   1337:                                startup_pipe = startup_p[1];
                   1338:                                close_startup_pipes();
                   1339:                                close_listen_socks();
                   1340:                                *sock_in = *newsock;
                   1341:                                *sock_out = *newsock;
                   1342:                                log_init(__progname,
                   1343:                                    options.log_level,
                   1344:                                    options.log_facility,
                   1345:                                    log_stderr);
                   1346:                                if (rexec_flag)
                   1347:                                        close(config_s[0]);
                   1348:                                break;
                   1349:                        }
                   1350:
                   1351:                        /* Parent.  Stay in the loop. */
                   1352:                        if (pid < 0)
                   1353:                                error("fork: %.100s", strerror(errno));
                   1354:                        else
                   1355:                                debug("Forked child %ld.", (long)pid);
                   1356:
                   1357:                        close(startup_p[1]);
                   1358:
                   1359:                        if (rexec_flag) {
                   1360:                                send_rexec_state(config_s[0], &cfg);
                   1361:                                close(config_s[0]);
                   1362:                                close(config_s[1]);
                   1363:                        }
                   1364:
                   1365:                        /*
                   1366:                         * Mark that the key has been used (it
                   1367:                         * was "given" to the child).
                   1368:                         */
                   1369:                        if ((options.protocol & SSH_PROTO_1) &&
                   1370:                            key_used == 0) {
                   1371:                                /* Schedule server key regeneration alarm. */
                   1372:                                signal(SIGALRM, key_regeneration_alarm);
                   1373:                                alarm(options.key_regeneration_time);
                   1374:                                key_used = 1;
                   1375:                        }
                   1376:
                   1377:                        close(*newsock);
                   1378:                }
                   1379:
                   1380:                /* child process check (or debug mode) */
                   1381:                if (num_listen_socks < 0)
                   1382:                        break;
                   1383:        }
                   1384: }
                   1385:
                   1386:
1.65      deraadt  1387: /*
                   1388:  * Main program for the daemon.
                   1389:  */
1.2       provos   1390: int
                   1391: main(int ac, char **av)
1.1       deraadt  1392: {
1.64      markus   1393:        extern char *optarg;
                   1394:        extern int optind;
1.432     djm      1395:        int r, opt, i, j, on = 1;
1.297     avsm     1396:        int sock_in = -1, sock_out = -1, newsock = -1;
1.64      markus   1397:        const char *remote_ip;
                   1398:        int remote_port;
1.447     dtucker  1399:        char *fp, *line, *laddr, *logfile = NULL;
1.345     djm      1400:        int config_s[2] = { -1 , -1 };
1.396     djm      1401:        u_int n;
1.364     markus   1402:        u_int64_t ibytes, obytes;
1.362     dtucker  1403:        mode_t new_umask;
1.278     markus   1404:        Key *key;
1.404     markus   1405:        Key *pubkey;
                   1406:        int keytype;
1.230     provos   1407:        Authctxt *authctxt;
1.391     dtucker  1408:        struct connection_info *connection_info = get_connection_info(0, 0);
1.64      markus   1409:
1.465   ! dtucker  1410:        ssh_malloc_init();      /* must be called before any mallocs */
1.138     markus   1411:        /* Save argv. */
1.64      markus   1412:        saved_argv = av;
1.294     djm      1413:        rexec_argc = ac;
1.313     djm      1414:
                   1415:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1416:        sanitise_stdfd();
1.64      markus   1417:
                   1418:        /* Initialize configuration options to their default values. */
                   1419:        initialize_server_options(&options);
                   1420:
                   1421:        /* Parse command-line arguments. */
1.450     djm      1422:        while ((opt = getopt(ac, av,
                   1423:            "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1.64      markus   1424:                switch (opt) {
1.75      markus   1425:                case '4':
1.305     djm      1426:                        options.address_family = AF_INET;
1.75      markus   1427:                        break;
                   1428:                case '6':
1.305     djm      1429:                        options.address_family = AF_INET6;
1.75      markus   1430:                        break;
1.64      markus   1431:                case 'f':
                   1432:                        config_file_name = optarg;
                   1433:                        break;
1.373     djm      1434:                case 'c':
                   1435:                        if (options.num_host_cert_files >= MAX_HOSTCERTS) {
                   1436:                                fprintf(stderr, "too many host certificates.\n");
                   1437:                                exit(1);
                   1438:                        }
                   1439:                        options.host_cert_files[options.num_host_cert_files++] =
                   1440:                           derelativise_path(optarg);
                   1441:                        break;
1.64      markus   1442:                case 'd':
1.273     markus   1443:                        if (debug_flag == 0) {
1.127     markus   1444:                                debug_flag = 1;
                   1445:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus   1446:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus   1447:                                options.log_level++;
1.64      markus   1448:                        break;
1.135     markus   1449:                case 'D':
                   1450:                        no_daemon_flag = 1;
1.192     lebel    1451:                        break;
1.399     dtucker  1452:                case 'E':
1.459     dtucker  1453:                        logfile = optarg;
1.399     dtucker  1454:                        /* FALLTHROUGH */
1.192     lebel    1455:                case 'e':
                   1456:                        log_stderr = 1;
1.135     markus   1457:                        break;
1.64      markus   1458:                case 'i':
                   1459:                        inetd_flag = 1;
                   1460:                        break;
1.294     djm      1461:                case 'r':
                   1462:                        rexec_flag = 0;
                   1463:                        break;
                   1464:                case 'R':
                   1465:                        rexeced_flag = 1;
                   1466:                        inetd_flag = 1;
                   1467:                        break;
1.64      markus   1468:                case 'Q':
1.158     markus   1469:                        /* ignored */
1.64      markus   1470:                        break;
                   1471:                case 'q':
                   1472:                        options.log_level = SYSLOG_LEVEL_QUIET;
                   1473:                        break;
                   1474:                case 'b':
1.327     deraadt  1475:                        options.server_key_bits = (int)strtonum(optarg, 256,
                   1476:                            32768, NULL);
1.64      markus   1477:                        break;
                   1478:                case 'p':
1.75      markus   1479:                        options.ports_from_cmdline = 1;
1.127     markus   1480:                        if (options.num_ports >= MAX_PORTS) {
                   1481:                                fprintf(stderr, "too many ports.\n");
                   1482:                                exit(1);
                   1483:                        }
1.193     stevesk  1484:                        options.ports[options.num_ports++] = a2port(optarg);
1.366     djm      1485:                        if (options.ports[options.num_ports-1] <= 0) {
1.193     stevesk  1486:                                fprintf(stderr, "Bad port number.\n");
                   1487:                                exit(1);
                   1488:                        }
1.64      markus   1489:                        break;
                   1490:                case 'g':
1.197     stevesk  1491:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                   1492:                                fprintf(stderr, "Invalid login grace time.\n");
                   1493:                                exit(1);
                   1494:                        }
1.64      markus   1495:                        break;
                   1496:                case 'k':
1.197     stevesk  1497:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                   1498:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                   1499:                                exit(1);
                   1500:                        }
1.64      markus   1501:                        break;
                   1502:                case 'h':
1.134     markus   1503:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                   1504:                                fprintf(stderr, "too many host keys.\n");
                   1505:                                exit(1);
                   1506:                        }
1.371     djm      1507:                        options.host_key_files[options.num_host_key_files++] =
                   1508:                           derelativise_path(optarg);
1.64      markus   1509:                        break;
1.203     stevesk  1510:                case 't':
                   1511:                        test_flag = 1;
                   1512:                        break;
1.358     dtucker  1513:                case 'T':
                   1514:                        test_flag = 2;
                   1515:                        break;
                   1516:                case 'C':
1.391     dtucker  1517:                        if (parse_server_match_testspec(connection_info,
                   1518:                            optarg) == -1)
                   1519:                                exit(1);
1.358     dtucker  1520:                        break;
1.125     markus   1521:                case 'u':
1.438     deraadt  1522:                        utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
                   1523:                        if (utmp_len > HOST_NAME_MAX+1) {
1.257     stevesk  1524:                                fprintf(stderr, "Invalid utmp length.\n");
                   1525:                                exit(1);
                   1526:                        }
1.125     markus   1527:                        break;
1.215     markus   1528:                case 'o':
1.283     markus   1529:                        line = xstrdup(optarg);
                   1530:                        if (process_server_config_line(&options, line,
1.391     dtucker  1531:                            "command-line", 0, NULL, NULL) != 0)
1.217     deraadt  1532:                                exit(1);
1.402     djm      1533:                        free(line);
1.215     markus   1534:                        break;
1.64      markus   1535:                case '?':
                   1536:                default:
1.215     markus   1537:                        usage();
                   1538:                        break;
1.64      markus   1539:                }
                   1540:        }
1.294     djm      1541:        if (rexeced_flag || inetd_flag)
                   1542:                rexec_flag = 0;
1.355     mbalmer  1543:        if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1.294     djm      1544:                fatal("sshd re-exec requires execution with an absolute path");
                   1545:        if (rexeced_flag)
1.296     djm      1546:                closefrom(REEXEC_MIN_FREE_FD);
                   1547:        else
                   1548:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294     djm      1549:
1.426     markus   1550: #ifdef WITH_OPENSSL
1.379     djm      1551:        OpenSSL_add_all_algorithms();
1.426     markus   1552: #endif
1.64      markus   1553:
1.399     dtucker  1554:        /* If requested, redirect the logs to the specified logfile. */
1.459     dtucker  1555:        if (logfile != NULL)
1.399     dtucker  1556:                log_redirect_stderr_to(logfile);
1.75      markus   1557:        /*
                   1558:         * Force logging to stderr until we have loaded the private host
                   1559:         * key (unless started from inetd)
                   1560:         */
1.138     markus   1561:        log_init(__progname,
1.224     markus   1562:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1563:            SYSLOG_LEVEL_INFO : options.log_level,
                   1564:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1565:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1566:            log_stderr || !inetd_flag);
1.75      markus   1567:
1.294     djm      1568:        sensitive_data.server_key = NULL;
                   1569:        sensitive_data.ssh1_host_key = NULL;
                   1570:        sensitive_data.have_ssh1_key = 0;
                   1571:        sensitive_data.have_ssh2_key = 0;
                   1572:
1.358     dtucker  1573:        /*
                   1574:         * If we're doing an extended config test, make sure we have all of
                   1575:         * the parameters we need.  If we're not doing an extended test,
                   1576:         * do not silently ignore connection test params.
                   1577:         */
1.391     dtucker  1578:        if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1.358     dtucker  1579:                fatal("user, host and addr are all required when testing "
                   1580:                   "Match configs");
1.391     dtucker  1581:        if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1.358     dtucker  1582:                fatal("Config test connection parameter (-C) provided without "
                   1583:                   "test mode (-T)");
                   1584:
1.294     djm      1585:        /* Fetch our configuration */
                   1586:        buffer_init(&cfg);
                   1587:        if (rexeced_flag)
1.296     djm      1588:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1.448     djm      1589:        else if (strcasecmp(config_file_name, "none") != 0)
1.294     djm      1590:                load_server_config(config_file_name, &cfg);
                   1591:
1.337     dtucker  1592:        parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.391     dtucker  1593:            &cfg, NULL);
1.64      markus   1594:
                   1595:        /* Fill in default values for those options not explicitly set. */
                   1596:        fill_default_server_options(&options);
1.350     dtucker  1597:
                   1598:        /* challenge-response is implemented via keyboard interactive */
                   1599:        if (options.challenge_response_authentication)
                   1600:                options.kbd_interactive_authentication = 1;
1.395     djm      1601:
                   1602:        /* Check that options are sensible */
                   1603:        if (options.authorized_keys_command_user == NULL &&
                   1604:            (options.authorized_keys_command != NULL &&
                   1605:            strcasecmp(options.authorized_keys_command, "none") != 0))
                   1606:                fatal("AuthorizedKeysCommand set without "
                   1607:                    "AuthorizedKeysCommandUser");
1.449     djm      1608:        if (options.authorized_principals_command_user == NULL &&
                   1609:            (options.authorized_principals_command != NULL &&
                   1610:            strcasecmp(options.authorized_principals_command, "none") != 0))
                   1611:                fatal("AuthorizedPrincipalsCommand set without "
                   1612:                    "AuthorizedPrincipalsCommandUser");
1.396     djm      1613:
                   1614:        /*
                   1615:         * Check whether there is any path through configured auth methods.
                   1616:         * Unfortunately it is not possible to verify this generally before
                   1617:         * daemonisation in the presence of Match block, but this catches
                   1618:         * and warns for trivial misconfigurations that could break login.
                   1619:         */
                   1620:        if (options.num_auth_methods != 0) {
                   1621:                if ((options.protocol & SSH_PROTO_1))
                   1622:                        fatal("AuthenticationMethods is not supported with "
                   1623:                            "SSH protocol 1");
                   1624:                for (n = 0; n < options.num_auth_methods; n++) {
                   1625:                        if (auth2_methods_valid(options.auth_methods[n],
                   1626:                            1) == 0)
                   1627:                                break;
                   1628:                }
                   1629:                if (n >= options.num_auth_methods)
                   1630:                        fatal("AuthenticationMethods cannot be satisfied by "
                   1631:                            "enabled authentication methods");
                   1632:        }
1.305     djm      1633:
1.370     dtucker  1634:        /* set default channel AF */
1.305     djm      1635:        channel_set_af(options.address_family);
1.64      markus   1636:
                   1637:        /* Check that there are no remaining arguments. */
                   1638:        if (optind < ac) {
                   1639:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1640:                exit(1);
                   1641:        }
                   1642:
1.397     dtucker  1643:        debug("sshd version %s, %s", SSH_VERSION,
1.426     markus   1644: #ifdef WITH_OPENSSL
                   1645:            SSLeay_version(SSLEAY_VERSION)
                   1646: #else
                   1647:            "without OpenSSL"
                   1648: #endif
                   1649:        );
1.64      markus   1650:
1.404     markus   1651:        /* load host keys */
1.329     djm      1652:        sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.255     deraadt  1653:            sizeof(Key *));
1.404     markus   1654:        sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
                   1655:            sizeof(Key *));
                   1656:
                   1657:        if (options.host_key_agent) {
                   1658:                if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
                   1659:                        setenv(SSH_AUTHSOCKET_ENV_NAME,
                   1660:                            options.host_key_agent, 1);
1.433     djm      1661:                if ((r = ssh_get_authentication_socket(NULL)) == 0)
                   1662:                        have_agent = 1;
                   1663:                else
                   1664:                        error("Could not connect to agent \"%s\": %s",
                   1665:                            options.host_key_agent, ssh_err(r));
1.404     markus   1666:        }
1.134     markus   1667:
1.217     deraadt  1668:        for (i = 0; i < options.num_host_key_files; i++) {
1.430     djm      1669:                if (options.host_key_files[i] == NULL)
                   1670:                        continue;
1.179     markus   1671:                key = key_load_private(options.host_key_files[i], "", NULL);
1.404     markus   1672:                pubkey = key_load_public(options.host_key_files[i], NULL);
1.439     djm      1673:                if (pubkey == NULL && key != NULL)
                   1674:                        pubkey = key_demote(key);
1.179     markus   1675:                sensitive_data.host_keys[i] = key;
1.404     markus   1676:                sensitive_data.host_pubkeys[i] = pubkey;
                   1677:
1.443     djm      1678:                if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
                   1679:                    have_agent) {
                   1680:                        debug("will rely on agent for hostkey %s",
                   1681:                            options.host_key_files[i]);
1.404     markus   1682:                        keytype = pubkey->type;
                   1683:                } else if (key != NULL) {
                   1684:                        keytype = key->type;
                   1685:                } else {
1.195     markus   1686:                        error("Could not load host key: %s",
                   1687:                            options.host_key_files[i]);
1.179     markus   1688:                        sensitive_data.host_keys[i] = NULL;
1.404     markus   1689:                        sensitive_data.host_pubkeys[i] = NULL;
1.134     markus   1690:                        continue;
                   1691:                }
1.404     markus   1692:
                   1693:                switch (keytype) {
1.134     markus   1694:                case KEY_RSA1:
                   1695:                        sensitive_data.ssh1_host_key = key;
                   1696:                        sensitive_data.have_ssh1_key = 1;
                   1697:                        break;
                   1698:                case KEY_RSA:
                   1699:                case KEY_DSA:
1.378     djm      1700:                case KEY_ECDSA:
1.412     markus   1701:                case KEY_ED25519:
1.441     djm      1702:                        if (have_agent || key != NULL)
                   1703:                                sensitive_data.have_ssh2_key = 1;
1.134     markus   1704:                        break;
                   1705:                }
1.441     djm      1706:                if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
                   1707:                    SSH_FP_DEFAULT)) == NULL)
                   1708:                        fatal("sshkey_fingerprint failed");
                   1709:                debug("%s host key #%d: %s %s",
1.443     djm      1710:                    key ? "private" : "agent", i, keytype == KEY_RSA1 ?
1.441     djm      1711:                    sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
                   1712:                free(fp);
1.134     markus   1713:        }
                   1714:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264     itojun   1715:                logit("Disabling protocol version 1. Could not load host key");
1.108     markus   1716:                options.protocol &= ~SSH_PROTO_1;
                   1717:        }
1.134     markus   1718:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264     itojun   1719:                logit("Disabling protocol version 2. Could not load host key");
1.134     markus   1720:                options.protocol &= ~SSH_PROTO_2;
1.108     markus   1721:        }
1.162     stevesk  1722:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264     itojun   1723:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1724:                exit(1);
                   1725:        }
                   1726:
1.373     djm      1727:        /*
                   1728:         * Load certificates. They are stored in an array at identical
                   1729:         * indices to the public keys that they relate to.
                   1730:         */
                   1731:        sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
                   1732:            sizeof(Key *));
                   1733:        for (i = 0; i < options.num_host_key_files; i++)
                   1734:                sensitive_data.host_certificates[i] = NULL;
                   1735:
                   1736:        for (i = 0; i < options.num_host_cert_files; i++) {
1.430     djm      1737:                if (options.host_cert_files[i] == NULL)
                   1738:                        continue;
1.373     djm      1739:                key = key_load_public(options.host_cert_files[i], NULL);
                   1740:                if (key == NULL) {
                   1741:                        error("Could not load host certificate: %s",
                   1742:                            options.host_cert_files[i]);
                   1743:                        continue;
                   1744:                }
                   1745:                if (!key_is_cert(key)) {
                   1746:                        error("Certificate file is not a certificate: %s",
                   1747:                            options.host_cert_files[i]);
                   1748:                        key_free(key);
                   1749:                        continue;
                   1750:                }
                   1751:                /* Find matching private key */
                   1752:                for (j = 0; j < options.num_host_key_files; j++) {
                   1753:                        if (key_equal_public(key,
                   1754:                            sensitive_data.host_keys[j])) {
                   1755:                                sensitive_data.host_certificates[j] = key;
                   1756:                                break;
                   1757:                        }
                   1758:                }
                   1759:                if (j >= options.num_host_key_files) {
                   1760:                        error("No matching private key for certificate: %s",
                   1761:                            options.host_cert_files[i]);
                   1762:                        key_free(key);
                   1763:                        continue;
                   1764:                }
                   1765:                sensitive_data.host_certificates[j] = key;
                   1766:                debug("host certificate: #%d type %d %s", j, key->type,
                   1767:                    key_type(key));
                   1768:        }
1.426     markus   1769:
                   1770: #ifdef WITH_SSH1
1.108     markus   1771:        /* Check certain values for sanity. */
                   1772:        if (options.protocol & SSH_PROTO_1) {
1.453     djm      1773:                if (options.server_key_bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
                   1774:                    options.server_key_bits > OPENSSL_RSA_MAX_MODULUS_BITS) {
1.108     markus   1775:                        fprintf(stderr, "Bad server key size.\n");
                   1776:                        exit(1);
                   1777:                }
                   1778:                /*
                   1779:                 * Check that server and host key lengths differ sufficiently. This
                   1780:                 * is necessary to make double encryption work with rsaref. Oh, I
                   1781:                 * hate software patents. I dont know if this can go? Niels
                   1782:                 */
                   1783:                if (options.server_key_bits >
1.250     deraadt  1784:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
                   1785:                    SSH_KEY_BITS_RESERVED && options.server_key_bits <
                   1786:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1787:                    SSH_KEY_BITS_RESERVED) {
1.108     markus   1788:                        options.server_key_bits =
1.250     deraadt  1789:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1790:                            SSH_KEY_BITS_RESERVED;
1.108     markus   1791:                        debug("Forcing server key to %d bits to make it differ from host key.",
                   1792:                            options.server_key_bits);
                   1793:                }
1.244     markus   1794:        }
1.426     markus   1795: #endif
1.244     markus   1796:
                   1797:        if (use_privsep) {
                   1798:                struct stat st;
                   1799:
1.327     deraadt  1800:                if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244     markus   1801:                        fatal("Privilege separation user %s does not exist",
                   1802:                            SSH_PRIVSEP_USER);
                   1803:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1804:                    (S_ISDIR(st.st_mode) == 0))
                   1805:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1806:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1807:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1808:                        fatal("%s must be owned by root and not group or "
                   1809:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358     dtucker  1810:        }
                   1811:
                   1812:        if (test_flag > 1) {
1.391     dtucker  1813:                if (server_match_spec_complete(connection_info) == 1)
                   1814:                        parse_server_match_config(&options, connection_info);
1.358     dtucker  1815:                dump_config(&options);
1.108     markus   1816:        }
1.203     stevesk  1817:
                   1818:        /* Configuration looks good, so exit if in test mode. */
                   1819:        if (test_flag)
                   1820:                exit(0);
1.108     markus   1821:
1.294     djm      1822:        if (rexec_flag) {
1.329     djm      1823:                rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.294     djm      1824:                for (i = 0; i < rexec_argc; i++) {
                   1825:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1826:                        rexec_argv[i] = saved_argv[i];
                   1827:                }
                   1828:                rexec_argv[rexec_argc] = "-R";
                   1829:                rexec_argv[rexec_argc + 1] = NULL;
                   1830:        }
1.362     dtucker  1831:
                   1832:        /* Ensure that umask disallows at least group and world write */
                   1833:        new_umask = umask(0077) | 0022;
                   1834:        (void) umask(new_umask);
1.294     djm      1835:
1.108     markus   1836:        /* Initialize the log (it is reinitialized below in case we forked). */
1.306     dtucker  1837:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1838:                log_stderr = 1;
1.138     markus   1839:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1840:
1.108     markus   1841:        /*
                   1842:         * If not in debugging mode, and not started from inetd, disconnect
                   1843:         * from the controlling terminal, and fork.  The original process
                   1844:         * exits.
                   1845:         */
1.135     markus   1846:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.64      markus   1847:                int fd;
1.345     djm      1848:
1.64      markus   1849:                if (daemon(0, 0) < 0)
                   1850:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1851:
                   1852:                /* Disconnect from the controlling tty. */
1.165     itojun   1853:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus   1854:                if (fd >= 0) {
                   1855:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                   1856:                        close(fd);
                   1857:                }
                   1858:        }
                   1859:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1860:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1861:
                   1862:        /* Chdir to the root directory so that the current disk can be
                   1863:           unmounted if desired. */
1.401     dtucker  1864:        if (chdir("/") == -1)
                   1865:                error("chdir(\"/\"): %s", strerror(errno));
1.217     deraadt  1866:
1.178     markus   1867:        /* ignore SIGPIPE */
                   1868:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1869:
1.345     djm      1870:        /* Get a connection, either from inetd or a listening TCP socket */
1.64      markus   1871:        if (inetd_flag) {
1.345     djm      1872:                server_accept_inetd(&sock_in, &sock_out);
1.64      markus   1873:        } else {
1.345     djm      1874:                server_listen();
1.75      markus   1875:
1.201     markus   1876:                if (options.protocol & SSH_PROTO_1)
                   1877:                        generate_ephemeral_server_key();
                   1878:
                   1879:                signal(SIGHUP, sighup_handler);
1.345     djm      1880:                signal(SIGCHLD, main_sigchld_handler);
1.201     markus   1881:                signal(SIGTERM, sigterm_handler);
                   1882:                signal(SIGQUIT, sigterm_handler);
                   1883:
1.345     djm      1884:                /*
                   1885:                 * Write out the pid file after the sigterm handler
                   1886:                 * is setup and the listen sockets are bound
                   1887:                 */
1.430     djm      1888:                if (options.pid_file != NULL && !debug_flag) {
1.345     djm      1889:                        FILE *f = fopen(options.pid_file, "w");
1.201     markus   1890:
1.270     djm      1891:                        if (f == NULL) {
                   1892:                                error("Couldn't create pid file \"%s\": %s",
                   1893:                                    options.pid_file, strerror(errno));
                   1894:                        } else {
1.245     mpech    1895:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1896:                                fclose(f);
                   1897:                        }
                   1898:                }
                   1899:
1.345     djm      1900:                /* Accept a connection and return in a forked child */
                   1901:                server_accept_loop(&sock_in, &sock_out,
                   1902:                    &newsock, config_s);
1.1       deraadt  1903:        }
                   1904:
1.64      markus   1905:        /* This is the child processing a new connection. */
1.288     markus   1906:        setproctitle("%s", "[accepted]");
1.294     djm      1907:
1.300     markus   1908:        /*
                   1909:         * Create a new session and process group since the 4.4BSD
                   1910:         * setlogin() affects the entire process group.  We don't
                   1911:         * want the child to be able to affect the parent.
                   1912:         */
                   1913:        if (!debug_flag && !inetd_flag && setsid() < 0)
                   1914:                error("setsid: %.100s", strerror(errno));
                   1915:
1.294     djm      1916:        if (rexec_flag) {
                   1917:                int fd;
                   1918:
1.296     djm      1919:                debug("rexec start 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:                dup2(newsock, STDIN_FILENO);
                   1922:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1923:                if (startup_pipe == -1)
1.296     djm      1924:                        close(REEXEC_STARTUP_PIPE_FD);
1.407     djm      1925:                else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1.296     djm      1926:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.407     djm      1927:                        close(startup_pipe);
                   1928:                        startup_pipe = REEXEC_STARTUP_PIPE_FD;
                   1929:                }
1.294     djm      1930:
1.296     djm      1931:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294     djm      1932:                close(config_s[1]);
1.296     djm      1933:
1.294     djm      1934:                execv(rexec_argv[0], rexec_argv);
                   1935:
                   1936:                /* Reexec has failed, fall back and continue */
                   1937:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296     djm      1938:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294     djm      1939:                log_init(__progname, options.log_level,
                   1940:                    options.log_facility, log_stderr);
                   1941:
                   1942:                /* Clean up fds */
1.296     djm      1943:                close(REEXEC_CONFIG_PASS_FD);
                   1944:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294     djm      1945:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1946:                        dup2(fd, STDIN_FILENO);
                   1947:                        dup2(fd, STDOUT_FILENO);
                   1948:                        if (fd > STDERR_FILENO)
                   1949:                                close(fd);
                   1950:                }
1.296     djm      1951:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1952:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1953:        }
1.372     djm      1954:
                   1955:        /* Executed child processes don't need these. */
                   1956:        fcntl(sock_out, F_SETFD, FD_CLOEXEC);
                   1957:        fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64      markus   1958:
1.66      markus   1959:        /*
                   1960:         * Disable the key regeneration alarm.  We will not regenerate the
                   1961:         * key since we are no longer in a position to give it to anyone. We
                   1962:         * will not restart on SIGHUP since it no longer makes sense.
                   1963:         */
1.64      markus   1964:        alarm(0);
                   1965:        signal(SIGALRM, SIG_DFL);
                   1966:        signal(SIGHUP, SIG_DFL);
                   1967:        signal(SIGTERM, SIG_DFL);
                   1968:        signal(SIGQUIT, SIG_DFL);
                   1969:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1970:
1.66      markus   1971:        /*
                   1972:         * Register our connection.  This turns encryption off because we do
                   1973:         * not have a key.
                   1974:         */
1.64      markus   1975:        packet_set_connection(sock_in, sock_out);
1.312     markus   1976:        packet_set_server();
1.309     djm      1977:
                   1978:        /* Set SO_KEEPALIVE if requested. */
                   1979:        if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
                   1980:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
                   1981:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1       deraadt  1982:
1.310     markus   1983:        if ((remote_port = get_remote_port()) < 0) {
                   1984:                debug("get_remote_port failed");
                   1985:                cleanup_exit(255);
                   1986:        }
1.316     dtucker  1987:
                   1988:        /*
                   1989:         * We use get_canonical_hostname with usedns = 0 instead of
                   1990:         * get_remote_ipaddr here so IP options will be checked.
                   1991:         */
1.331     markus   1992:        (void) get_canonical_hostname(0);
                   1993:        /*
                   1994:         * The rest of the code depends on the fact that
                   1995:         * get_remote_ipaddr() caches the remote ip, even if
                   1996:         * the socket goes away.
                   1997:         */
                   1998:        remote_ip = get_remote_ipaddr();
1.209     markus   1999:
1.64      markus   2000:        /* Log the connection. */
1.447     dtucker  2001:        laddr = get_local_ipaddr(sock_in);
1.409     djm      2002:        verbose("Connection from %s port %d on %s port %d",
1.447     dtucker  2003:            remote_ip, remote_port, laddr,  get_local_port());
                   2004:        free(laddr);
1.1       deraadt  2005:
1.66      markus   2006:        /*
1.317     djm      2007:         * We don't want to listen forever unless the other side
1.66      markus   2008:         * successfully authenticates itself.  So we set up an alarm which is
                   2009:         * cleared after successful authentication.  A limit of zero
1.317     djm      2010:         * indicates no limit. Note that we don't set the alarm in debugging
1.66      markus   2011:         * mode; it is just annoying to have the server exit just when you
                   2012:         * are about to discover the bug.
                   2013:         */
1.64      markus   2014:        signal(SIGALRM, grace_alarm_handler);
                   2015:        if (!debug_flag)
                   2016:                alarm(options.login_grace_time);
                   2017:
1.96      markus   2018:        sshd_exchange_identification(sock_in, sock_out);
1.353     dtucker  2019:
                   2020:        /* In inetd mode, generate ephemeral key only for proto 1 connections */
                   2021:        if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
                   2022:                generate_ephemeral_server_key();
1.275     markus   2023:
1.64      markus   2024:        packet_set_nonblocking();
1.1       deraadt  2025:
1.278     markus   2026:        /* allocate authentication context */
1.329     djm      2027:        authctxt = xcalloc(1, sizeof(*authctxt));
1.278     markus   2028:
                   2029:        /* XXX global for cleanup, access from other modules */
                   2030:        the_authctxt = authctxt;
                   2031:
1.307     otto     2032:        /* prepare buffer to collect messages to display to user after login */
                   2033:        buffer_init(&loginmsg);
1.374     dtucker  2034:        auth_debug_reset();
1.307     otto     2035:
1.404     markus   2036:        if (use_privsep) {
1.278     markus   2037:                if (privsep_preauth(authctxt) == 1)
1.237     markus   2038:                        goto authenticated;
1.432     djm      2039:        } else if (compat20 && have_agent) {
                   2040:                if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
                   2041:                        error("Unable to get agent socket: %s", ssh_err(r));
1.433     djm      2042:                        have_agent = 0;
1.432     djm      2043:                }
                   2044:        }
1.231     provos   2045:
1.77      markus   2046:        /* perform the key exchange */
                   2047:        /* authenticate user and start session */
1.98      markus   2048:        if (compat20) {
                   2049:                do_ssh2_kex();
1.278     markus   2050:                do_authentication2(authctxt);
1.98      markus   2051:        } else {
1.426     markus   2052: #ifdef WITH_SSH1
1.98      markus   2053:                do_ssh1_kex();
1.278     markus   2054:                do_authentication(authctxt);
1.426     markus   2055: #else
                   2056:                fatal("ssh1 not supported");
                   2057: #endif
1.98      markus   2058:        }
1.237     markus   2059:        /*
                   2060:         * If we use privilege separation, the unprivileged child transfers
                   2061:         * the current keystate and exits
                   2062:         */
                   2063:        if (use_privsep) {
1.242     mouring  2064:                mm_send_keystate(pmonitor);
1.231     provos   2065:                exit(0);
1.237     markus   2066:        }
1.231     provos   2067:
                   2068:  authenticated:
1.318     djm      2069:        /*
                   2070:         * Cancel the alarm we set to limit the time taken for
                   2071:         * authentication.
                   2072:         */
                   2073:        alarm(0);
                   2074:        signal(SIGALRM, SIG_DFL);
1.347     markus   2075:        authctxt->authenticated = 1;
1.318     djm      2076:        if (startup_pipe != -1) {
                   2077:                close(startup_pipe);
                   2078:                startup_pipe = -1;
                   2079:        }
                   2080:
1.234     markus   2081:        /*
1.231     provos   2082:         * In privilege separation, we fork another child and prepare
                   2083:         * file descriptor passing.
                   2084:         */
                   2085:        if (use_privsep) {
1.237     markus   2086:                privsep_postauth(authctxt);
                   2087:                /* the monitor process [priv] will not return */
1.231     provos   2088:                if (!compat20)
                   2089:                        destroy_sensitive_data();
                   2090:        }
1.360     dtucker  2091:
                   2092:        packet_set_timeout(options.client_alive_interval,
                   2093:            options.client_alive_count_max);
1.439     djm      2094:
                   2095:        /* Try to send all our hostkeys to the client */
                   2096:        if (compat20)
                   2097:                notify_hostkeys(active_state);
1.230     provos   2098:
1.278     markus   2099:        /* Start session. */
1.230     provos   2100:        do_authenticated(authctxt);
                   2101:
1.64      markus   2102:        /* The connection has been terminated. */
1.434     markus   2103:        packet_get_bytes(&ibytes, &obytes);
1.381     djm      2104:        verbose("Transferred: sent %llu, received %llu bytes",
                   2105:            (unsigned long long)obytes, (unsigned long long)ibytes);
1.364     markus   2106:
                   2107:        verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.64      markus   2108:        packet_close();
1.231     provos   2109:
                   2110:        if (use_privsep)
                   2111:                mm_terminate();
                   2112:
1.64      markus   2113:        exit(0);
1.1       deraadt  2114: }
                   2115:
1.426     markus   2116: #ifdef WITH_SSH1
1.65      deraadt  2117: /*
1.229     markus   2118:  * Decrypt session_key_int using our private server key and private host key
                   2119:  * (key with larger modulus first).
                   2120:  */
1.231     provos   2121: int
1.229     markus   2122: ssh1_session_key(BIGNUM *session_key_int)
                   2123: {
                   2124:        int rsafail = 0;
                   2125:
1.327     deraadt  2126:        if (BN_cmp(sensitive_data.server_key->rsa->n,
                   2127:            sensitive_data.ssh1_host_key->rsa->n) > 0) {
1.229     markus   2128:                /* Server key has bigger modulus. */
                   2129:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1.327     deraadt  2130:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   2131:                    SSH_KEY_BITS_RESERVED) {
                   2132:                        fatal("do_connection: %s: "
                   2133:                            "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1.229     markus   2134:                            get_remote_ipaddr(),
                   2135:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2136:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   2137:                            SSH_KEY_BITS_RESERVED);
                   2138:                }
                   2139:                if (rsa_private_decrypt(session_key_int, session_key_int,
1.427     djm      2140:                    sensitive_data.server_key->rsa) != 0)
1.229     markus   2141:                        rsafail++;
                   2142:                if (rsa_private_decrypt(session_key_int, session_key_int,
1.427     djm      2143:                    sensitive_data.ssh1_host_key->rsa) != 0)
1.229     markus   2144:                        rsafail++;
                   2145:        } else {
                   2146:                /* Host key has bigger modulus (or they are equal). */
                   2147:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1.327     deraadt  2148:                    BN_num_bits(sensitive_data.server_key->rsa->n) +
                   2149:                    SSH_KEY_BITS_RESERVED) {
                   2150:                        fatal("do_connection: %s: "
                   2151:                            "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1.229     markus   2152:                            get_remote_ipaddr(),
                   2153:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   2154:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2155:                            SSH_KEY_BITS_RESERVED);
                   2156:                }
                   2157:                if (rsa_private_decrypt(session_key_int, session_key_int,
1.427     djm      2158:                    sensitive_data.ssh1_host_key->rsa) != 0)
1.229     markus   2159:                        rsafail++;
                   2160:                if (rsa_private_decrypt(session_key_int, session_key_int,
1.427     djm      2161:                    sensitive_data.server_key->rsa) != 0)
1.229     markus   2162:                        rsafail++;
                   2163:        }
                   2164:        return (rsafail);
                   2165: }
1.426     markus   2166:
1.229     markus   2167: /*
1.77      markus   2168:  * SSH1 key exchange
1.65      deraadt  2169:  */
1.200     itojun   2170: static void
1.142     markus   2171: do_ssh1_kex(void)
1.1       deraadt  2172: {
1.64      markus   2173:        int i, len;
1.159     markus   2174:        int rsafail = 0;
1.431     tedu     2175:        BIGNUM *session_key_int, *fake_key_int, *real_key_int;
1.140     markus   2176:        u_char session_key[SSH_SESSION_KEY_LENGTH];
1.431     tedu     2177:        u_char fake_key_bytes[4096 / 8];
                   2178:        size_t fake_key_len;
1.140     markus   2179:        u_char cookie[8];
                   2180:        u_int cipher_type, auth_mask, protocol_flags;
1.64      markus   2181:
1.66      markus   2182:        /*
                   2183:         * Generate check bytes that the client must send back in the user
                   2184:         * packet in order for it to be accepted; this is used to defy ip
                   2185:         * spoofing attacks.  Note that this only works against somebody
                   2186:         * doing IP spoofing from a remote machine; any machine on the local
                   2187:         * network can still see outgoing packets and catch the random
                   2188:         * cookie.  This only affects rhosts authentication, and this is one
                   2189:         * of the reasons why it is inherently insecure.
                   2190:         */
1.356     djm      2191:        arc4random_buf(cookie, sizeof(cookie));
1.64      markus   2192:
1.66      markus   2193:        /*
                   2194:         * Send our public key.  We include in the packet 64 bits of random
                   2195:         * data that must be matched in the reply in order to prevent IP
                   2196:         * spoofing.
                   2197:         */
1.64      markus   2198:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   2199:        for (i = 0; i < 8; i++)
1.77      markus   2200:                packet_put_char(cookie[i]);
1.64      markus   2201:
                   2202:        /* Store our public server RSA key. */
1.134     markus   2203:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   2204:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   2205:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   2206:
                   2207:        /* Store our public host RSA key. */
1.134     markus   2208:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   2209:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   2210:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   2211:
                   2212:        /* Put protocol flags. */
                   2213:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   2214:
                   2215:        /* Declare which ciphers we support. */
1.131     markus   2216:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   2217:
                   2218:        /* Declare supported authentication types. */
                   2219:        auth_mask = 0;
                   2220:        if (options.rhosts_rsa_authentication)
                   2221:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   2222:        if (options.rsa_authentication)
                   2223:                auth_mask |= 1 << SSH_AUTH_RSA;
1.196     markus   2224:        if (options.challenge_response_authentication == 1)
1.64      markus   2225:                auth_mask |= 1 << SSH_AUTH_TIS;
                   2226:        if (options.password_authentication)
                   2227:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   2228:        packet_put_int(auth_mask);
                   2229:
                   2230:        /* Send the packet and wait for it to be sent. */
                   2231:        packet_send();
                   2232:        packet_write_wait();
                   2233:
1.134     markus   2234:        debug("Sent %d bit server key and %d bit host key.",
                   2235:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2236:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   2237:
                   2238:        /* Read clients reply (cipher type and session key). */
1.222     markus   2239:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   2240:
1.69      markus   2241:        /* Get cipher type and check whether we accept this. */
1.64      markus   2242:        cipher_type = packet_get_char();
1.69      markus   2243:
1.131     markus   2244:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   2245:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   2246:
                   2247:        /* Get check bytes from the packet.  These must match those we
                   2248:           sent earlier with the public key packet. */
                   2249:        for (i = 0; i < 8; i++)
1.77      markus   2250:                if (cookie[i] != packet_get_char())
1.64      markus   2251:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   2252:
                   2253:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   2254:
                   2255:        /* Get the encrypted integer. */
1.431     tedu     2256:        if ((real_key_int = BN_new()) == NULL)
1.218     markus   2257:                fatal("do_ssh1_kex: BN_new failed");
1.431     tedu     2258:        packet_get_bignum(real_key_int);
1.64      markus   2259:
                   2260:        protocol_flags = packet_get_int();
                   2261:        packet_set_protocol_flags(protocol_flags);
1.220     markus   2262:        packet_check_eom();
1.64      markus   2263:
1.431     tedu     2264:        /* Setup a fake key in case RSA decryption fails */
                   2265:        if ((fake_key_int = BN_new()) == NULL)
                   2266:                fatal("do_ssh1_kex: BN_new failed");
                   2267:        fake_key_len = BN_num_bytes(real_key_int);
                   2268:        if (fake_key_len > sizeof(fake_key_bytes))
                   2269:                fake_key_len = sizeof(fake_key_bytes);
                   2270:        arc4random_buf(fake_key_bytes, fake_key_len);
                   2271:        if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
                   2272:                fatal("do_ssh1_kex: BN_bin2bn failed");
                   2273:
                   2274:        /* Decrypt real_key_int using host/server keys */
                   2275:        rsafail = PRIVSEP(ssh1_session_key(real_key_int));
                   2276:        /* If decryption failed, use the fake key. Else, the real key. */
                   2277:        if (rsafail)
                   2278:                session_key_int = fake_key_int;
                   2279:        else
                   2280:                session_key_int = real_key_int;
1.231     provos   2281:
1.66      markus   2282:        /*
                   2283:         * Extract session key from the decrypted integer.  The key is in the
                   2284:         * least significant 256 bits of the integer; the first byte of the
                   2285:         * key is in the highest bits.
                   2286:         */
1.431     tedu     2287:        (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   2288:        len = BN_num_bytes(session_key_int);
                   2289:        if (len < 0 || (u_int)len > sizeof(session_key)) {
                   2290:                error("do_ssh1_kex: bad session key len from %s: "
                   2291:                    "session_key_int %d > sizeof(session_key) %lu",
                   2292:                    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
                   2293:                rsafail++;
                   2294:        } else {
                   2295:                explicit_bzero(session_key, sizeof(session_key));
                   2296:                BN_bn2bin(session_key_int,
                   2297:                    session_key + sizeof(session_key) - len);
                   2298:
                   2299:                derive_ssh1_session_id(
                   2300:                    sensitive_data.ssh1_host_key->rsa->n,
                   2301:                    sensitive_data.server_key->rsa->n,
                   2302:                    cookie, session_id);
                   2303:                /*
                   2304:                 * Xor the first 16 bytes of the session key with the
                   2305:                 * session id.
                   2306:                 */
1.170     markus   2307:                for (i = 0; i < 16; i++)
1.431     tedu     2308:                        session_key[i] ^= session_id[i];
1.159     markus   2309:        }
1.431     tedu     2310:
1.231     provos   2311:        /* Destroy the private and public keys. No longer. */
1.169     markus   2312:        destroy_sensitive_data();
                   2313:
1.231     provos   2314:        if (use_privsep)
                   2315:                mm_ssh1_session_id(session_id);
                   2316:
1.77      markus   2317:        /* Destroy the decrypted integer.  It is no longer needed. */
1.431     tedu     2318:        BN_clear_free(real_key_int);
                   2319:        BN_clear_free(fake_key_int);
1.64      markus   2320:
                   2321:        /* Set the session key.  From this on all communications will be encrypted. */
                   2322:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   2323:
                   2324:        /* Destroy our copy of the session key.  It is no longer needed. */
1.418     djm      2325:        explicit_bzero(session_key, sizeof(session_key));
1.64      markus   2326:
                   2327:        debug("Received session key; encryption turned on.");
                   2328:
1.243     deraadt  2329:        /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1.64      markus   2330:        packet_start(SSH_SMSG_SUCCESS);
                   2331:        packet_send();
                   2332:        packet_write_wait();
1.98      markus   2333: }
1.426     markus   2334: #endif
1.98      markus   2335:
1.435     markus   2336: int
                   2337: sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
1.461     markus   2338:     const u_char *data, size_t dlen, const char *alg, u_int flag)
1.404     markus   2339: {
1.432     djm      2340:        int r;
1.435     markus   2341:        u_int xxx_slen, xxx_dlen = dlen;
1.432     djm      2342:
1.404     markus   2343:        if (privkey) {
1.461     markus   2344:                if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
                   2345:                    alg) < 0))
1.404     markus   2346:                        fatal("%s: key_sign failed", __func__);
1.435     markus   2347:                if (slen)
                   2348:                        *slen = xxx_slen;
1.404     markus   2349:        } else if (use_privsep) {
1.461     markus   2350:                if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
                   2351:                    alg) < 0)
1.404     markus   2352:                        fatal("%s: pubkey_sign failed", __func__);
1.435     markus   2353:                if (slen)
                   2354:                        *slen = xxx_slen;
1.404     markus   2355:        } else {
1.435     markus   2356:                if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
1.461     markus   2357:                    data, dlen, alg, datafellows)) != 0)
1.432     djm      2358:                        fatal("%s: ssh_agent_sign failed: %s",
                   2359:                            __func__, ssh_err(r));
1.404     markus   2360:        }
1.435     markus   2361:        return 0;
1.404     markus   2362: }
                   2363:
1.452     djm      2364: /* SSH2 key exchange */
1.200     itojun   2365: static void
1.142     markus   2366: do_ssh2_kex(void)
1.98      markus   2367: {
1.422     markus   2368:        char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
1.435     markus   2369:        struct kex *kex;
1.437     markus   2370:        int r;
1.102     markus   2371:
1.457     djm      2372:        myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
                   2373:            options.kex_algorithms);
                   2374:        myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
                   2375:            options.ciphers);
                   2376:        myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
                   2377:            options.ciphers);
                   2378:        myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   2379:            myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
                   2380:
1.312     markus   2381:        if (options.compression == COMP_NONE) {
1.246     markus   2382:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   2383:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.312     markus   2384:        } else if (options.compression == COMP_DELAYED) {
                   2385:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   2386:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
1.102     markus   2387:        }
1.400     dtucker  2388:
                   2389:        if (options.rekey_limit || options.rekey_interval)
1.464     dtucker  2390:                packet_set_rekey_limits(options.rekey_limit,
1.400     dtucker  2391:                    (time_t)options.rekey_interval);
1.327     deraadt  2392:
1.413     djm      2393:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
                   2394:            list_hostkey_types());
1.134     markus   2395:
1.189     markus   2396:        /* start key exchange */
1.437     markus   2397:        if ((r = kex_setup(active_state, myproposal)) != 0)
                   2398:                fatal("kex_setup: %s", ssh_err(r));
1.435     markus   2399:        kex = active_state->kex;
1.426     markus   2400: #ifdef WITH_OPENSSL
1.263     markus   2401:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292     djm      2402:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263     markus   2403:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324     djm      2404:        kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.378     djm      2405:        kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1.426     markus   2406: #endif
1.410     markus   2407:        kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1.186     markus   2408:        kex->server = 1;
                   2409:        kex->client_version_string=client_version_string;
                   2410:        kex->server_version_string=server_version_string;
1.373     djm      2411:        kex->load_host_public_key=&get_hostkey_public_by_type;
                   2412:        kex->load_host_private_key=&get_hostkey_private_by_type;
1.231     provos   2413:        kex->host_key_index=&get_hostkey_index;
1.404     markus   2414:        kex->sign = sshd_hostkey_sign;
1.189     markus   2415:
1.435     markus   2416:        dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
1.187     markus   2417:
                   2418:        session_id2 = kex->session_id;
                   2419:        session_id2_len = kex->session_id_len;
1.129     provos   2420:
                   2421: #ifdef DEBUG_KEXDH
                   2422:        /* send 1st encrypted/maced/compressed message */
                   2423:        packet_start(SSH2_MSG_IGNORE);
                   2424:        packet_put_cstring("markus");
                   2425:        packet_send();
                   2426:        packet_write_wait();
                   2427: #endif
1.186     markus   2428:        debug("KEX done");
1.278     markus   2429: }
                   2430:
                   2431: /* server specific fatal cleanup */
                   2432: void
                   2433: cleanup_exit(int i)
                   2434: {
1.386     djm      2435:        if (the_authctxt) {
1.278     markus   2436:                do_cleanup(the_authctxt);
1.423     djm      2437:                if (use_privsep && privsep_is_preauth &&
                   2438:                    pmonitor != NULL && pmonitor->m_pid > 1) {
1.386     djm      2439:                        debug("Killing privsep child %d", pmonitor->m_pid);
                   2440:                        if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388     djm      2441:                            errno != ESRCH)
1.386     djm      2442:                                error("%s: kill(%d): %s", __func__,
                   2443:                                    pmonitor->m_pid, strerror(errno));
                   2444:                }
                   2445:        }
1.278     markus   2446:        _exit(i);
1.1       deraadt  2447: }