[BACK]Return to clientloop.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/clientloop.c, Revision 1.406

1.406   ! djm         1: /* $OpenBSD: clientloop.c,v 1.405 2024/04/30 02:14:10 djm Exp $ */
1.1       deraadt     2: /*
1.12      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.33      deraadt     6:  * The main loop for the interactive session (client side).
1.20      markus      7:  *
1.33      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
                     13:  *
                     14:  *
                     15:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     16:  *
                     17:  * Redistribution and use in source and binary forms, with or without
                     18:  * modification, are permitted provided that the following conditions
                     19:  * are met:
                     20:  * 1. Redistributions of source code must retain the above copyright
                     21:  *    notice, this list of conditions and the following disclaimer.
                     22:  * 2. Redistributions in binary form must reproduce the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer in the
                     24:  *    documentation and/or other materials provided with the distribution.
                     25:  *
                     26:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     27:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     28:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     29:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     30:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     31:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     32:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     33:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     34:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     35:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.20      markus     36:  *
                     37:  *
1.33      deraadt    38:  * SSH2 support added by Markus Friedl.
1.78      markus     39:  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
1.20      markus     40:  *
1.33      deraadt    41:  * Redistribution and use in source and binary forms, with or without
                     42:  * modification, are permitted provided that the following conditions
                     43:  * are met:
                     44:  * 1. Redistributions of source code must retain the above copyright
                     45:  *    notice, this list of conditions and the following disclaimer.
                     46:  * 2. Redistributions in binary form must reproduce the above copyright
                     47:  *    notice, this list of conditions and the following disclaimer in the
                     48:  *    documentation and/or other materials provided with the distribution.
                     49:  *
                     50:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     51:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     52:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     53:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     54:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     55:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     56:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     57:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     58:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     59:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.12      deraadt    60:  */
1.1       deraadt    61:
1.152     stevesk    62:
1.175     deraadt    63: #include <sys/types.h>
1.152     stevesk    64: #include <sys/ioctl.h>
1.154     stevesk    65: #include <sys/stat.h>
1.166     stevesk    66: #include <sys/socket.h>
1.171     stevesk    67: #include <sys/time.h>
1.189     djm        68: #include <sys/queue.h>
1.150     stevesk    69:
1.155     stevesk    70: #include <ctype.h>
1.168     stevesk    71: #include <errno.h>
1.151     stevesk    72: #include <paths.h>
1.374     djm        73: #include <poll.h>
1.153     stevesk    74: #include <signal.h>
1.174     stevesk    75: #include <stdio.h>
1.173     stevesk    76: #include <stdlib.h>
1.170     stevesk    77: #include <string.h>
1.328     deraadt    78: #include <stdarg.h>
1.150     stevesk    79: #include <termios.h>
1.175     deraadt    80: #include <pwd.h>
1.169     stevesk    81: #include <unistd.h>
1.266     deraadt    82: #include <limits.h>
1.1       deraadt    83:
1.175     deraadt    84: #include "xmalloc.h"
1.45      markus     85: #include "ssh.h"
                     86: #include "ssh2.h"
1.1       deraadt    87: #include "packet.h"
1.315     markus     88: #include "sshbuf.h"
1.15      markus     89: #include "compat.h"
1.74      markus     90: #include "channels.h"
1.15      markus     91: #include "dispatch.h"
1.317     markus     92: #include "sshkey.h"
1.175     deraadt    93: #include "cipher.h"
1.54      markus     94: #include "kex.h"
1.275     markus     95: #include "myproposal.h"
1.45      markus     96: #include "log.h"
1.261     millert    97: #include "misc.h"
1.45      markus     98: #include "readconf.h"
                     99: #include "clientloop.h"
1.147     djm       100: #include "sshconnect.h"
1.40      markus    101: #include "authfd.h"
1.45      markus    102: #include "atomicio.h"
1.118     deraadt   103: #include "sshpty.h"
1.123     djm       104: #include "match.h"
                    105: #include "msg.h"
1.262     djm       106: #include "ssherr.h"
1.267     djm       107: #include "hostfile.h"
1.319     djm       108:
1.375     djm       109: /* Permitted RSA signature algorithms for UpdateHostkeys proofs */
                    110: #define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256"
                    111:
1.397     djm       112: /* Uncertainty (in percent) of keystroke timing intervals */
                    113: #define SSH_KEYSTROKE_TIMING_FUZZ 10
                    114:
1.39      markus    115: /* import options */
                    116: extern Options options;
1.1       deraadt   117:
1.123     djm       118: /* Control socket */
1.217     djm       119: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123     djm       120:
1.13      markus    121: /*
                    122:  * Name of the host we are connecting to.  This is the name given on the
1.324     jmc       123:  * command line, or the Hostname specified for the user-supplied name in a
1.13      markus    124:  * configuration file.
                    125:  */
1.1       deraadt   126: extern char *host;
                    127:
1.13      markus    128: /*
1.330     djm       129:  * If this field is not NULL, the ForwardAgent socket is this path and different
                    130:  * instead of SSH_AUTH_SOCK.
                    131:  */
                    132: extern char *forward_agent_sock_path;
                    133:
                    134: /*
1.13      markus    135:  * Flag to indicate that we have received a window change signal which has
                    136:  * not yet been processed.  This will cause a message indicating the new
                    137:  * window size to be sent to the server a little later.  This is volatile
                    138:  * because this is updated in a signal handler.
                    139:  */
1.88      markus    140: static volatile sig_atomic_t received_window_change_signal = 0;
                    141: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   142:
1.222     djm       143: /* Time when backgrounded control master using ControlPersist should exit */
                    144: static time_t control_persist_exit_time = 0;
                    145:
1.1       deraadt   146: /* Common data for the client loop code. */
1.217     djm       147: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.11      markus    148: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       149: static int exit_status;                /* Used to store the command exit status. */
1.11      markus    150: static int connection_in;      /* Connection to server (input). */
                    151: static int connection_out;     /* Connection to server (output). */
1.56      markus    152: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221     djm       153: static int session_closed;     /* In SSH2: login session closed. */
1.388     dtucker   154: static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */
1.345     dtucker   155: static time_t server_alive_time;       /* Time to do server_alive_check */
1.384     djm       156: static int hostkeys_update_complete;
                    157: static int session_setup_complete;
1.1       deraadt   158:
1.321     djm       159: static void client_init_dispatch(struct ssh *ssh);
1.16      markus    160: int    session_ident = -1;
                    161:
1.195     djm       162: /* Track escape per proto2 channel */
                    163: struct escape_filter_ctx {
                    164:        int escape_pending;
                    165:        int escape_char;
                    166: };
                    167:
                    168: /* Context for channel confirmation replies */
1.190     djm       169: struct channel_reply_ctx {
                    170:        const char *request_type;
1.234     djm       171:        int id;
                    172:        enum confirm_action action;
1.190     djm       173: };
                    174:
1.196     djm       175: /* Global request success/failure callbacks */
1.303     djm       176: /* XXX move to struct ssh? */
1.196     djm       177: struct global_confirm {
                    178:        TAILQ_ENTRY(global_confirm) entry;
                    179:        global_confirm_cb *cb;
                    180:        void *ctx;
                    181:        int ref_count;
                    182: };
                    183: TAILQ_HEAD(global_confirms, global_confirm);
                    184: static struct global_confirms global_confirms =
                    185:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    186:
1.315     markus    187: void ssh_process_session2_setup(int, int, int, struct sshbuf *);
1.377     djm       188: static void quit_message(const char *fmt, ...)
                    189:     __attribute__((__format__ (printf, 1, 2)));
                    190:
                    191: static void
                    192: quit_message(const char *fmt, ...)
                    193: {
1.406   ! djm       194:        char *msg, *fmt2;
1.377     djm       195:        va_list args;
1.406   ! djm       196:        xasprintf(&fmt2, "%s\r\n", fmt);
1.377     djm       197:
                    198:        va_start(args, fmt);
1.406   ! djm       199:        xvasprintf(&msg, fmt2, args);
1.377     djm       200:        va_end(args);
                    201:
1.406   ! djm       202:        (void)atomicio(vwrite, STDERR_FILENO, msg, strlen(msg));
1.402     dtucker   203:        free(msg);
1.406   ! djm       204:        free(fmt2);
        !           205:
1.377     djm       206:        quit_pending = 1;
                    207: }
1.123     djm       208:
1.13      markus    209: /*
                    210:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    211:  * flag indicating that the window has changed.
                    212:  */
1.77      itojun    213: static void
1.11      markus    214: window_change_handler(int sig)
1.1       deraadt   215: {
1.11      markus    216:        received_window_change_signal = 1;
1.1       deraadt   217: }
                    218:
1.13      markus    219: /*
                    220:  * Signal handler for signals that cause the program to terminate.  These
                    221:  * signals must be trapped to restore terminal modes.
                    222:  */
1.77      itojun    223: static void
1.11      markus    224: signal_handler(int sig)
1.1       deraadt   225: {
1.75      markus    226:        received_signal = sig;
                    227:        quit_pending = 1;
1.1       deraadt   228: }
                    229:
1.13      markus    230: /*
1.222     djm       231:  * Sets control_persist_exit_time to the absolute time when the
                    232:  * backgrounded control master should exit due to expiry of the
                    233:  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
                    234:  * control master process, or if there is no ControlPersist timeout.
                    235:  */
                    236: static void
1.303     djm       237: set_control_persist_exit_time(struct ssh *ssh)
1.222     djm       238: {
                    239:        if (muxserver_sock == -1 || !options.control_persist
1.232     djm       240:            || options.control_persist_timeout == 0) {
1.222     djm       241:                /* not using a ControlPersist timeout */
                    242:                control_persist_exit_time = 0;
1.303     djm       243:        } else if (channel_still_open(ssh)) {
1.222     djm       244:                /* some client connections are still open */
                    245:                if (control_persist_exit_time > 0)
1.354     djm       246:                        debug2_f("cancel scheduled exit");
1.222     djm       247:                control_persist_exit_time = 0;
                    248:        } else if (control_persist_exit_time <= 0) {
                    249:                /* a client connection has recently closed */
1.251     dtucker   250:                control_persist_exit_time = monotime() +
1.222     djm       251:                        (time_t)options.control_persist_timeout;
1.354     djm       252:                debug2_f("schedule exit in %d seconds",
1.222     djm       253:                    options.control_persist_timeout);
                    254:        }
                    255:        /* else we are already counting down to the timeout */
                    256: }
                    257:
1.238     dtucker   258: #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
                    259: static int
                    260: client_x11_display_valid(const char *display)
                    261: {
                    262:        size_t i, dlen;
                    263:
1.279     djm       264:        if (display == NULL)
                    265:                return 0;
                    266:
1.238     dtucker   267:        dlen = strlen(display);
                    268:        for (i = 0; i < dlen; i++) {
1.256     deraadt   269:                if (!isalnum((u_char)display[i]) &&
1.238     dtucker   270:                    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
                    271:                        debug("Invalid character '%c' in DISPLAY", display[i]);
                    272:                        return 0;
                    273:                }
                    274:        }
                    275:        return 1;
                    276: }
                    277:
1.274     djm       278: #define SSH_X11_PROTO          "MIT-MAGIC-COOKIE-1"
                    279: #define X11_TIMEOUT_SLACK      60
1.279     djm       280: int
1.303     djm       281: client_x11_get_proto(struct ssh *ssh, const char *display,
                    282:     const char *xauth_path, u_int trusted, u_int timeout,
                    283:     char **_proto, char **_data)
1.138     djm       284: {
1.318     djm       285:        char *cmd, line[512], xdisplay[512];
1.279     djm       286:        char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
1.138     djm       287:        static char proto[512], data[512];
                    288:        FILE *f;
1.288     tedu      289:        int got_data = 0, generated = 0, do_unlink = 0, r;
1.138     djm       290:        struct stat st;
1.274     djm       291:        u_int now, x11_timeout_real;
1.138     djm       292:
                    293:        *_proto = proto;
                    294:        *_data = data;
1.279     djm       295:        proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
1.138     djm       296:
1.279     djm       297:        if (!client_x11_display_valid(display)) {
1.283     millert   298:                if (display != NULL)
                    299:                        logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
                    300:                            display);
1.279     djm       301:                return -1;
                    302:        }
                    303:        if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
1.138     djm       304:                debug("No xauth program.");
1.279     djm       305:                xauth_path = NULL;
                    306:        }
                    307:
                    308:        if (xauth_path != NULL) {
1.138     djm       309:                /*
                    310:                 * Handle FamilyLocal case where $DISPLAY does
                    311:                 * not match an authorization entry.  For this we
                    312:                 * just try "xauth list unix:displaynum.screennum".
                    313:                 * XXX: "localhost" match to determine FamilyLocal
                    314:                 *      is not perfect.
                    315:                 */
                    316:                if (strncmp(display, "localhost:", 10) == 0) {
1.279     djm       317:                        if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    318:                            display + 10)) < 0 ||
                    319:                            (size_t)r >= sizeof(xdisplay)) {
1.354     djm       320:                                error_f("display name too long");
1.279     djm       321:                                return -1;
                    322:                        }
1.138     djm       323:                        display = xdisplay;
                    324:                }
                    325:                if (trusted == 0) {
1.274     djm       326:                        /*
1.279     djm       327:                         * Generate an untrusted X11 auth cookie.
                    328:                         *
1.274     djm       329:                         * The authentication cookie should briefly outlive
                    330:                         * ssh's willingness to forward X11 connections to
                    331:                         * avoid nasty fail-open behaviour in the X server.
                    332:                         */
1.279     djm       333:                        mktemp_proto(xauthdir, sizeof(xauthdir));
                    334:                        if (mkdtemp(xauthdir) == NULL) {
1.354     djm       335:                                error_f("mkdtemp: %s", strerror(errno));
1.279     djm       336:                                return -1;
                    337:                        }
                    338:                        do_unlink = 1;
                    339:                        if ((r = snprintf(xauthfile, sizeof(xauthfile),
                    340:                            "%s/xauthfile", xauthdir)) < 0 ||
                    341:                            (size_t)r >= sizeof(xauthfile)) {
1.354     djm       342:                                error_f("xauthfile path too long");
1.279     djm       343:                                rmdir(xauthdir);
                    344:                                return -1;
                    345:                        }
                    346:
1.318     djm       347:                        if (timeout == 0) {
                    348:                                /* auth doesn't time out */
                    349:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    350:                                    "untrusted 2>%s",
                    351:                                    xauth_path, xauthfile, display,
                    352:                                    SSH_X11_PROTO, _PATH_DEVNULL);
                    353:                        } else {
                    354:                                /* Add some slack to requested expiry */
                    355:                                if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
                    356:                                        x11_timeout_real = timeout +
                    357:                                            X11_TIMEOUT_SLACK;
                    358:                                else {
                    359:                                        /* Don't overflow on long timeouts */
                    360:                                        x11_timeout_real = UINT_MAX;
                    361:                                }
                    362:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    363:                                    "untrusted timeout %u 2>%s",
                    364:                                    xauth_path, xauthfile, display,
                    365:                                    SSH_X11_PROTO, x11_timeout_real,
                    366:                                    _PATH_DEVNULL);
                    367:                        }
