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

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