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

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