1.354     djm       368:                        debug2_f("xauth command: %s", cmd);
1.318     djm       369:
                    370:                        if (timeout != 0 && x11_refuse_time == 0) {
1.279     djm       371:                                now = monotime() + 1;
1.388     dtucker   372:                                if (SSH_TIME_T_MAX - timeout < now)
                    373:                                        x11_refuse_time = SSH_TIME_T_MAX;
1.279     djm       374:                                else
                    375:                                        x11_refuse_time = now + timeout;
1.303     djm       376:                                channel_set_x11_refuse_time(ssh,
                    377:                                    x11_refuse_time);
1.138     djm       378:                        }
1.279     djm       379:                        if (system(cmd) == 0)
                    380:                                generated = 1;
1.318     djm       381:                        free(cmd);
1.138     djm       382:                }
1.181     markus    383:
                    384:                /*
                    385:                 * When in untrusted mode, we read the cookie only if it was
                    386:                 * successfully generated as an untrusted one in the step
                    387:                 * above.
                    388:                 */
                    389:                if (trusted || generated) {
1.318     djm       390:                        xasprintf(&cmd,
1.181     markus    391:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    392:                            xauth_path,
                    393:                            generated ? "-f " : "" ,
                    394:                            generated ? xauthfile : "",
                    395:                            display);
                    396:                        debug2("x11_get_proto: %s", cmd);
                    397:                        f = popen(cmd, "r");
                    398:                        if (f && fgets(line, sizeof(line), f) &&
                    399:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    400:                                got_data = 1;
                    401:                        if (f)
                    402:                                pclose(f);
1.318     djm       403:                        free(cmd);
1.279     djm       404:                }
1.138     djm       405:        }
                    406:
                    407:        if (do_unlink) {
                    408:                unlink(xauthfile);
                    409:                rmdir(xauthdir);
                    410:        }
                    411:
1.279     djm       412:        /* Don't fall back to fake X11 data for untrusted forwarding */
                    413:        if (!trusted && !got_data) {
                    414:                error("Warning: untrusted X11 forwarding setup failed: "
                    415:                    "xauth key data not generated");
                    416:                return -1;
                    417:        }
                    418:
1.138     djm       419:        /*
                    420:         * If we didn't get authentication data, just make up some
                    421:         * data.  The forwarding code will check the validity of the
                    422:         * response anyway, and substitute this data.  The X11
                    423:         * server, however, will ignore this fake data and use
                    424:         * whatever authentication mechanisms it was using otherwise
                    425:         * for the local connection.
                    426:         */
                    427:        if (!got_data) {
1.288     tedu      428:                u_int8_t rnd[16];
                    429:                u_int i;
1.138     djm       430:
                    431:                logit("Warning: No xauth data; "
                    432:                    "using fake authentication data for X11 forwarding.");
                    433:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.288     tedu      434:                arc4random_buf(rnd, sizeof(rnd));
                    435:                for (i = 0; i < sizeof(rnd); i++) {
1.138     djm       436:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.288     tedu      437:                            rnd[i]);
1.138     djm       438:                }
                    439:        }
1.279     djm       440:
                    441:        return 0;
1.1       deraadt   442: }
                    443:
1.13      markus    444: /*
                    445:  * Checks if the client window has changed, and sends a packet about it to
                    446:  * the server if so.  The actual change is detected elsewhere (by a software
                    447:  * interrupt on Unix); this just checks the flag and sends a message if
                    448:  * appropriate.
                    449:  */
1.1       deraadt   450:
1.77      itojun    451: static void
1.303     djm       452: client_check_window_change(struct ssh *ssh)
1.1       deraadt   453: {
1.292     djm       454:        if (!received_window_change_signal)
1.16      markus    455:                return;
                    456:        received_window_change_signal = 0;
1.354     djm       457:        debug2_f("changed");
1.303     djm       458:        channel_send_window_changes(ssh);
1.1       deraadt   459: }
                    460:
1.264     markus    461: static int
1.297     markus    462: client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
1.117     markus    463: {
1.196     djm       464:        struct global_confirm *gc;
                    465:
                    466:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
1.264     markus    467:                return 0;
1.196     djm       468:        if (gc->cb != NULL)
1.303     djm       469:                gc->cb(ssh, type, seq, gc->ctx);
1.196     djm       470:        if (--gc->ref_count <= 0) {
                    471:                TAILQ_REMOVE(&global_confirms, gc, entry);
1.342     jsg       472:                freezero(gc, sizeof(*gc));
1.196     djm       473:        }
                    474:
1.320     djm       475:        ssh_packet_set_alive_timeouts(ssh, 0);
1.264     markus    476:        return 0;
1.117     markus    477: }
                    478:
                    479: static void
1.345     dtucker   480: schedule_server_alive_check(void)
                    481: {
                    482:        if (options.server_alive_interval > 0)
                    483:                server_alive_time = monotime() + options.server_alive_interval;
                    484: }
                    485:
                    486: static void
1.320     djm       487: server_alive_check(struct ssh *ssh)
1.117     markus    488: {
1.320     djm       489:        int r;
                    490:
                    491:        if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
1.228     djm       492:                logit("Timeout, server %s not responding.", host);
1.176     markus    493:                cleanup_exit(255);
                    494:        }
1.320     djm       495:        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                    496:            (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
                    497:            (r = sshpkt_put_u8(ssh, 1)) != 0 ||         /* boolean: want reply */
                    498:            (r = sshpkt_send(ssh)) != 0)
1.354     djm       499:                fatal_fr(r, "send packet");
1.196     djm       500:        /* Insert an empty placeholder to maintain ordering */
                    501:        client_register_global_confirm(NULL, NULL);
1.345     dtucker   502:        schedule_server_alive_check();
1.117     markus    503: }
                    504:
1.393     djm       505: /* Try to send a dummy keystroke */
                    506: static int
                    507: send_chaff(struct ssh *ssh)
                    508: {
                    509:        int r;
                    510:
1.403     djm       511:        if (ssh->kex == NULL || (ssh->kex->flags & KEX_HAS_PING) == 0)
1.393     djm       512:                return 0;
                    513:        /* XXX probabilistically send chaff? */
                    514:        /*
                    515:         * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
                    516:         *    4 bytes channel ID + 4 bytes string length + 1 byte string data
                    517:         * simulate that here.
                    518:         */
                    519:        if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
                    520:            (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
                    521:            (r = sshpkt_send(ssh)) != 0)
                    522:                fatal_fr(r, "send packet");
                    523:        return 1;
                    524: }
                    525:
1.397     djm       526: /* Sets the next interval to send a keystroke or chaff packet */
                    527: static void
                    528: set_next_interval(const struct timespec *now, struct timespec *next_interval,
                    529:     u_int interval_ms, int starting)
                    530: {
                    531:        struct timespec tmp;
                    532:        long long interval_ns, fuzz_ns;
                    533:        static long long rate_fuzz;
                    534:
                    535:        interval_ns = interval_ms * (1000LL * 1000);
                    536:        fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100;
                    537:        /* Center fuzz around requested interval */
                    538:        if (fuzz_ns > INT_MAX)
                    539:                fuzz_ns = INT_MAX;
                    540:        if (fuzz_ns > interval_ns) {
                    541:                /* Shouldn't happen */
                    542:                fatal_f("internal error: fuzz %u%% %lldns > interval %lldns",
                    543:                    SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns);
                    544:        }
                    545:        /*
                    546:         * Randomise the keystroke/chaff intervals in two ways:
                    547:         * 1. Each interval has some random jitter applied to make the
                    548:         *    interval-to-interval time unpredictable.
                    549:         * 2. The overall interval rate is also randomly perturbed for each
1.398     djm       550:         *    chaffing session to make the average rate unpredictable.
1.397     djm       551:         */
                    552:        if (starting)
                    553:                rate_fuzz = arc4random_uniform(fuzz_ns);
                    554:        interval_ns -= fuzz_ns;
                    555:        interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz;
                    556:
                    557:        tmp.tv_sec = interval_ns / (1000 * 1000 * 1000);
                    558:        tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000);
                    559:
                    560:        timespecadd(now, &tmp, next_interval);
                    561: }
                    562:
1.393     djm       563: /*
                    564:  * Performs keystroke timing obfuscation. Returns non-zero if the
                    565:  * output fd should be polled.
                    566:  */
                    567: static int
1.396     djm       568: obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout,
                    569:     int channel_did_enqueue)
1.393     djm       570: {
                    571:        static int active;
                    572:        static struct timespec next_interval, chaff_until;
                    573:        struct timespec now, tmp;
                    574:        int just_started = 0, had_keystroke = 0;
                    575:        static unsigned long long nchaff;
                    576:        char *stop_reason = NULL;
                    577:        long long n;
                    578:
                    579:        monotime_ts(&now);
                    580:
                    581:        if (options.obscure_keystroke_timing_interval <= 0)
                    582:                return 1;       /* disabled in config */
                    583:
1.401     djm       584:        if (!channel_tty_open(ssh) || quit_pending) {
1.393     djm       585:                /* Stop if no channels left of we're waiting for one to close */
                    586:                stop_reason = "no active channels";
                    587:        } else if (ssh_packet_is_rekeying(ssh)) {
                    588:                /* Stop if we're rekeying */
                    589:                stop_reason = "rekeying started";
                    590:        } else if (!ssh_packet_interactive_data_to_write(ssh) &&
                    591:            ssh_packet_have_data_to_write(ssh)) {
                    592:                /* Stop if the output buffer has more than a few keystrokes */
                    593:                stop_reason = "output buffer filling";
1.396     djm       594:        } else if (active && channel_did_enqueue &&
                    595:            ssh_packet_have_data_to_write(ssh)) {
1.393     djm       596:                /* Still in active mode and have a keystroke queued. */
                    597:                had_keystroke = 1;
                    598:        } else if (active) {
                    599:                if (timespeccmp(&now, &chaff_until, >=)) {
                    600:                        /* Stop if there have been no keystrokes for a while */
                    601:                        stop_reason = "chaff time expired";
                    602:                } else if (timespeccmp(&now, &next_interval, >=)) {
                    603:                        /* Otherwise if we were due to send, then send chaff */
                    604:                        if (send_chaff(ssh))
                    605:                                nchaff++;
                    606:                }
                    607:        }
                    608:
                    609:        if (stop_reason != NULL) {
1.395     djm       610:                if (active) {
                    611:                        debug3_f("stopping: %s (%llu chaff packets sent)",
                    612:                            stop_reason, nchaff);
                    613:                        active = 0;
                    614:                }
1.393     djm       615:                return 1;
                    616:        }
                    617:
                    618:        /*
                    619:         * If we're in interactive mode, and only have a small amount
                    620:         * of outbound data, then we assume that the user is typing
                    621:         * interactively. In this case, start quantising outbound packets to
                    622:         * fixed time intervals to hide inter-keystroke timing.
                    623:         */
1.396     djm       624:        if (!active && ssh_packet_interactive_data_to_write(ssh) &&
                    625:            channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) {
1.397     djm       626:                debug3_f("starting: interval ~%dms",
1.393     djm       627:                    options.obscure_keystroke_timing_interval);
                    628:                just_started = had_keystroke = active = 1;
                    629:                nchaff = 0;
1.397     djm       630:                set_next_interval(&now, &next_interval,
                    631:                    options.obscure_keystroke_timing_interval, 1);
1.393     djm       632:        }
                    633:
                    634:        /* Don't hold off if obfuscation inactive */
                    635:        if (!active)
                    636:                return 1;
                    637:
                    638:        if (had_keystroke) {
                    639:                /*
                    640:                 * Arrange to send chaff packets for a random interval after
                    641:                 * the last keystroke was sent.
                    642:                 */
                    643:                ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
                    644:                    arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
                    645:                timespecadd(&now, &tmp, &chaff_until);
                    646:        }
                    647:
                    648:        ptimeout_deadline_monotime_tsp(timeout, &next_interval);
                    649:
                    650:        if (just_started)
                    651:                return 1;
                    652:
                    653:        /* Don't arm output fd for poll until the timing interval has elapsed */
                    654:        if (timespeccmp(&now, &next_interval, <))
                    655:                return 0;
                    656:
                    657:        /* Calculate number of intervals missed since the last check */
1.394     djm       658:        n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000;
1.393     djm       659:        n += now.tv_nsec - next_interval.tv_nsec;
1.394     djm       660:        n /= options.obscure_keystroke_timing_interval * 1000LL * 1000;
1.393     djm       661:        n = (n < 0) ? 1 : n + 1;
                    662:
                    663:        /* Advance to the next interval */
1.397     djm       664:        set_next_interval(&now, &next_interval,
                    665:            options.obscure_keystroke_timing_interval * n, 0);
1.393     djm       666:        return 1;
                    667: }
                    668:
1.13      markus    669: /*
                    670:  * Waits until the client can do something (some data becomes available on
                    671:  * one of the file descriptors).
                    672:  */
1.77      itojun    673: static void
1.374     djm       674: client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
1.396     djm       675:     u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue,
1.400     djm       676:     sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
1.11      markus    677: {
1.386     djm       678:        struct timespec timeout;
1.393     djm       679:        int ret, oready;
1.374     djm       680:        u_int p;
1.117     markus    681:
1.374     djm       682:        *conn_in_readyp = *conn_out_readyp = 0;
1.11      markus    683:
1.374     djm       684:        /* Prepare channel poll. First two pollfd entries are reserved */
1.386     djm       685:        ptimeout_init(&timeout);
                    686:        channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
1.374     djm       687:        if (*npfd_activep < 2)
                    688:                fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
                    689:
                    690:        /* channel_prepare_poll could have closed the last channel */
1.303     djm       691:        if (session_closed && !channel_still_open(ssh) &&
1.320     djm       692:            !ssh_packet_have_data_to_write(ssh)) {
1.374     djm       693:                /* clear events since we did not call poll() */
                    694:                for (p = 0; p < *npfd_activep; p++)
                    695:                        (*pfdp)[p].revents = 0;
1.292     djm       696:                return;
1.16      markus    697:        }
1.11      markus    698:
1.396     djm       699:        oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue);
1.393     djm       700:
1.374     djm       701:        /* Monitor server connection on reserved pollfd entries */
                    702:        (*pfdp)[0].fd = connection_in;
                    703:        (*pfdp)[0].events = POLLIN;
                    704:        (*pfdp)[1].fd = connection_out;
1.393     djm       705:        (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
                    706:            POLLOUT : 0;
1.11      markus    707:
1.13      markus    708:        /*
                    709:         * Wait for something to happen.  This will suspend the process until
1.374     djm       710:         * some polled descriptor can be read, written, or has some other
1.222     djm       711:         * event pending, or a timeout expires.
1.13      markus    712:         */
1.386     djm       713:        set_control_persist_exit_time(ssh);
                    714:        if (control_persist_exit_time > 0)
                    715:                ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
1.345     dtucker   716:        if (options.server_alive_interval > 0)
1.386     djm       717:                ptimeout_deadline_monotime(&timeout, server_alive_time);
1.396     djm       718:        if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
1.386     djm       719:                ptimeout_deadline_sec(&timeout,
1.320     djm       720:                    ssh_packet_get_rekey_timeout(ssh));
1.386     djm       721:        }
1.374     djm       722:
1.400     djm       723:        ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
1.222     djm       724:
1.326     deraadt   725:        if (ret == -1) {
1.51      markus    726:                /*
1.374     djm       727:                 * We have to clear the events because we return.
1.51      markus    728:                 * We have to return, because the mainloop checks for the flags
                    729:                 * set by the signal handlers.
                    730:                 */
1.374     djm       731:                for (p = 0; p < *npfd_activep; p++)
                    732:                        (*pfdp)[p].revents = 0;
1.11      markus    733:                if (errno == EINTR)
                    734:                        return;
                    735:                /* Note: we might still have data in the buffers. */
1.377     djm       736:                quit_message("poll: %s", strerror(errno));
1.374     djm       737:                return;
                    738:        }
                    739:
                    740:        *conn_in_readyp = (*pfdp)[0].revents != 0;
                    741:        *conn_out_readyp = (*pfdp)[1].revents != 0;
                    742:
                    743:        if (options.server_alive_interval > 0 && !*conn_in_readyp &&
                    744:            monotime() >= server_alive_time) {
1.249     dtucker   745:                /*
1.374     djm       746:                 * ServerAlive check is needed. We can't rely on the poll
1.345     dtucker   747:                 * timing out since traffic on the client side such as port
                    748:                 * forwards can keep waking it up.
1.249     dtucker   749:                 */
1.345     dtucker   750:                server_alive_check(ssh);
1.374     djm       751:        }
1.11      markus    752: }
                    753:
1.77      itojun    754: static void
1.315     markus    755: client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
1.1       deraadt   756: {
1.11      markus    757:        /* Flush stdout and stderr buffers. */
1.315     markus    758:        if (sshbuf_len(bout) > 0)
                    759:                atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
                    760:                    sshbuf_len(bout));
                    761:        if (sshbuf_len(berr) > 0)
                    762:                atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
                    763:                    sshbuf_len(berr));
1.11      markus    764:
1.233     djm       765:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    766:
1.305     djm       767:        sshbuf_reset(bin);
                    768:        sshbuf_reset(bout);
                    769:        sshbuf_reset(berr);
1.11      markus    770:
                    771:        /* Send the suspend signal to the program itself. */
                    772:        kill(getpid(), SIGTSTP);
                    773:
1.132     djm       774:        /* Reset window sizes in case they have changed */
                    775:        received_window_change_signal = 1;
1.11      markus    776:
1.233     djm       777:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    778: }
                    779:
1.77      itojun    780: static void
1.374     djm       781: client_process_net_input(struct ssh *ssh)
1.11      markus    782: {
1.378     djm       783:        int r;
1.11      markus    784:
1.13      markus    785:        /*
                    786:         * Read input from the server, and add any such data to the buffer of
                    787:         * the packet subsystem.
                    788:         */
1.374     djm       789:        schedule_server_alive_check();
1.378     djm       790:        if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
                    791:                return; /* success */
                    792:        if (r == SSH_ERR_SYSTEM_ERROR) {
                    793:                if (errno == EAGAIN || errno == EINTR)
                    794:                        return;
                    795:                if (errno == EPIPE) {
                    796:                        quit_message("Connection to %s closed by remote host.",
                    797:                            host);
                    798:                        return;
                    799:                }
1.11      markus    800:        }
1.378     djm       801:        quit_message("Read from remote host %s: %s", host, ssh_err(r));
1.17      markus    802: }
1.16      markus    803:
1.97      jakob     804: static void
1.303     djm       805: client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
1.123     djm       806: {
1.190     djm       807:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    808:        char errmsg[256];
1.315     markus    809:        int r, tochan;
1.190     djm       810:
1.234     djm       811:        /*
                    812:         * If a TTY was explicitly requested, then a failure to allocate
                    813:         * one is fatal.
                    814:         */
                    815:        if (cr->action == CONFIRM_TTY &&
                    816:            (options.request_tty == REQUEST_TTY_FORCE ||
                    817:            options.request_tty == REQUEST_TTY_YES))
                    818:                cr->action = CONFIRM_CLOSE;
                    819:
1.312     djm       820:        /* XXX suppress on mux _client_ quietmode */
1.190     djm       821:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       822:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       823:
                    824:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    825:                debug2("%s request accepted on channel %d",
                    826:                    cr->request_type, c->self);
                    827:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    828:                if (tochan) {
                    829:                        snprintf(errmsg, sizeof(errmsg),
                    830:                            "%s request failed\r\n", cr->request_type);
                    831:                } else {
                    832:                        snprintf(errmsg, sizeof(errmsg),
                    833:                            "%s request failed on channel %d",
                    834:                            cr->request_type, c->self);
                    835:                }
                    836:                /* If error occurred on primary session channel, then exit */
1.234     djm       837:                if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190     djm       838:                        fatal("%s", errmsg);
1.234     djm       839:                /*
                    840:                 * If error occurred on mux client, append to
                    841:                 * their stderr.
                    842:                 */
                    843:                if (tochan) {
1.360     djm       844:                        debug3_f("channel %d: mux request: %s", c->self,
                    845:                            cr->request_type);
1.315     markus    846:                        if ((r = sshbuf_put(c->extended, errmsg,
                    847:                            strlen(errmsg))) != 0)
1.354     djm       848:                                fatal_fr(r, "sshbuf_put");
1.234     djm       849:                } else
1.190     djm       850:                        error("%s", errmsg);
1.234     djm       851:                if (cr->action == CONFIRM_TTY) {
                    852:                        /*
                    853:                         * If a TTY allocation error occurred, then arrange
                    854:                         * for the correct TTY to leave raw mode.
                    855:                         */
                    856:                        if (c->self == session_ident)
                    857:                                leave_raw_mode(0);
                    858:                        else
1.303     djm       859:                                mux_tty_alloc_failed(ssh, c);
1.234     djm       860:                } else if (cr->action == CONFIRM_CLOSE) {
1.303     djm       861:                        chan_read_failed(ssh, c);
                    862:                        chan_write_failed(ssh, c);
1.190     djm       863:                }
                    864:        }
1.250     djm       865:        free(cr);
1.190     djm       866: }
                    867:
                    868: static void
1.303     djm       869: client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
1.190     djm       870: {
1.250     djm       871:        free(ctx);
1.190     djm       872: }
1.129     deraadt   873:
1.236     djm       874: void
1.303     djm       875: client_expect_confirm(struct ssh *ssh, int id, const char *request,
1.234     djm       876:     enum confirm_action action)
1.190     djm       877: {
1.255     djm       878:        struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123     djm       879:
1.190     djm       880:        cr->request_type = request;
1.234     djm       881:        cr->action = action;
1.123     djm       882:
1.303     djm       883:        channel_register_status_confirm(ssh, id, client_status_confirm,
1.190     djm       884:            client_abandon_status_confirm, cr);
1.196     djm       885: }
                    886:
                    887: void
                    888: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    889: {
1.201     djm       890:        struct global_confirm *gc, *last_gc;
1.196     djm       891:
                    892:        /* Coalesce identical callbacks */
1.201     djm       893:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    894:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    895:                if (++last_gc->ref_count >= INT_MAX)
1.354     djm       896:                        fatal_f("last_gc->ref_count = %d",
                    897:                            last_gc->ref_count);
1.196     djm       898:                return;
                    899:        }
                    900:
1.255     djm       901:        gc = xcalloc(1, sizeof(*gc));
1.196     djm       902:        gc->cb = cb;
                    903:        gc->ctx = ctx;
                    904:        gc->ref_count = 1;
                    905:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       906: }
                    907:
1.384     djm       908: /*
                    909:  * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
                    910:  * hostkey update request.
                    911:  */
                    912: static int
                    913: can_update_hostkeys(void)
                    914: {
                    915:        if (hostkeys_update_complete)
                    916:                return 0;
                    917:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
                    918:            options.batch_mode)
                    919:                return 0; /* won't ask in batchmode, so don't even try */
                    920:        if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
                    921:                return 0;
                    922:        return 1;
                    923: }
                    924:
1.385     dtucker   925: static void
                    926: client_repledge(void)
1.384     djm       927: {
                    928:        debug3_f("enter");
                    929:
                    930:        /* Might be able to tighten pledge now that session is established */
                    931:        if (options.control_master || options.control_path != NULL ||
                    932:            options.forward_x11 || options.fork_after_authentication ||
                    933:            can_update_hostkeys() ||
                    934:            (session_ident != -1 && !session_setup_complete)) {
                    935:                /* Can't tighten */
                    936:                return;
                    937:        }
                    938:        /*
                    939:         * LocalCommand and UpdateHostkeys have finished, so can get rid of
                    940:         * filesystem.
                    941:         *
                    942:         * XXX protocol allows a server can to change hostkeys during the
                    943:         *     connection at rekey time that could trigger a hostkeys update
                    944:         *     but AFAIK no implementations support this. Could improve by
                    945:         *     forcing known_hosts to be read-only or via unveil(2).
                    946:         */
                    947:        if (options.num_local_forwards != 0 ||
                    948:            options.num_remote_forwards != 0 ||
                    949:            options.num_permitted_remote_opens != 0 ||
                    950:            options.enable_escape_commandline != 0) {
                    951:                /* rfwd needs inet */
                    952:                debug("pledge: network");
                    953:                if (pledge("stdio unix inet dns proc tty", NULL) == -1)
                    954:                        fatal_f("pledge(): %s", strerror(errno));
                    955:        } else if (options.forward_agent != 0) {
                    956:                /* agent forwarding needs to open $SSH_AUTH_SOCK at will */
                    957:                debug("pledge: agent");
                    958:                if (pledge("stdio unix proc tty", NULL) == -1)
                    959:                        fatal_f("pledge(): %s", strerror(errno));
                    960:        } else {
                    961:                debug("pledge: fork");
                    962:                if (pledge("stdio proc tty", NULL) == -1)
                    963:                        fatal_f("pledge(): %s", strerror(errno));
                    964:        }
                    965:        /* XXX further things to do:
                    966:         *
                    967:         * - might be able to get rid of proc if we kill ~^Z
                    968:         * - ssh -N (no session)
                    969:         * - stdio forwarding
                    970:         * - sessions without tty
                    971:         */
                    972: }
                    973:
1.123     djm       974: static void
1.303     djm       975: process_cmdline(struct ssh *ssh)
1.97      jakob     976: {
                    977:        void (*handler)(int);
1.261     millert   978:        char *s, *cmd;
                    979:        int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
                    980:        struct Forward fwd;
1.97      jakob     981:
1.257     tedu      982:        memset(&fwd, 0, sizeof(fwd));
1.183     djm       983:
1.233     djm       984:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.332     dtucker   985:        handler = ssh_signal(SIGINT, SIG_IGN);
1.99      markus    986:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     987:        if (s == NULL)
                    988:                goto out;
1.256     deraadt   989:        while (isspace((u_char)*s))
1.97      jakob     990:                s++;
1.121     djm       991:        if (*s == '-')
                    992:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   993:        if (*s == '\0')
1.97      jakob     994:                goto out;
1.121     djm       995:
1.122     djm       996:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       997:                logit("Commands:");
1.164     djm       998:                logit("      -L[bind_address:]port:host:hostport    "
                    999:                    "Request local forward");
                   1000:                logit("      -R[bind_address:]port:host:hostport    "
                   1001:                    "Request remote forward");
1.204     stevesk  1002:                logit("      -D[bind_address:]port                  "
                   1003:                    "Request dynamic forward");
1.237     markus   1004:                logit("      -KL[bind_address:]port                 "
                   1005:                    "Cancel local forward");
1.165     stevesk  1006:                logit("      -KR[bind_address:]port                 "
1.164     djm      1007:                    "Cancel remote forward");
1.237     markus   1008:                logit("      -KD[bind_address:]port                 "
                   1009:                    "Cancel dynamic forward");
1.146     reyk     1010:                if (!options.permit_local_command)
                   1011:                        goto out;
1.164     djm      1012:                logit("      !args                                  "
                   1013:                    "Execute local command");
1.146     reyk     1014:                goto out;
                   1015:        }
                   1016:
                   1017:        if (*s == '!' && options.permit_local_command) {
                   1018:                s++;
                   1019:                ssh_local_cmd(s);
1.121     djm      1020:                goto out;
                   1021:        }
                   1022:
                   1023:        if (*s == 'K') {
                   1024:                delete = 1;
                   1025:                s++;
                   1026:        }
1.204     stevesk  1027:        if (*s == 'L')
                   1028:                local = 1;
                   1029:        else if (*s == 'R')
                   1030:                remote = 1;
                   1031:        else if (*s == 'D')
                   1032:                dynamic = 1;
                   1033:        else {
1.109     itojun   1034:                logit("Invalid command.");
1.97      jakob    1035:                goto out;
                   1036:        }
1.204     stevesk  1037:
1.256     deraadt  1038:        while (isspace((u_char)*++s))
1.179     tedu     1039:                ;
1.97      jakob    1040:
1.217     djm      1041:        /* XXX update list of forwards in options */
1.121     djm      1042:        if (delete) {
1.261     millert  1043:                /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
                   1044:                if (!parse_forward(&fwd, s, 1, 0)) {
                   1045:                        logit("Bad forwarding close specification.");
1.121     djm      1046:                        goto out;
                   1047:                }
1.237     markus   1048:                if (remote)
1.303     djm      1049:                        ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1.237     markus   1050:                else if (dynamic)
1.303     djm      1051:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert  1052:                            0, &options.fwd_opts) > 0;
1.237     markus   1053:                else
1.303     djm      1054:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert  1055:                            CHANNEL_CANCEL_PORT_STATIC,
                   1056:                            &options.fwd_opts) > 0;
1.237     markus   1057:                if (!ok) {
1.290     dtucker  1058:                        logit("Unknown port forwarding.");
1.237     markus   1059:                        goto out;
                   1060:                }
                   1061:                logit("Canceled forwarding.");
1.121     djm      1062:        } else {
1.382     dtucker  1063:                /* -R specs can be both dynamic or not, so check both. */
                   1064:                if (remote) {
                   1065:                        if (!parse_forward(&fwd, s, 0, remote) &&
                   1066:                            !parse_forward(&fwd, s, 1, remote)) {
                   1067:                                logit("Bad remote forwarding specification.");
                   1068:                                goto out;
                   1069:                        }
                   1070:                } else if (!parse_forward(&fwd, s, dynamic, remote)) {
                   1071:                        logit("Bad local forwarding specification.");
1.121     djm      1072:                        goto out;
                   1073:                }
1.204     stevesk  1074:                if (local || dynamic) {
1.303     djm      1075:                        if (!channel_setup_local_fwd_listener(ssh, &fwd,
1.261     millert  1076:                            &options.fwd_opts)) {
1.121     djm      1077:                                logit("Port forwarding failed.");
                   1078:                                goto out;
                   1079:                        }
1.135     djm      1080:                } else {
1.303     djm      1081:                        if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1.167     markus   1082:                                logit("Port forwarding failed.");
                   1083:                                goto out;
                   1084:                        }
1.135     djm      1085:                }
1.121     djm      1086:                logit("Forwarding port.");
                   1087:        }
                   1088:
1.97      jakob    1089: out:
1.332     dtucker  1090:        ssh_signal(SIGINT, handler);
1.233     djm      1091:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250     djm      1092:        free(cmd);
                   1093:        free(fwd.listen_host);
1.261     millert  1094:        free(fwd.listen_path);
1.250     djm      1095:        free(fwd.connect_host);
1.261     millert  1096:        free(fwd.connect_path);
1.97      jakob    1097: }
                   1098:
1.244     dtucker  1099: /* reasons to suppress output of an escape command in help output */
                   1100: #define SUPPRESS_NEVER         0       /* never suppress, always show */
1.292     djm      1101: #define SUPPRESS_MUXCLIENT     1       /* don't show in mux client sessions */
                   1102: #define SUPPRESS_MUXMASTER     2       /* don't show in mux master sessions */
                   1103: #define SUPPRESS_SYSLOG                4       /* don't show when logging to syslog */
1.383     djm      1104: #define SUPPRESS_NOCMDLINE     8       /* don't show when cmdline disabled*/
1.244     dtucker  1105: struct escape_help_text {
                   1106:        const char *cmd;
                   1107:        const char *text;
                   1108:        unsigned int flags;
                   1109: };
                   1110: static struct escape_help_text esc_txt[] = {
                   1111:     {".",  "terminate session", SUPPRESS_MUXMASTER},
                   1112:     {".",  "terminate connection (and any multiplexed sessions)",
                   1113:        SUPPRESS_MUXCLIENT},
1.292     djm      1114:     {"B",  "send a BREAK to the remote system", SUPPRESS_NEVER},
1.383     djm      1115:     {"C",  "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1.292     djm      1116:     {"R",  "request rekey", SUPPRESS_NEVER},
1.246     dtucker  1117:     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244     dtucker  1118:     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
                   1119:     {"#",  "list forwarded connections", SUPPRESS_NEVER},
                   1120:     {"&",  "background ssh (when waiting for connections to terminate)",
                   1121:        SUPPRESS_MUXCLIENT},
                   1122:     {"?", "this message", SUPPRESS_NEVER},
                   1123: };
                   1124:
                   1125: static void
1.315     markus   1126: print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
                   1127:     int using_stderr)
1.244     dtucker  1128: {
                   1129:        unsigned int i, suppress_flags;
1.315     markus   1130:        int r;
1.244     dtucker  1131:
1.315     markus   1132:        if ((r = sshbuf_putf(b,
                   1133:            "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
1.354     djm      1134:                fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1135:
1.292     djm      1136:        suppress_flags =
1.244     dtucker  1137:            (mux_client ? SUPPRESS_MUXCLIENT : 0) |
                   1138:            (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1.383     djm      1139:            (using_stderr ? 0 : SUPPRESS_SYSLOG) |
                   1140:            (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
1.244     dtucker  1141:
                   1142:        for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
                   1143:                if (esc_txt[i].flags & suppress_flags)
                   1144:                        continue;
1.315     markus   1145:                if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
                   1146:                    escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
1.354     djm      1147:                        fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1148:        }
                   1149:
1.315     markus   1150:        if ((r = sshbuf_putf(b,
1.246     dtucker  1151:            " %c%c   - send the escape character by typing it twice\r\n"
1.244     dtucker  1152:            "(Note that escapes are only recognized immediately after "
1.315     markus   1153:            "newline.)\r\n", escape_char, escape_char)) != 0)
1.354     djm      1154:                fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1155: }
                   1156:
1.314     djm      1157: /*
1.296     naddy    1158:  * Process the characters one by one.
1.195     djm      1159:  */
1.77      itojun   1160: static int
1.303     djm      1161: process_escapes(struct ssh *ssh, Channel *c,
1.315     markus   1162:     struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1.195     djm      1163:     char *buf, int len)
1.31      markus   1164: {
                   1165:        pid_t pid;
1.315     markus   1166:        int r, bytes = 0;
1.42      markus   1167:        u_int i;
                   1168:        u_char ch;
1.31      markus   1169:        char *s;
1.392     dtucker  1170:        struct escape_filter_ctx *efc;
1.31      markus   1171:
1.392     dtucker  1172:        if (c == NULL || c->filter_ctx == NULL || len <= 0)
1.294     djm      1173:                return 0;
1.314     djm      1174:
1.392     dtucker  1175:        efc = (struct escape_filter_ctx *)c->filter_ctx;
1.139     djm      1176:
                   1177:        for (i = 0; i < (u_int)len; i++) {
1.31      markus   1178:                /* Get one character at a time. */
                   1179:                ch = buf[i];
                   1180:
1.294     djm      1181:                if (efc->escape_pending) {
1.31      markus   1182:                        /* We have previously seen an escape character. */
                   1183:                        /* Clear the flag now. */
1.294     djm      1184:                        efc->escape_pending = 0;
1.31      markus   1185:
                   1186:                        /* Process the escaped character. */
                   1187:                        switch (ch) {
                   1188:                        case '.':
                   1189:                                /* Terminate the connection. */
1.315     markus   1190:                                if ((r = sshbuf_putf(berr, "%c.\r\n",
                   1191:                                    efc->escape_char)) != 0)
1.354     djm      1192:                                        fatal_fr(r, "sshbuf_putf");
1.217     djm      1193:                                if (c && c->ctl_chan != -1) {
1.387     djm      1194:                                        channel_force_close(ssh, c, 1);
1.195     djm      1195:                                        return 0;
                   1196:                                } else
                   1197:                                        quit_pending = 1;
1.31      markus   1198:                                return -1;
                   1199:
                   1200:                        case 'Z' - 64:
1.195     djm      1201:                                /* XXX support this for mux clients */
1.217     djm      1202:                                if (c && c->ctl_chan != -1) {
1.245     dtucker  1203:                                        char b[16];
1.195     djm      1204:  noescape:
1.245     dtucker  1205:                                        if (ch == 'Z' - 64)
                   1206:                                                snprintf(b, sizeof b, "^Z");
                   1207:                                        else
                   1208:                                                snprintf(b, sizeof b, "%c", ch);
1.315     markus   1209:                                        if ((r = sshbuf_putf(berr,
1.245     dtucker  1210:                                            "%c%s escape not available to "
1.195     djm      1211:                                            "multiplexed sessions\r\n",
1.315     markus   1212:                                            efc->escape_char, b)) != 0)
1.354     djm      1213:                                                fatal_fr(r, "sshbuf_putf");
1.195     djm      1214:                                        continue;
                   1215:                                }
1.197     djm      1216:                                /* Suspend the program. Inform the user */
1.315     markus   1217:                                if ((r = sshbuf_putf(berr,
                   1218:                                    "%c^Z [suspend ssh]\r\n",
                   1219:                                    efc->escape_char)) != 0)
1.354     djm      1220:                                        fatal_fr(r, "sshbuf_putf");
1.31      markus   1221:
                   1222:                                /* Restore terminal modes and suspend. */
                   1223:                                client_suspend_self(bin, bout, berr);
                   1224:
                   1225:                                /* We have been continued. */
                   1226:                                continue;
                   1227:
1.111     markus   1228:                        case 'B':
1.315     markus   1229:                                if ((r = sshbuf_putf(berr,
                   1230:                                    "%cB\r\n", efc->escape_char)) != 0)
1.354     djm      1231:                                        fatal_fr(r, "sshbuf_putf");
1.303     djm      1232:                                channel_request_start(ssh, c->self, "break", 0);
1.315     markus   1233:                                if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
                   1234:                                    (r = sshpkt_send(ssh)) != 0)
1.354     djm      1235:                                        fatal_fr(r, "send packet");
1.111     markus   1236:                                continue;
                   1237:
1.54      markus   1238:                        case 'R':
1.357     djm      1239:                                if (ssh->compat & SSH_BUG_NOREKEY)
1.292     djm      1240:                                        logit("Server does not "
                   1241:                                            "support re-keying");
                   1242:                                else
                   1243:                                        need_rekeying = 1;
1.54      markus   1244:                                continue;
                   1245:
1.242     dtucker  1246:                        case 'V':
                   1247:                                /* FALLTHROUGH */
                   1248:                        case 'v':
                   1249:                                if (c && c->ctl_chan != -1)
                   1250:                                        goto noescape;
                   1251:                                if (!log_is_on_stderr()) {
1.315     markus   1252:                                        if ((r = sshbuf_putf(berr,
1.242     dtucker  1253:                                            "%c%c [Logging to syslog]\r\n",
1.315     markus   1254:                                            efc->escape_char, ch)) != 0)
1.354     djm      1255:                                                fatal_fr(r, "sshbuf_putf");
1.242     dtucker  1256:                                        continue;
                   1257:                                }
                   1258:                                if (ch == 'V' && options.log_level >
                   1259:                                    SYSLOG_LEVEL_QUIET)
                   1260:                                        log_change_level(--options.log_level);
                   1261:                                if (ch == 'v' && options.log_level <
                   1262:                                    SYSLOG_LEVEL_DEBUG3)
                   1263:                                        log_change_level(++options.log_level);
1.315     markus   1264:                                if ((r = sshbuf_putf(berr,
1.294     djm      1265:                                    "%c%c [LogLevel %s]\r\n",
                   1266:                                    efc->escape_char, ch,
1.315     markus   1267:                                    log_level_name(options.log_level))) != 0)
1.354     djm      1268:                                        fatal_fr(r, "sshbuf_putf");
1.242     dtucker  1269:                                continue;
                   1270:
1.31      markus   1271:                        case '&':
1.392     dtucker  1272:                                if (c->ctl_chan != -1)
1.195     djm      1273:                                        goto noescape;
1.31      markus   1274:                                /*
1.197     djm      1275:                                 * Detach the program (continue to serve
                   1276:                                 * connections, but put in background and no
                   1277:                                 * more new connections).
1.31      markus   1278:                                 */
                   1279:                                /* Restore tty modes. */
1.233     djm      1280:                                leave_raw_mode(
                   1281:                                    options.request_tty == REQUEST_TTY_FORCE);
1.31      markus   1282:
                   1283:                                /* Stop listening for new connections. */
1.303     djm      1284:                                channel_stop_listening(ssh);
1.31      markus   1285:
1.354     djm      1286:                                if ((r = sshbuf_putf(berr, "%c& "
                   1287:                                    "[backgrounded]\n", efc->escape_char)) != 0)
                   1288:                                        fatal_fr(r, "sshbuf_putf");
1.31      markus   1289:
                   1290:                                /* Fork into background. */
                   1291:                                pid = fork();
1.326     deraadt  1292:                                if (pid == -1) {
1.31      markus   1293:                                        error("fork: %.100s", strerror(errno));
                   1294:                                        continue;
                   1295:                                }
                   1296:                                if (pid != 0) { /* This is the parent. */
                   1297:                                        /* The parent just exits. */
                   1298:                                        exit(0);
                   1299:                                }
                   1300:                                /* The child continues serving connections. */
1.292     djm      1301:                                /* fake EOF on stdin */
1.315     markus   1302:                                if ((r = sshbuf_put_u8(bin, 4)) != 0)
1.354     djm      1303:                                        fatal_fr(r, "sshbuf_put_u8");
1.292     djm      1304:                                return -1;
1.31      markus   1305:                        case '?':
1.294     djm      1306:                                print_escape_help(berr, efc->escape_char,
1.244     dtucker  1307:                                    (c && c->ctl_chan != -1),
                   1308:                                    log_is_on_stderr());
1.31      markus   1309:                                continue;
                   1310:
                   1311:                        case '#':
1.315     markus   1312:                                if ((r = sshbuf_putf(berr, "%c#\r\n",
                   1313:                                    efc->escape_char)) != 0)
1.354     djm      1314:                                        fatal_fr(r, "sshbuf_putf");
1.303     djm      1315:                                s = channel_open_message(ssh);
1.315     markus   1316:                                if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1.354     djm      1317:                                        fatal_fr(r, "sshbuf_put");
1.250     djm      1318:                                free(s);
1.97      jakob    1319:                                continue;
                   1320:
                   1321:                        case 'C':
1.217     djm      1322:                                if (c && c->ctl_chan != -1)
1.206     djm      1323:                                        goto noescape;
1.383     djm      1324:                                if (options.enable_escape_commandline == 0) {
                   1325:                                        if ((r = sshbuf_putf(berr,
                   1326:                                            "commandline disabled\r\n")) != 0)
                   1327:                                                fatal_fr(r, "sshbuf_putf");
                   1328:                                        continue;
                   1329:                                }
1.303     djm      1330:                                process_cmdline(ssh);
1.31      markus   1331:                                continue;
                   1332:
                   1333:                        default:
1.294     djm      1334:                                if (ch != efc->escape_char) {
1.315     markus   1335:                                        if ((r = sshbuf_put_u8(bin,
                   1336:                                            efc->escape_char)) != 0)
1.354     djm      1337:                                                fatal_fr(r, "sshbuf_put_u8");
1.31      markus   1338:                                        bytes++;
                   1339:                                }
                   1340:                                /* Escaped characters fall through here */
                   1341:                                break;
                   1342:                        }
                   1343:                } else {
                   1344:                        /*
1.197     djm      1345:                         * The previous character was not an escape char.
                   1346:                         * Check if this is an escape.
1.31      markus   1347:                         */
1.294     djm      1348:                        if (last_was_cr && ch == efc->escape_char) {
1.197     djm      1349:                                /*
                   1350:                                 * It is. Set the flag and continue to
                   1351:                                 * next character.
                   1352:                                 */
1.294     djm      1353:                                efc->escape_pending = 1;
1.31      markus   1354:                                continue;
                   1355:                        }
                   1356:                }
                   1357:
                   1358:                /*
                   1359:                 * Normal character.  Record whether it was a newline,
                   1360:                 * and append it to the buffer.
                   1361:                 */
                   1362:                last_was_cr = (ch == '\r' || ch == '\n');
1.315     markus   1363:                if ((r = sshbuf_put_u8(bin, ch)) != 0)
1.354     djm      1364:                        fatal_fr(r, "sshbuf_put_u8");
1.31      markus   1365:                bytes++;
                   1366:        }
                   1367:        return bytes;
                   1368: }
                   1369:
1.13      markus   1370: /*
1.15      markus   1371:  * Get packets from the connection input buffer, and process them as long as
                   1372:  * there are packets available.
                   1373:  *
                   1374:  * Any unknown packets received during the actual
                   1375:  * session cause the session to terminate.  This is
                   1376:  * intended to make debugging easier since no
                   1377:  * confirmations are sent.  Any compatible protocol
                   1378:  * extensions must be negotiated during the
                   1379:  * preparatory phase.
                   1380:  */
                   1381:
1.77      itojun   1382: static void
1.321     djm      1383: client_process_buffered_input_packets(struct ssh *ssh)
1.15      markus   1384: {
1.321     djm      1385:        ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1.15      markus   1386: }
                   1387:
1.31      markus   1388: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1389:
1.195     djm      1390: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1391: void *
                   1392: client_new_escape_filter_ctx(int escape_char)
                   1393: {
                   1394:        struct escape_filter_ctx *ret;
                   1395:
1.255     djm      1396:        ret = xcalloc(1, sizeof(*ret));
1.195     djm      1397:        ret->escape_pending = 0;
                   1398:        ret->escape_char = escape_char;
                   1399:        return (void *)ret;
                   1400: }
                   1401:
1.198     djm      1402: /* Free the escape filter context on channel free */
                   1403: void
1.303     djm      1404: client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1.198     djm      1405: {
1.250     djm      1406:        free(ctx);
1.198     djm      1407: }
                   1408:
1.195     djm      1409: int
1.303     djm      1410: client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1.30      markus   1411: {
1.190     djm      1412:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1413:                return 0;
                   1414:
1.303     djm      1415:        return process_escapes(ssh, c, c->input, c->output, c->extended,
1.195     djm      1416:            buf, len);
1.30      markus   1417: }
                   1418:
1.77      itojun   1419: static void
1.387     djm      1420: client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
1.60      markus   1421: {
1.303     djm      1422:        channel_cancel_cleanup(ssh, id);
1.60      markus   1423:        session_closed = 1;
1.233     djm      1424:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60      markus   1425: }
                   1426:
1.15      markus   1427: /*
1.13      markus   1428:  * Implements the interactive session with the server.  This is called after
                   1429:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1430:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1431:  * used as an escape character for terminating or suspending the session.
1.13      markus   1432:  */
1.20      markus   1433: int
1.303     djm      1434: client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
                   1435:     int ssh2_chan_id)
1.1       deraadt  1436: {
1.374     djm      1437:        struct pollfd *pfd = NULL;
                   1438:        u_int npfd_alloc = 0, npfd_active = 0;
1.11      markus   1439:        double start_time, total_time;
1.406   ! djm      1440:        int channel_did_enqueue = 0, r;
1.200     markus   1441:        u_int64_t ibytes, obytes;
1.374     djm      1442:        int conn_in_ready, conn_out_ready;
1.400     djm      1443:        sigset_t bsigset, osigset;
1.11      markus   1444:
                   1445:        debug("Entering interactive session.");
1.384     djm      1446:        session_ident = ssh2_chan_id;
1.277     semarie  1447:
1.278     semarie  1448:        if (options.control_master &&
1.286     djm      1449:            !option_clear_or_none(options.control_path)) {
1.278     semarie  1450:                debug("pledge: id");
1.327     mestre   1451:                if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1.278     semarie  1452:                    NULL) == -1)
1.354     djm      1453:                        fatal_f("pledge(): %s", strerror(errno));
1.278     semarie  1454:
                   1455:        } else if (options.forward_x11 || options.permit_local_command) {
1.277     semarie  1456:                debug("pledge: exec");
                   1457:                if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
                   1458:                    NULL) == -1)
1.354     djm      1459:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1460:
                   1461:        } else if (options.update_hostkeys) {
1.373     jsg      1462:                debug("pledge: filesystem");
1.277     semarie  1463:                if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
                   1464:                    NULL) == -1)
1.354     djm      1465:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1466:
1.286     djm      1467:        } else if (!option_clear_or_none(options.proxy_command) ||
1.369     djm      1468:            options.fork_after_authentication) {
1.277     semarie  1469:                debug("pledge: proc");
                   1470:                if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1.354     djm      1471:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1472:
                   1473:        } else {
                   1474:                debug("pledge: network");
1.300     mestre   1475:                if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1.354     djm      1476:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1477:        }
1.11      markus   1478:
1.384     djm      1479:        /* might be able to tighten now */
                   1480:        client_repledge();
                   1481:
1.307     dtucker  1482:        start_time = monotime_double();
1.11      markus   1483:
                   1484:        /* Initialize variables. */
                   1485:        last_was_cr = 1;
                   1486:        exit_status = -1;
1.320     djm      1487:        connection_in = ssh_packet_get_connection_in(ssh);
                   1488:        connection_out = ssh_packet_get_connection_out(ssh);
1.46      markus   1489:
1.11      markus   1490:        quit_pending = 0;
                   1491:
1.321     djm      1492:        client_init_dispatch(ssh);
1.15      markus   1493:
1.105     markus   1494:        /*
                   1495:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1496:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1497:         */
1.332     dtucker  1498:        if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1499:                ssh_signal(SIGHUP, signal_handler);
                   1500:        if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1501:                ssh_signal(SIGINT, signal_handler);
                   1502:        if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1503:                ssh_signal(SIGQUIT, signal_handler);
                   1504:        if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1505:                ssh_signal(SIGTERM, signal_handler);
                   1506:        ssh_signal(SIGWINCH, window_change_handler);
1.11      markus   1507:
                   1508:        if (have_pty)
1.233     djm      1509:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus   1510:
1.292     djm      1511:        if (session_ident != -1) {
                   1512:                if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1.303     djm      1513:                        channel_register_filter(ssh, session_ident,
1.292     djm      1514:                            client_simple_escape_filter, NULL,
                   1515:                            client_filter_cleanup,
                   1516:                            client_new_escape_filter_ctx(
                   1517:                            escape_char_arg));
1.232     djm      1518:                }
1.303     djm      1519:                channel_register_cleanup(ssh, session_ident,
1.292     djm      1520:                    client_channel_closed, 0);
1.48      markus   1521:        }
1.345     dtucker  1522:
                   1523:        schedule_server_alive_check();
1.30      markus   1524:
1.400     djm      1525:        if (sigemptyset(&bsigset) == -1 ||
                   1526:            sigaddset(&bsigset, SIGHUP) == -1 ||
                   1527:            sigaddset(&bsigset, SIGINT) == -1 ||
                   1528:            sigaddset(&bsigset, SIGQUIT) == -1 ||
                   1529:            sigaddset(&bsigset, SIGTERM) == -1)
                   1530:                error_f("bsigset setup: %s", strerror(errno));
                   1531:
1.11      markus   1532:        /* Main loop of the client for the interactive session mode. */
                   1533:        while (!quit_pending) {
1.396     djm      1534:                channel_did_enqueue = 0;
1.11      markus   1535:
1.13      markus   1536:                /* Process buffered packets sent by the server. */
1.321     djm      1537:                client_process_buffered_input_packets(ssh);
1.11      markus   1538:
1.303     djm      1539:                if (session_closed && !channel_still_open(ssh))
1.60      markus   1540:                        break;
                   1541:
1.303     djm      1542:                if (ssh_packet_is_rekeying(ssh)) {
1.56      markus   1543:                        debug("rekeying in progress");
1.284     djm      1544:                } else if (need_rekeying) {
                   1545:                        /* manual rekey request */
                   1546:                        debug("need rekeying");
1.303     djm      1547:                        if ((r = kex_start_rekex(ssh)) != 0)
1.354     djm      1548:                                fatal_fr(r, "kex_start_rekex");
1.284     djm      1549:                        need_rekeying = 0;
1.56      markus   1550:                } else {
                   1551:                        /*
                   1552:                         * Make packets from buffered channel data, and
                   1553:                         * enqueue them for sending to the server.
                   1554:                         */
1.320     djm      1555:                        if (ssh_packet_not_very_much_data_to_write(ssh))
1.396     djm      1556:                                channel_did_enqueue = channel_output_poll(ssh);
1.11      markus   1557:
1.56      markus   1558:                        /*
                   1559:                         * Check if the window size has changed, and buffer a
                   1560:                         * message about it to the server if so.
                   1561:                         */
1.303     djm      1562:                        client_check_window_change(ssh);
1.56      markus   1563:                }
1.13      markus   1564:                /*
                   1565:                 * Wait until we have something to do (something becomes
                   1566:                 * available on one of the descriptors).
                   1567:                 */
1.400     djm      1568:                if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
                   1569:                        error_f("bsigset sigprocmask: %s", strerror(errno));
                   1570:                if (quit_pending)
                   1571:                        break;
1.374     djm      1572:                client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
1.400     djm      1573:                    &npfd_active, channel_did_enqueue, &osigset,
1.374     djm      1574:                    &conn_in_ready, &conn_out_ready);
1.405     djm      1575:                if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
1.400     djm      1576:                        error_f("osigset sigprocmask: %s", strerror(errno));
1.11      markus   1577:
                   1578:                if (quit_pending)
                   1579:                        break;
                   1580:
1.379     djm      1581:                /* Do channel operations. */
                   1582:                channel_after_poll(ssh, pfd, npfd_active);
1.11      markus   1583:
1.17      markus   1584:                /* Buffer input from the connection.  */
1.374     djm      1585:                if (conn_in_ready)
                   1586:                        client_process_net_input(ssh);
1.17      markus   1587:
                   1588:                if (quit_pending)
                   1589:                        break;
1.367     djm      1590:
                   1591:                /* A timeout may have triggered rekeying */
                   1592:                if ((r = ssh_packet_check_rekey(ssh)) != 0)
                   1593:                        fatal_fr(r, "cannot start rekeying");
1.11      markus   1594:
1.197     djm      1595:                /*
                   1596:                 * Send as much buffered packet data as possible to the
                   1597:                 * sender.
                   1598:                 */
1.374     djm      1599:                if (conn_out_ready) {
1.338     djm      1600:                        if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   1601:                                sshpkt_fatal(ssh, r,
                   1602:                                    "%s: ssh_packet_write_poll", __func__);
                   1603:                        }
                   1604:                }
1.222     djm      1605:
                   1606:                /*
                   1607:                 * If we are a backgrounded control master, and the
                   1608:                 * timeout has expired without any active client
                   1609:                 * connections, then quit.
                   1610:                 */
                   1611:                if (control_persist_exit_time > 0) {
1.251     dtucker  1612:                        if (monotime() >= control_persist_exit_time) {
1.222     djm      1613:                                debug("ControlPersist timeout expired");
                   1614:                                break;
                   1615:                        }
                   1616:                }
1.11      markus   1617:        }
1.374     djm      1618:        free(pfd);
1.11      markus   1619:
                   1620:        /* Terminate the session. */
                   1621:
1.406   ! djm      1622:        /*
        !          1623:         * In interactive mode (with pseudo tty) display a message indicating
        !          1624:         * that the connection has been closed.
        !          1625:         */
        !          1626:        if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
        !          1627:                quit_message("Connection to %s closed.", host);
        !          1628:
        !          1629:
1.11      markus   1630:        /* Stop watching for window change. */
1.332     dtucker  1631:        ssh_signal(SIGWINCH, SIG_DFL);
1.211     andreas  1632:
1.320     djm      1633:        if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   1634:            (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
                   1635:            (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
                   1636:            (r = sshpkt_put_cstring(ssh, "")) != 0 ||   /* language tag */
                   1637:            (r = sshpkt_send(ssh)) != 0 ||
                   1638:            (r = ssh_packet_write_wait(ssh)) != 0)
1.354     djm      1639:                fatal_fr(r, "send disconnect");
1.11      markus   1640:
1.303     djm      1641:        channel_free_all(ssh);
1.11      markus   1642:
1.75      markus   1643:        if (have_pty)
1.233     djm      1644:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.116     dtucker  1645:
                   1646:        /*
                   1647:         * If there was no shell or command requested, there will be no remote
                   1648:         * exit status to be returned.  In that case, clear error code if the
                   1649:         * connection was deliberately terminated at this end.
                   1650:         */
1.370     djm      1651:        if (options.session_type == SESSION_TYPE_NONE &&
                   1652:            received_signal == SIGTERM) {
1.116     dtucker  1653:                received_signal = 0;
                   1654:                exit_status = 0;
                   1655:        }
1.75      markus   1656:
1.301     dtucker  1657:        if (received_signal) {
                   1658:                verbose("Killed by signal %d.", (int) received_signal);
1.359     djm      1659:                cleanup_exit(255);
1.301     dtucker  1660:        }
1.11      markus   1661:
                   1662:        /* Report bytes transferred, and transfer rates. */
1.307     dtucker  1663:        total_time = monotime_double() - start_time;
1.320     djm      1664:        ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.200     markus   1665:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229     djm      1666:            (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11      markus   1667:        if (total_time > 0)
1.200     markus   1668:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1669:                    obytes / total_time, ibytes / total_time);
1.11      markus   1670:        /* Return the exit status of the program. */
                   1671:        debug("Exit status %d", exit_status);
                   1672:        return exit_status;
1.15      markus   1673: }
                   1674:
                   1675: /*********/
                   1676:
1.77      itojun   1677: static Channel *
1.303     djm      1678: client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
                   1679:     int rchan, u_int rwindow, u_int rmaxpack)
1.40      markus   1680: {
1.103     deraadt  1681:        Channel *c = NULL;
1.289     markus   1682:        struct sshbuf *b = NULL;
1.40      markus   1683:        char *listen_address, *originator_address;
1.320     djm      1684:        u_int listen_port, originator_port;
1.289     markus   1685:        int r;
1.40      markus   1686:
                   1687:        /* Get rest of the packet */
1.320     djm      1688:        if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
                   1689:            (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
                   1690:            (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
                   1691:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
                   1692:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1693:                fatal_fr(r, "parse packet");
1.40      markus   1694:
1.354     djm      1695:        debug_f("listen %s port %d, originator %s port %d",
1.261     millert  1696:            listen_address, listen_port, originator_address, originator_port);
1.191     djm      1697:
1.320     djm      1698:        if (listen_port > 0xffff)
1.354     djm      1699:                error_f("invalid listen port");
1.320     djm      1700:        else if (originator_port > 0xffff)
1.354     djm      1701:                error_f("invalid originator port");
1.320     djm      1702:        else {
                   1703:                c = channel_connect_by_listen_address(ssh,
                   1704:                    listen_address, listen_port, "forwarded-tcpip",
                   1705:                    originator_address);
                   1706:        }
1.40      markus   1707:
1.289     markus   1708:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1709:                if ((b = sshbuf_new()) == NULL) {
1.354     djm      1710:                        error_f("alloc reply");
1.289     markus   1711:                        goto out;
                   1712:                }
                   1713:                /* reconstruct and send to muxclient */
                   1714:                if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
                   1715:                    (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1716:                    (r = sshbuf_put_cstring(b, request_type)) != 0 ||
                   1717:                    (r = sshbuf_put_u32(b, rchan)) != 0 ||
                   1718:                    (r = sshbuf_put_u32(b, rwindow)) != 0 ||
                   1719:                    (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
                   1720:                    (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
                   1721:                    (r = sshbuf_put_u32(b, listen_port)) != 0 ||
                   1722:                    (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
                   1723:                    (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1.303     djm      1724:                    (r = sshbuf_put_stringb(c->output, b)) != 0) {
1.354     djm      1725:                        error_fr(r, "compose for muxclient");
1.289     markus   1726:                        goto out;
                   1727:                }
                   1728:        }
                   1729:
                   1730:  out:
                   1731:        sshbuf_free(b);
1.250     djm      1732:        free(originator_address);
                   1733:        free(listen_address);
1.40      markus   1734:        return c;
                   1735: }
                   1736:
1.103     deraadt  1737: static Channel *
1.303     djm      1738: client_request_forwarded_streamlocal(struct ssh *ssh,
                   1739:     const char *request_type, int rchan)
1.261     millert  1740: {
                   1741:        Channel *c = NULL;
                   1742:        char *listen_path;
1.320     djm      1743:        int r;
1.261     millert  1744:
                   1745:        /* Get the remote path. */
1.320     djm      1746:        if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
                   1747:            (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 ||    /* reserved */
                   1748:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1749:                fatal_fr(r, "parse packet");
1.261     millert  1750:
1.354     djm      1751:        debug_f("request: %s", listen_path);
1.261     millert  1752:
1.303     djm      1753:        c = channel_connect_by_listen_path(ssh, listen_path,
1.261     millert  1754:            "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
                   1755:        free(listen_path);
                   1756:        return c;
                   1757: }
                   1758:
                   1759: static Channel *
1.303     djm      1760: client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1761: {
                   1762:        Channel *c = NULL;
                   1763:        char *originator;
1.321     djm      1764:        u_int originator_port;
1.320     djm      1765:        int r, sock;
1.40      markus   1766:
                   1767:        if (!options.forward_x11) {
                   1768:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1769:                error("Warning: this is probably a break-in attempt by a "
                   1770:                    "malicious server.");
1.221     djm      1771:                return NULL;
                   1772:        }
1.388     dtucker  1773:        if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1.221     djm      1774:                verbose("Rejected X11 connection after ForwardX11Timeout "
                   1775:                    "expired");
1.40      markus   1776:                return NULL;
                   1777:        }
1.320     djm      1778:        if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1.321     djm      1779:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1.320     djm      1780:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1781:                fatal_fr(r, "parse packet");
1.40      markus   1782:        /* XXX check permission */
1.321     djm      1783:        /* XXX range check originator port? */
                   1784:        debug("client_request_x11: request from %s %u", originator,
1.47      markus   1785:            originator_port);
1.250     djm      1786:        free(originator);
1.303     djm      1787:        sock = x11_connect_display(ssh);
1.67      markus   1788:        if (sock < 0)
                   1789:                return NULL;
1.399     djm      1790:        c = channel_new(ssh, "x11-connection",
1.67      markus   1791:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1792:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1793:        c->force_drain = 1;
1.40      markus   1794:        return c;
                   1795: }
                   1796:
1.103     deraadt  1797: static Channel *
1.303     djm      1798: client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1799: {
                   1800:        Channel *c = NULL;
1.262     djm      1801:        int r, sock;
1.40      markus   1802:
                   1803:        if (!options.forward_agent) {
                   1804:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1805:                error("Warning: this is probably a break-in attempt by a "
                   1806:                    "malicious server.");
1.40      markus   1807:                return NULL;
                   1808:        }
1.330     djm      1809:        if (forward_agent_sock_path == NULL) {
                   1810:                r = ssh_get_authentication_socket(&sock);
                   1811:        } else {
                   1812:                r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
                   1813:        }
                   1814:        if (r != 0) {
1.262     djm      1815:                if (r != SSH_ERR_AGENT_NOT_PRESENT)
1.354     djm      1816:                        debug_fr(r, "ssh_get_authentication_socket");
1.67      markus   1817:                return NULL;
1.262     djm      1818:        }
1.372     djm      1819:        if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
                   1820:            ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
                   1821:                debug_f("bound agent to hostkey");
                   1822:        else
                   1823:                debug2_fr(r, "ssh_agent_bind_hostkey");
                   1824:
1.399     djm      1825:        c = channel_new(ssh, "agent-connection",
1.67      markus   1826:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1827:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1828:            "authentication agent connection", 1);
1.82      markus   1829:        c->force_drain = 1;
1.40      markus   1830:        return c;
1.180     djm      1831: }
                   1832:
1.306     djm      1833: char *
1.303     djm      1834: client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1.343     djm      1835:     int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1.180     djm      1836: {
                   1837:        Channel *c;
1.320     djm      1838:        int r, fd;
1.306     djm      1839:        char *ifname = NULL;
1.180     djm      1840:
                   1841:        if (tun_mode == SSH_TUNMODE_NO)
                   1842:                return 0;
                   1843:
                   1844:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1845:
                   1846:        /* Open local tunnel device */
1.306     djm      1847:        if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1.180     djm      1848:                error("Tunnel device open failed.");
1.306     djm      1849:                return NULL;
1.180     djm      1850:        }
1.306     djm      1851:        debug("Tunnel forwarding using interface %s", ifname);
1.180     djm      1852:
1.399     djm      1853:        c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
1.180     djm      1854:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1855:        c->datagram = 1;
1.343     djm      1856:
                   1857:        if (cb != NULL)
                   1858:                channel_register_open_confirm(ssh, c->self, cb, cbctx);
1.180     djm      1859:
1.320     djm      1860:        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1861:            (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
                   1862:            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1863:            (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
                   1864:            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1865:            (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
                   1866:            (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
                   1867:            (r = sshpkt_send(ssh)) != 0)
1.321     djm      1868:                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.180     djm      1869:
1.306     djm      1870:        return ifname;
1.40      markus   1871: }
                   1872:
1.22      markus   1873: /* XXXX move to generic input handler */
1.264     markus   1874: static int
1.297     markus   1875: client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1.22      markus   1876: {
                   1877:        Channel *c = NULL;
1.320     djm      1878:        char *ctype = NULL;
                   1879:        int r;
                   1880:        u_int rchan;
                   1881:        size_t len;
                   1882:        u_int rmaxpack, rwindow;
                   1883:
                   1884:        if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
                   1885:            (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
                   1886:            (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
                   1887:            (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
                   1888:                goto out;
1.22      markus   1889:
1.24      markus   1890:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1891:            ctype, rchan, rwindow, rmaxpack);
                   1892:
1.40      markus   1893:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
1.303     djm      1894:                c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1.289     markus   1895:                    rmaxpack);
1.261     millert  1896:        } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1.303     djm      1897:                c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1.40      markus   1898:        } else if (strcmp(ctype, "x11") == 0) {
1.303     djm      1899:                c = client_request_x11(ssh, ctype, rchan);
1.40      markus   1900:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1.303     djm      1901:                c = client_request_agent(ssh, ctype, rchan);
1.22      markus   1902:        }
1.289     markus   1903:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1904:                debug3("proxied to downstream: %s", ctype);
                   1905:        } else if (c != NULL) {
1.22      markus   1906:                debug("confirm %s", ctype);
                   1907:                c->remote_id = rchan;
1.304     djm      1908:                c->have_remote_id = 1;
1.22      markus   1909:                c->remote_window = rwindow;
                   1910:                c->remote_maxpacket = rmaxpack;
1.69      markus   1911:                if (c->type != SSH_CHANNEL_CONNECTING) {
1.320     djm      1912:                        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
                   1913:                            (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1914:                            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1915:                            (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
                   1916:                            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1917:                            (r = sshpkt_send(ssh)) != 0)
                   1918:                                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.69      markus   1919:                }
1.22      markus   1920:        } else {
                   1921:                debug("failure %s", ctype);
1.320     djm      1922:                if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
                   1923:                    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
                   1924:                    (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
                   1925:                    (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
                   1926:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   1927:                    (r = sshpkt_send(ssh)) != 0)
                   1928:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.22      markus   1929:        }
1.320     djm      1930:        r = 0;
                   1931:  out:
1.250     djm      1932:        free(ctype);
1.320     djm      1933:        return r;
1.22      markus   1934: }
1.267     djm      1935:
1.264     markus   1936: static int
1.297     markus   1937: client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1.48      markus   1938: {
                   1939:        Channel *c = NULL;
1.320     djm      1940:        char *rtype = NULL;
                   1941:        u_char reply;
                   1942:        u_int id, exitval;
                   1943:        int r, success = 0;
                   1944:
                   1945:        if ((r = sshpkt_get_u32(ssh, &id)) != 0)
                   1946:                return r;
                   1947:        if (id <= INT_MAX)
                   1948:                c = channel_lookup(ssh, id);
1.297     markus   1949:        if (channel_proxy_upstream(c, type, seq, ssh))
1.289     markus   1950:                return 0;
1.320     djm      1951:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   1952:            (r = sshpkt_get_u8(ssh, &reply)) != 0)
                   1953:                goto out;
1.48      markus   1954:
1.320     djm      1955:        debug("client_input_channel_req: channel %u rtype %s reply %d",
1.48      markus   1956:            id, rtype, reply);
                   1957:
1.320     djm      1958:        if (c == NULL) {
1.197     djm      1959:                error("client_input_channel_req: channel %d: "
                   1960:                    "unknown channel", id);
1.193     markus   1961:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1.320     djm      1962:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1963:                        goto out;
1.303     djm      1964:                chan_rcvd_eow(ssh, c);
1.48      markus   1965:        } else if (strcmp(rtype, "exit-status") == 0) {
1.320     djm      1966:                if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
                   1967:                        goto out;
1.217     djm      1968:                if (c->ctl_chan != -1) {
1.303     djm      1969:                        mux_exit_message(ssh, c, exitval);
1.215     djm      1970:                        success = 1;
1.320     djm      1971:                } else if ((int)id == session_ident) {
1.215     djm      1972:                        /* Record exit value of local session */
1.123     djm      1973:                        success = 1;
                   1974:                        exit_status = exitval;
1.215     djm      1975:                } else {
1.218     djm      1976:                        /* Probably for a mux channel that has already closed */
1.354     djm      1977:                        debug_f("no sink for exit-status on channel %d",
                   1978:                            id);
1.123     djm      1979:                }
1.320     djm      1980:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1981:                        goto out;
1.48      markus   1982:        }
1.259     djm      1983:        if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.304     djm      1984:                if (!c->have_remote_id)
1.354     djm      1985:                        fatal_f("channel %d: no remote_id", c->self);
1.320     djm      1986:                if ((r = sshpkt_start(ssh, success ?
                   1987:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
                   1988:                    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1989:                    (r = sshpkt_send(ssh)) != 0)
                   1990:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.48      markus   1991:        }
1.320     djm      1992:        r = 0;
                   1993:  out:
1.250     djm      1994:        free(rtype);
1.320     djm      1995:        return r;
1.48      markus   1996: }
1.267     djm      1997:
1.269     djm      1998: struct hostkeys_update_ctx {
                   1999:        /* The hostname and (optionally) IP address string for the server */
                   2000:        char *host_str, *ip_str;
                   2001:
                   2002:        /*
                   2003:         * Keys received from the server and a flag for each indicating
                   2004:         * whether they already exist in known_hosts.
1.351     djm      2005:         * keys_match is filled in by hostkeys_find() and later (for new
1.381     djm      2006:         * keys) by client_global_hostkeys_prove_confirm().
1.269     djm      2007:         */
                   2008:        struct sshkey **keys;
1.351     djm      2009:        u_int *keys_match;      /* mask of HKF_MATCH_* from hostfile.h */
                   2010:        int *keys_verified;     /* flag for new keys verified by server */
                   2011:        size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
1.269     djm      2012:
                   2013:        /*
                   2014:         * Keys that are in known_hosts, but were not present in the update
                   2015:         * from the server (i.e. scheduled to be deleted).
                   2016:         * Filled in by hostkeys_find().
                   2017:         */
                   2018:        struct sshkey **old_keys;
                   2019:        size_t nold;
1.347     djm      2020:
                   2021:        /* Various special cases. */
1.350     djm      2022:        int complex_hostspec;   /* wildcard or manual pattern-list host name */
1.347     djm      2023:        int ca_available;       /* saw CA key for this host */
1.352     djm      2024:        int old_key_seen;       /* saw old key with other name/addr */
1.353     djm      2025:        int other_name_seen;    /* saw key with other name/addr */
1.269     djm      2026: };
                   2027:
                   2028: static void
                   2029: hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
                   2030: {
                   2031:        size_t i;
                   2032:
                   2033:        if (ctx == NULL)
                   2034:                return;
                   2035:        for (i = 0; i < ctx->nkeys; i++)
                   2036:                sshkey_free(ctx->keys[i]);
                   2037:        free(ctx->keys);
1.351     djm      2038:        free(ctx->keys_match);
                   2039:        free(ctx->keys_verified);
1.269     djm      2040:        for (i = 0; i < ctx->nold; i++)
                   2041:                sshkey_free(ctx->old_keys[i]);
                   2042:        free(ctx->old_keys);
                   2043:        free(ctx->host_str);
                   2044:        free(ctx->ip_str);
                   2045:        free(ctx);
                   2046: }
                   2047:
1.350     djm      2048: /*
                   2049:  * Returns non-zero if a known_hosts hostname list is not of a form that
                   2050:  * can be handled by UpdateHostkeys. These include wildcard hostnames and
                   2051:  * hostnames lists that do not follow the form host[,ip].
                   2052:  */
                   2053: static int
                   2054: hostspec_is_complex(const char *hosts)
                   2055: {
                   2056:        char *cp;
                   2057:
                   2058:        /* wildcard */
                   2059:        if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
                   2060:                return 1;
                   2061:        /* single host/ip = ok */
                   2062:        if ((cp = strchr(hosts, ',')) == NULL)
                   2063:                return 0;
                   2064:        /* more than two entries on the line */
                   2065:        if (strchr(cp + 1, ',') != NULL)
                   2066:                return 1;
                   2067:        /* XXX maybe parse cp+1 and ensure it is an IP? */
                   2068:        return 0;
                   2069: }
                   2070:
1.352     djm      2071: /* callback to search for ctx->keys in known_hosts */
1.269     djm      2072: static int
                   2073: hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
                   2074: {
                   2075:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2076:        size_t i;
                   2077:        struct sshkey **tmp;
                   2078:
1.353     djm      2079:        if (l->key == NULL)
1.269     djm      2080:                return 0;
1.353     djm      2081:        if (l->status != HKF_STATUS_MATCHED) {
                   2082:                /* Record if one of the keys appears on a non-matching line */
                   2083:                for (i = 0; i < ctx->nkeys; i++) {
                   2084:                        if (sshkey_equal(l->key, ctx->keys[i])) {
                   2085:                                ctx->other_name_seen = 1;
1.354     djm      2086:                                debug3_f("found %s key under different "
                   2087:                                    "name/addr at %s:%ld",
1.353     djm      2088:                                    sshkey_ssh_name(ctx->keys[i]),
                   2089:                                    l->path, l->linenum);
                   2090:                                return 0;
                   2091:                        }
                   2092:                }
                   2093:                return 0;
                   2094:        }
                   2095:        /* Don't proceed if revocation or CA markers are present */
                   2096:        /* XXX relax this */
                   2097:        if (l->marker != MRK_NONE) {
1.354     djm      2098:                debug3_f("hostkeys file %s:%ld has CA/revocation marker",
                   2099:                    l->path, l->linenum);
1.353     djm      2100:                ctx->complex_hostspec = 1;
                   2101:                return 0;
                   2102:        }
                   2103:
1.355     djm      2104:        /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
                   2105:        if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
                   2106:                if ((l->match & HKF_MATCH_HOST) == 0) {
                   2107:                        /* Record if address matched a different hostname. */
                   2108:                        ctx->other_name_seen = 1;
                   2109:                        debug3_f("found address %s against different hostname "
                   2110:                            "at %s:%ld", ctx->ip_str, l->path, l->linenum);
                   2111:                        return 0;
                   2112:                } else if ((l->match & HKF_MATCH_IP) == 0) {
                   2113:                        /* Record if hostname matched a different address. */
                   2114:                        ctx->other_name_seen = 1;
                   2115:                        debug3_f("found hostname %s against different address "
                   2116:                            "at %s:%ld", ctx->host_str, l->path, l->linenum);
                   2117:                }
1.353     djm      2118:        }
1.269     djm      2119:
1.350     djm      2120:        /*
                   2121:         * UpdateHostkeys is skipped for wildcard host names and hostnames
                   2122:         * that contain more than two entries (ssh never writes these).
                   2123:         */
                   2124:        if (hostspec_is_complex(l->hosts)) {
1.354     djm      2125:                debug3_f("hostkeys file %s:%ld complex host specification",
                   2126:                    l->path, l->linenum);
1.350     djm      2127:                ctx->complex_hostspec = 1;
1.347     djm      2128:                return 0;
                   2129:        }
                   2130:
1.269     djm      2131:        /* Mark off keys we've already seen for this host */
                   2132:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2133:                if (!sshkey_equal(l->key, ctx->keys[i]))
                   2134:                        continue;
1.354     djm      2135:                debug3_f("found %s key at %s:%ld",
1.351     djm      2136:                    sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
                   2137:                ctx->keys_match[i] |= l->match;
                   2138:                return 0;
1.269     djm      2139:        }
                   2140:        /* This line contained a key that not offered by the server */
1.354     djm      2141:        debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
                   2142:            l->path, l->linenum);
1.299     deraadt  2143:        if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1.269     djm      2144:            sizeof(*ctx->old_keys))) == NULL)
1.354     djm      2145:                fatal_f("recallocarray failed nold = %zu", ctx->nold);
1.269     djm      2146:        ctx->old_keys = tmp;
                   2147:        ctx->old_keys[ctx->nold++] = l->key;
                   2148:        l->key = NULL;
                   2149:
                   2150:        return 0;
                   2151: }
                   2152:
1.352     djm      2153: /* callback to search for ctx->old_keys in known_hosts under other names */
                   2154: static int
                   2155: hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
                   2156: {
                   2157:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2158:        size_t i;
                   2159:        int hashed;
                   2160:
                   2161:        /* only care about lines that *don't* match the active host spec */
                   2162:        if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
                   2163:                return 0;
                   2164:
                   2165:        hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
                   2166:        for (i = 0; i < ctx->nold; i++) {
                   2167:                if (!sshkey_equal(l->key, ctx->old_keys[i]))
                   2168:                        continue;
1.354     djm      2169:                debug3_f("found deprecated %s key at %s:%ld as %s",
1.364     djm      2170:                    sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
1.352     djm      2171:                    hashed ? "[HASHED]" : l->hosts);
                   2172:                ctx->old_key_seen = 1;
                   2173:                break;
                   2174:        }
                   2175:        return 0;
                   2176: }
                   2177:
                   2178: /*
                   2179:  * Check known_hosts files for deprecated keys under other names. Returns 0
                   2180:  * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
                   2181:  * exist under names other than the active hostname/IP.
                   2182:  */
                   2183: static int
                   2184: check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
                   2185: {
                   2186:        size_t i;
                   2187:        int r;
                   2188:
1.354     djm      2189:        debug2_f("checking for %zu deprecated keys", ctx->nold);
1.352     djm      2190:        for (i = 0; i < options.num_user_hostfiles; i++) {
1.354     djm      2191:                debug3_f("searching %s for %s / %s",
1.352     djm      2192:                    options.user_hostfiles[i], ctx->host_str,
                   2193:                    ctx->ip_str ? ctx->ip_str : "(none)");
                   2194:                if ((r = hostkeys_foreach(options.user_hostfiles[i],
                   2195:                    hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
1.356     djm      2196:                    HKF_WANT_PARSE_KEY, 0)) != 0) {
1.352     djm      2197:                        if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354     djm      2198:                                debug_f("hostkeys file %s does not exist",
                   2199:                                    options.user_hostfiles[i]);
1.352     djm      2200:                                continue;
                   2201:                        }
1.354     djm      2202:                        error_fr(r, "hostkeys_foreach failed for %s",
                   2203:                            options.user_hostfiles[i]);
1.352     djm      2204:                        return -1;
                   2205:                }
                   2206:        }
                   2207:        return 0;
                   2208: }
                   2209:
1.269     djm      2210: static void
1.337     djm      2211: hostkey_change_preamble(LogLevel loglevel)
1.269     djm      2212: {
1.336     djm      2213:        do_log2(loglevel, "The server has updated its host keys.");
                   2214:        do_log2(loglevel, "These changes were verified by the server's "
                   2215:            "existing trusted key.");
                   2216: }
                   2217:
                   2218: static void
                   2219: update_known_hosts(struct hostkeys_update_ctx *ctx)
                   2220: {
                   2221:        int r, was_raw = 0, first = 1;
                   2222:        int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
                   2223:        LogLevel loglevel = asking ?  SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1.269     djm      2224:        char *fp, *response;
                   2225:        size_t i;
1.333     djm      2226:        struct stat sb;
1.269     djm      2227:
                   2228:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2229:                if (!ctx->keys_verified[i])
1.269     djm      2230:                        continue;
                   2231:                if ((fp = sshkey_fingerprint(ctx->keys[i],
                   2232:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354     djm      2233:                        fatal_f("sshkey_fingerprint failed");
1.336     djm      2234:                if (first && asking)
1.337     djm      2235:                        hostkey_change_preamble(loglevel);
1.269     djm      2236:                do_log2(loglevel, "Learned new hostkey: %s %s",
                   2237:                    sshkey_type(ctx->keys[i]), fp);
1.336     djm      2238:                first = 0;
1.269     djm      2239:                free(fp);
                   2240:        }
                   2241:        for (i = 0; i < ctx->nold; i++) {
                   2242:                if ((fp = sshkey_fingerprint(ctx->old_keys[i],
                   2243:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354     djm      2244:                        fatal_f("sshkey_fingerprint failed");
1.336     djm      2245:                if (first && asking)
1.337     djm      2246:                        hostkey_change_preamble(loglevel);
1.269     djm      2247:                do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
                   2248:                    sshkey_type(ctx->old_keys[i]), fp);
1.336     djm      2249:                first = 0;
1.269     djm      2250:                free(fp);
                   2251:        }
                   2252:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1.271     djm      2253:                if (get_saved_tio() != NULL) {
                   2254:                        leave_raw_mode(1);
                   2255:                        was_raw = 1;
                   2256:                }
1.269     djm      2257:                response = NULL;
                   2258:                for (i = 0; !quit_pending && i < 3; i++) {
                   2259:                        free(response);
                   2260:                        response = read_passphrase("Accept updated hostkeys? "
                   2261:                            "(yes/no): ", RP_ECHO);
1.389     dtucker  2262:                        if (response != NULL && strcasecmp(response, "yes") == 0)
1.269     djm      2263:                                break;
                   2264:                        else if (quit_pending || response == NULL ||
                   2265:                            strcasecmp(response, "no") == 0) {
                   2266:                                options.update_hostkeys = 0;
                   2267:                                break;
                   2268:                        } else {
                   2269:                                do_log2(loglevel, "Please enter "
                   2270:                                    "\"yes\" or \"no\"");
                   2271:                        }
                   2272:                }
                   2273:                if (quit_pending || i >= 3 || response == NULL)
                   2274:                        options.update_hostkeys = 0;
                   2275:                free(response);
1.271     djm      2276:                if (was_raw)
                   2277:                        enter_raw_mode(1);
1.269     djm      2278:        }
1.333     djm      2279:        if (options.update_hostkeys == 0)
                   2280:                return;
1.269     djm      2281:        /*
                   2282:         * Now that all the keys are verified, we can go ahead and replace
                   2283:         * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
                   2284:         * cancel the operation).
                   2285:         */
1.333     djm      2286:        for (i = 0; i < options.num_user_hostfiles; i++) {
                   2287:                /*
                   2288:                 * NB. keys are only added to hostfiles[0], for the rest we
                   2289:                 * just delete the hostname entries.
                   2290:                 */
                   2291:                if (stat(options.user_hostfiles[i], &sb) != 0) {
                   2292:                        if (errno == ENOENT) {
1.354     djm      2293:                                debug_f("known hosts file %s does not "
                   2294:                                    "exist", options.user_hostfiles[i]);
1.333     djm      2295:                        } else {
1.354     djm      2296:                                error_f("known hosts file %s "
                   2297:                                    "inaccessible: %s",
                   2298:                                    options.user_hostfiles[i], strerror(errno));
1.333     djm      2299:                        }
                   2300:                        continue;
                   2301:                }
                   2302:                if ((r = hostfile_replace_entries(options.user_hostfiles[i],
                   2303:                    ctx->host_str, ctx->ip_str,
                   2304:                    i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
                   2305:                    options.hash_known_hosts, 0,
                   2306:                    options.fingerprint_hash)) != 0) {
1.354     djm      2307:                        error_fr(r, "hostfile_replace_entries failed for %s",
                   2308:                            options.user_hostfiles[i]);
1.333     djm      2309:                }
                   2310:        }
1.269     djm      2311: }
                   2312:
                   2313: static void
1.381     djm      2314: client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
1.303     djm      2315:     u_int32_t seq, void *_ctx)
1.269     djm      2316: {
                   2317:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2318:        size_t i, ndone;
                   2319:        struct sshbuf *signdata;
1.375     djm      2320:        int r, plaintype;
1.269     djm      2321:        const u_char *sig;
1.375     djm      2322:        const char *rsa_kexalg = NULL;
                   2323:        char *alg = NULL;
1.269     djm      2324:        size_t siglen;
                   2325:
                   2326:        if (ctx->nnew == 0)
1.354     djm      2327:                fatal_f("ctx->nnew == 0"); /* sanity */
1.269     djm      2328:        if (type != SSH2_MSG_REQUEST_SUCCESS) {
                   2329:                error("Server failed to confirm ownership of "
                   2330:                    "private host keys");
                   2331:                hostkeys_update_ctx_free(ctx);
                   2332:                return;
                   2333:        }
1.375     djm      2334:        if (sshkey_type_plain(sshkey_type_from_name(
                   2335:            ssh->kex->hostkey_alg)) == KEY_RSA)
                   2336:                rsa_kexalg = ssh->kex->hostkey_alg;
1.269     djm      2337:        if ((signdata = sshbuf_new()) == NULL)
1.354     djm      2338:                fatal_f("sshbuf_new failed");
1.269     djm      2339:        /*
                   2340:         * Expect a signature for each of the ctx->nnew private keys we
                   2341:         * haven't seen before. They will be in the same order as the
1.351     djm      2342:         * ctx->keys where the corresponding ctx->keys_match[i] == 0.
1.269     djm      2343:         */
                   2344:        for (ndone = i = 0; i < ctx->nkeys; i++) {
1.351     djm      2345:                if (ctx->keys_match[i])
1.269     djm      2346:                        continue;
1.375     djm      2347:                plaintype = sshkey_type_plain(ctx->keys[i]->type);
1.269     djm      2348:                /* Prepare data to be signed: session ID, unique string, key */
                   2349:                sshbuf_reset(signdata);
1.270     djm      2350:                if ( (r = sshbuf_put_cstring(signdata,
                   2351:                    "hostkeys-prove-00@openssh.com")) != 0 ||
1.358     djm      2352:                    (r = sshbuf_put_stringb(signdata,
                   2353:                    ssh->kex->session_id)) != 0 ||
1.269     djm      2354:                    (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1.354     djm      2355:                        fatal_fr(r, "compose signdata");
1.269     djm      2356:                /* Extract and verify signature */
                   2357:                if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1.354     djm      2358:                        error_fr(r, "parse sig");
1.269     djm      2359:                        goto out;
                   2360:                }
1.375     djm      2361:                if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
                   2362:                        error_fr(r, "server gave unintelligible signature "
                   2363:                            "for %s key %zu", sshkey_type(ctx->keys[i]), i);
                   2364:                        goto out;
                   2365:                }
1.309     djm      2366:                /*
1.375     djm      2367:                 * Special case for RSA keys: if a RSA hostkey was negotiated,
                   2368:                 * then use its signature type for verification of RSA hostkey
                   2369:                 * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
1.309     djm      2370:                 */
1.375     djm      2371:                if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
                   2372:                    match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
                   2373:                        debug_f("server used untrusted RSA signature algorithm "
                   2374:                            "%s for key %zu, disregarding", alg, i);
                   2375:                        free(alg);
                   2376:                        /* zap the key from the list */
                   2377:                        sshkey_free(ctx->keys[i]);
                   2378:                        ctx->keys[i] = NULL;
                   2379:                        ndone++;
                   2380:                        continue;
                   2381:                }
                   2382:                debug3_f("verify %s key %zu using sigalg %s",
                   2383:                    sshkey_type(ctx->keys[i]), i, alg);
                   2384:                free(alg);
1.269     djm      2385:                if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1.308     djm      2386:                    sshbuf_ptr(signdata), sshbuf_len(signdata),
1.375     djm      2387:                    plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
1.361     djm      2388:                        error_fr(r, "server gave bad signature for %s key %zu",
1.354     djm      2389:                            sshkey_type(ctx->keys[i]), i);
1.269     djm      2390:                        goto out;
                   2391:                }
                   2392:                /* Key is good. Mark it as 'seen' */
1.351     djm      2393:                ctx->keys_verified[i] = 1;
1.269     djm      2394:                ndone++;
                   2395:        }
1.354     djm      2396:        /* Shouldn't happen */
1.269     djm      2397:        if (ndone != ctx->nnew)
1.354     djm      2398:                fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
1.320     djm      2399:        if ((r = sshpkt_get_end(ssh)) != 0) {
1.354     djm      2400:                error_f("protocol error");
1.320     djm      2401:                goto out;
                   2402:        }
1.269     djm      2403:
                   2404:        /* Make the edits to known_hosts */
                   2405:        update_known_hosts(ctx);
                   2406:  out:
                   2407:        hostkeys_update_ctx_free(ctx);
1.384     djm      2408:        hostkeys_update_complete = 1;
                   2409:        client_repledge();
1.269     djm      2410: }
                   2411:
1.267     djm      2412: /*
1.270     djm      2413:  * Handle hostkeys-00@openssh.com global request to inform the client of all
1.267     djm      2414:  * the server's hostkeys. The keys are checked against the user's
                   2415:  * HostkeyAlgorithms preference before they are accepted.
                   2416:  */
                   2417: static int
1.321     djm      2418: client_input_hostkeys(struct ssh *ssh)
1.267     djm      2419: {
                   2420:        const u_char *blob = NULL;
1.269     djm      2421:        size_t i, len = 0;
1.267     djm      2422:        struct sshbuf *buf = NULL;
1.269     djm      2423:        struct sshkey *key = NULL, **tmp;
1.384     djm      2424:        int r, prove_sent = 0;
1.269     djm      2425:        char *fp;
1.267     djm      2426:        static int hostkeys_seen = 0; /* XXX use struct ssh */
1.268     djm      2427:        extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1.272     djm      2428:        struct hostkeys_update_ctx *ctx = NULL;
1.351     djm      2429:        u_int want;
1.267     djm      2430:
                   2431:        if (hostkeys_seen)
1.354     djm      2432:                fatal_f("server already sent hostkeys");
1.384     djm      2433:        if (!can_update_hostkeys())
1.267     djm      2434:                return 1;
1.384     djm      2435:        hostkeys_seen = 1;
1.272     djm      2436:
                   2437:        ctx = xcalloc(1, sizeof(*ctx));
1.269     djm      2438:        while (ssh_packet_remaining(ssh) > 0) {
1.267     djm      2439:                sshkey_free(key);
                   2440:                key = NULL;
1.269     djm      2441:                if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
1.354     djm      2442:                        error_fr(r, "parse key");
1.269     djm      2443:                        goto out;
                   2444:                }
1.270     djm      2445:                if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
1.354     djm      2446:                        do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
1.335     djm      2447:                            SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
1.354     djm      2448:                            "convert key");
1.335     djm      2449:                        continue;
1.270     djm      2450:                }
1.267     djm      2451:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                   2452:                    SSH_FP_DEFAULT);
1.354     djm      2453:                debug3_f("received %s key %s", sshkey_type(key), fp);
1.267     djm      2454:                free(fp);
1.275     markus   2455:
1.404     djm      2456:                if (!hostkey_accepted_by_hostkeyalgs(key)) {
1.354     djm      2457:                        debug3_f("%s key not permitted by "
                   2458:                            "HostkeyAlgorithms", sshkey_ssh_name(key));
1.267     djm      2459:                        continue;
                   2460:                }
1.269     djm      2461:                /* Skip certs */
                   2462:                if (sshkey_is_cert(key)) {
1.354     djm      2463:                        debug3_f("%s key is a certificate; skipping",
                   2464:                            sshkey_ssh_name(key));
1.269     djm      2465:                        continue;
                   2466:                }
                   2467:                /* Ensure keys are unique */
                   2468:                for (i = 0; i < ctx->nkeys; i++) {
                   2469:                        if (sshkey_equal(key, ctx->keys[i])) {
1.354     djm      2470:                                error_f("received duplicated %s host key",
                   2471:                                    sshkey_ssh_name(key));
1.269     djm      2472:                                goto out;
                   2473:                        }
                   2474:                }
                   2475:                /* Key is good, record it */
1.299     deraadt  2476:                if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
1.269     djm      2477:                    sizeof(*ctx->keys))) == NULL)
1.354     djm      2478:                        fatal_f("recallocarray failed nkeys = %zu",
                   2479:                            ctx->nkeys);
1.269     djm      2480:                ctx->keys = tmp;
                   2481:                ctx->keys[ctx->nkeys++] = key;
1.267     djm      2482:                key = NULL;
                   2483:        }
                   2484:
1.269     djm      2485:        if (ctx->nkeys == 0) {
1.354     djm      2486:                debug_f("server sent no hostkeys");
1.267     djm      2487:                goto out;
                   2488:        }
1.270     djm      2489:
1.351     djm      2490:        if ((ctx->keys_match = calloc(ctx->nkeys,
                   2491:            sizeof(*ctx->keys_match))) == NULL ||
                   2492:            (ctx->keys_verified = calloc(ctx->nkeys,
                   2493:            sizeof(*ctx->keys_verified))) == NULL)
1.354     djm      2494:                fatal_f("calloc failed");
1.267     djm      2495:
1.268     djm      2496:        get_hostfile_hostname_ipaddr(host,
                   2497:            options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
1.269     djm      2498:            options.port, &ctx->host_str,
                   2499:            options.check_host_ip ? &ctx->ip_str : NULL);
1.268     djm      2500:
1.269     djm      2501:        /* Find which keys we already know about. */
1.333     djm      2502:        for (i = 0; i < options.num_user_hostfiles; i++) {
1.354     djm      2503:                debug_f("searching %s for %s / %s",
1.339     dtucker  2504:                    options.user_hostfiles[i], ctx->host_str,
1.340     dtucker  2505:                    ctx->ip_str ? ctx->ip_str : "(none)");
1.333     djm      2506:                if ((r = hostkeys_foreach(options.user_hostfiles[i],
                   2507:                    hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
1.356     djm      2508:                    HKF_WANT_PARSE_KEY, 0)) != 0) {
1.333     djm      2509:                        if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354     djm      2510:                                debug_f("hostkeys file %s does not exist",
                   2511:                                    options.user_hostfiles[i]);
1.333     djm      2512:                                continue;
                   2513:                        }
1.354     djm      2514:                        error_fr(r, "hostkeys_foreach failed for %s",
                   2515:                            options.user_hostfiles[i]);
1.333     djm      2516:                        goto out;
                   2517:                }
1.267     djm      2518:        }
                   2519:
1.269     djm      2520:        /* Figure out if we have any new keys to add */
1.351     djm      2521:        ctx->nnew = ctx->nincomplete = 0;
                   2522:        want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
1.269     djm      2523:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2524:                if (ctx->keys_match[i] == 0)
1.269     djm      2525:                        ctx->nnew++;
1.351     djm      2526:                if ((ctx->keys_match[i] & want) != want)
                   2527:                        ctx->nincomplete++;
1.269     djm      2528:        }
                   2529:
1.354     djm      2530:        debug3_f("%zu server keys: %zu new, %zu retained, "
                   2531:            "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
                   2532:            ctx->nkeys - ctx->nnew - ctx->nincomplete,
1.351     djm      2533:            ctx->nincomplete, ctx->nold);
1.269     djm      2534:
1.353     djm      2535:        if (ctx->nnew == 0 && ctx->nold == 0) {
1.354     djm      2536:                debug_f("no new or deprecated keys from server");
1.353     djm      2537:                goto out;
                   2538:        }
                   2539:
                   2540:        /* Various reasons why we cannot proceed with the update */
                   2541:        if (ctx->complex_hostspec) {
1.354     djm      2542:                debug_f("CA/revocation marker, manual host list or wildcard "
                   2543:                    "host pattern found, skipping UserKnownHostsFile update");
1.353     djm      2544:                goto out;
                   2545:        }
                   2546:        if (ctx->other_name_seen) {
1.354     djm      2547:                debug_f("host key found matching a different name/address, "
                   2548:                    "skipping UserKnownHostsFile update");
1.347     djm      2549:                goto out;
1.352     djm      2550:        }
                   2551:        /*
                   2552:         * If removing keys, check whether they appear under different
                   2553:         * names/addresses and refuse to proceed if they do. This avoids
                   2554:         * cases such as hosts with multiple names becoming inconsistent
                   2555:         * with regards to CheckHostIP entries.
                   2556:         * XXX UpdateHostkeys=force to override this (and other) checks?
                   2557:         */
                   2558:        if (ctx->nold != 0) {
                   2559:                if (check_old_keys_othernames(ctx) != 0)
                   2560:                        goto out; /* error already logged */
                   2561:                if (ctx->old_key_seen) {
1.354     djm      2562:                        debug_f("key(s) for %s%s%s exist under other names; "
                   2563:                            "skipping UserKnownHostsFile update",
1.352     djm      2564:                            ctx->host_str, ctx->ip_str == NULL ? "" : ",",
                   2565:                            ctx->ip_str == NULL ? "" : ctx->ip_str);
                   2566:                        goto out;
                   2567:                }
                   2568:        }
                   2569:
1.353     djm      2570:        if (ctx->nnew == 0) {
1.351     djm      2571:                /*
                   2572:                 * We have some keys to remove or fix matching for.
                   2573:                 * We can proceed to do this without requiring a fresh proof
                   2574:                 * from the server.
                   2575:                 */
1.269     djm      2576:                update_known_hosts(ctx);
1.353     djm      2577:                goto out;
                   2578:        }
                   2579:        /*
                   2580:         * We have received previously-unseen keys from the server.
                   2581:         * Ask the server to confirm ownership of the private halves.
                   2582:         */
1.354     djm      2583:        debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
1.353     djm      2584:        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   2585:            (r = sshpkt_put_cstring(ssh,
                   2586:            "hostkeys-prove-00@openssh.com")) != 0 ||
                   2587:            (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
1.354     djm      2588:                fatal_fr(r, "prepare hostkeys-prove");
1.353     djm      2589:        if ((buf = sshbuf_new()) == NULL)
1.354     djm      2590:                fatal_f("sshbuf_new");
1.353     djm      2591:        for (i = 0; i < ctx->nkeys; i++) {
                   2592:                if (ctx->keys_match[i])
                   2593:                        continue;
                   2594:                sshbuf_reset(buf);
                   2595:                if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
1.354     djm      2596:                    (r = sshpkt_put_stringb(ssh, buf)) != 0)
                   2597:                        fatal_fr(r, "assemble hostkeys-prove");
1.269     djm      2598:        }
1.353     djm      2599:        if ((r = sshpkt_send(ssh)) != 0)
1.354     djm      2600:                fatal_fr(r, "send hostkeys-prove");
1.353     djm      2601:        client_register_global_confirm(
1.381     djm      2602:            client_global_hostkeys_prove_confirm, ctx);
1.353     djm      2603:        ctx = NULL;  /* will be freed in callback */
1.384     djm      2604:        prove_sent = 1;
1.269     djm      2605:
1.267     djm      2606:        /* Success */
                   2607:  out:
1.269     djm      2608:        hostkeys_update_ctx_free(ctx);
1.267     djm      2609:        sshkey_free(key);
                   2610:        sshbuf_free(buf);
1.384     djm      2611:        if (!prove_sent) {
                   2612:                /* UpdateHostkeys handling completed */
                   2613:                hostkeys_update_complete = 1;
                   2614:                client_repledge();
                   2615:        }
1.269     djm      2616:        /*
                   2617:         * NB. Return success for all cases. The server doesn't need to know
                   2618:         * what the client does with its hosts file.
                   2619:         */
                   2620:        return 1;
1.267     djm      2621: }
                   2622:
1.264     markus   2623: static int
1.297     markus   2624: client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
1.95      markus   2625: {
                   2626:        char *rtype;
1.320     djm      2627:        u_char want_reply;
                   2628:        int r, success = 0;
1.95      markus   2629:
1.320     djm      2630:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   2631:            (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
                   2632:                goto out;
1.117     markus   2633:        debug("client_input_global_request: rtype %s want_reply %d",
                   2634:            rtype, want_reply);
1.270     djm      2635:        if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
1.321     djm      2636:                success = client_input_hostkeys(ssh);
1.95      markus   2637:        if (want_reply) {
1.320     djm      2638:                if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
                   2639:                    SSH2_MSG_REQUEST_FAILURE)) != 0 ||
                   2640:                    (r = sshpkt_send(ssh)) != 0 ||
                   2641:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   2642:                        goto out;
1.95      markus   2643:        }
1.320     djm      2644:        r = 0;
                   2645:  out:
1.250     djm      2646:        free(rtype);
1.320     djm      2647:        return r;
1.95      markus   2648: }
1.22      markus   2649:
1.354     djm      2650: static void
                   2651: client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
                   2652: {
                   2653:        int r;
                   2654:
                   2655:        debug("channel %d: setting env %s = \"%s\"", id, name, val);
                   2656:        channel_request_start(ssh, id, "env", 0);
                   2657:        if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
                   2658:            (r = sshpkt_put_cstring(ssh, val)) != 0 ||
                   2659:            (r = sshpkt_send(ssh)) != 0)
                   2660:                fatal_fr(r, "send setenv");
                   2661: }
                   2662:
1.123     djm      2663: void
1.303     djm      2664: client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
1.315     markus   2665:     const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
                   2666:     char **env)
1.123     djm      2667: {
1.380     djm      2668:        size_t i, j, len;
                   2669:        int matched, r;
1.313     djm      2670:        char *name, *val;
1.132     djm      2671:        Channel *c = NULL;
1.123     djm      2672:
1.354     djm      2673:        debug2_f("id %d", id);
1.123     djm      2674:
1.303     djm      2675:        if ((c = channel_lookup(ssh, id)) == NULL)
1.354     djm      2676:                fatal_f("channel %d: unknown channel", id);
1.224     djm      2677:
1.320     djm      2678:        ssh_packet_set_interactive(ssh, want_tty,
1.224     djm      2679:            options.ip_qos_interactive, options.ip_qos_bulk);
1.132     djm      2680:
1.123     djm      2681:        if (want_tty) {
                   2682:                struct winsize ws;
                   2683:
                   2684:                /* Store window size in the packet. */
1.326     deraadt  2685:                if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
1.123     djm      2686:                        memset(&ws, 0, sizeof(ws));
                   2687:
1.303     djm      2688:                channel_request_start(ssh, id, "pty-req", 1);
                   2689:                client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
1.320     djm      2690:                if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
                   2691:                    != 0 ||
                   2692:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
                   2693:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
                   2694:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
                   2695:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
1.354     djm      2696:                        fatal_fr(r, "build pty-req");
1.194     djm      2697:                if (tiop == NULL)
                   2698:                        tiop = get_saved_tio();
1.316     markus   2699:                ssh_tty_make_modes(ssh, -1, tiop);
1.320     djm      2700:                if ((r = sshpkt_send(ssh)) != 0)
1.354     djm      2701:                        fatal_fr(r, "send pty-req");
1.123     djm      2702:                /* XXX wait for reply */
1.132     djm      2703:                c->client_tty = 1;
1.123     djm      2704:        }
                   2705:
                   2706:        /* Transfer any environment variables from client to server */
1.126     djm      2707:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      2708:                debug("Sending environment.");
1.126     djm      2709:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      2710:                        /* Split */
1.126     djm      2711:                        name = xstrdup(env[i]);
1.123     djm      2712:                        if ((val = strchr(name, '=')) == NULL) {
1.250     djm      2713:                                free(name);
1.123     djm      2714:                                continue;
                   2715:                        }
                   2716:                        *val++ = '\0';
                   2717:
                   2718:                        matched = 0;
                   2719:                        for (j = 0; j < options.num_send_env; j++) {
                   2720:                                if (match_pattern(name, options.send_env[j])) {
                   2721:                                        matched = 1;
                   2722:                                        break;
                   2723:                                }
                   2724:                        }
                   2725:                        if (!matched) {
                   2726:                                debug3("Ignored env %s", name);
1.250     djm      2727:                                free(name);
1.123     djm      2728:                                continue;
                   2729:                        }
1.354     djm      2730:                        client_send_env(ssh, id, name, val);
1.250     djm      2731:                        free(name);
1.123     djm      2732:                }
1.313     djm      2733:        }
                   2734:        for (i = 0; i < options.num_setenv; i++) {
                   2735:                /* Split */
                   2736:                name = xstrdup(options.setenv[i]);
                   2737:                if ((val = strchr(name, '=')) == NULL) {
                   2738:                        free(name);
                   2739:                        continue;
                   2740:                }
                   2741:                *val++ = '\0';
1.354     djm      2742:                client_send_env(ssh, id, name, val);
1.313     djm      2743:                free(name);
1.123     djm      2744:        }
                   2745:
1.315     markus   2746:        len = sshbuf_len(cmd);
1.123     djm      2747:        if (len > 0) {
                   2748:                if (len > 900)
                   2749:                        len = 900;
                   2750:                if (want_subsystem) {
1.190     djm      2751:                        debug("Sending subsystem: %.*s",
1.380     djm      2752:                            (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2753:                        channel_request_start(ssh, id, "subsystem", 1);
                   2754:                        client_expect_confirm(ssh, id, "subsystem",
                   2755:                            CONFIRM_CLOSE);
1.123     djm      2756:                } else {
1.190     djm      2757:                        debug("Sending command: %.*s",
1.380     djm      2758:                            (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2759:                        channel_request_start(ssh, id, "exec", 1);
                   2760:                        client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
1.123     djm      2761:                }
1.320     djm      2762:                if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
                   2763:                    (r = sshpkt_send(ssh)) != 0)
1.354     djm      2764:                        fatal_fr(r, "send command");
1.123     djm      2765:        } else {
1.303     djm      2766:                channel_request_start(ssh, id, "shell", 1);
                   2767:                client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
1.354     djm      2768:                if ((r = sshpkt_send(ssh)) != 0)
                   2769:                        fatal_fr(r, "send shell");
1.123     djm      2770:        }
1.384     djm      2771:
                   2772:        session_setup_complete = 1;
                   2773:        client_repledge();
1.123     djm      2774: }
                   2775:
1.77      itojun   2776: static void
1.321     djm      2777: client_init_dispatch(struct ssh *ssh)
1.16      markus   2778: {
1.321     djm      2779:        ssh_dispatch_init(ssh, &dispatch_protocol_error);
1.100     markus   2780:
1.321     djm      2781:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   2782:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   2783:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   2784:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
                   2785:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
                   2786:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2787:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2788:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
                   2789:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
                   2790:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2791:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
                   2792:        ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2793:
                   2794:        /* rekeying */
1.321     djm      2795:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2796:
                   2797:        /* global request reply messages */
1.321     djm      2798:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2799:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.232     djm      2800: }
                   2801:
                   2802: void
                   2803: client_stop_mux(void)
                   2804: {
                   2805:        if (options.control_path != NULL && muxserver_sock != -1)
                   2806:                unlink(options.control_path);
                   2807:        /*
1.247     dtucker  2808:         * If we are in persist mode, or don't have a shell, signal that we
                   2809:         * should close when all active channels are closed.
1.232     djm      2810:         */
1.366     djm      2811:        if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
1.232     djm      2812:                session_closed = 1;
1.235     djm      2813:                setproctitle("[stopped mux]");
                   2814:        }
1.113     markus   2815: }
                   2816:
                   2817: /* client specific fatal cleanup */
                   2818: void
1.114     markus   2819: cleanup_exit(int i)
1.113     markus   2820: {
1.233     djm      2821:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.192     djm      2822:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2823:                unlink(options.control_path);
1.223     djm      2824:        ssh_kill_proxy_command();
1.114     markus   2825:        _exit(i);
1.1       deraadt  2826: }