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

1.345   ! dtucker     1: /* $OpenBSD: clientloop.c,v 1.344 2020/04/24 02:19:40 dtucker 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.153     stevesk    73: #include <signal.h>
1.174     stevesk    74: #include <stdio.h>
1.173     stevesk    75: #include <stdlib.h>
1.170     stevesk    76: #include <string.h>
1.328     deraadt    77: #include <stdarg.h>
1.150     stevesk    78: #include <termios.h>
1.175     deraadt    79: #include <pwd.h>
1.169     stevesk    80: #include <unistd.h>
1.266     deraadt    81: #include <limits.h>
1.1       deraadt    82:
1.175     deraadt    83: #include "xmalloc.h"
1.45      markus     84: #include "ssh.h"
                     85: #include "ssh2.h"
1.1       deraadt    86: #include "packet.h"
1.315     markus     87: #include "sshbuf.h"
1.15      markus     88: #include "compat.h"
1.74      markus     89: #include "channels.h"
1.15      markus     90: #include "dispatch.h"
1.317     markus     91: #include "sshkey.h"
1.175     deraadt    92: #include "cipher.h"
1.54      markus     93: #include "kex.h"
1.275     markus     94: #include "myproposal.h"
1.45      markus     95: #include "log.h"
1.261     millert    96: #include "misc.h"
1.45      markus     97: #include "readconf.h"
                     98: #include "clientloop.h"
1.147     djm        99: #include "sshconnect.h"
1.40      markus    100: #include "authfd.h"
1.45      markus    101: #include "atomicio.h"
1.118     deraadt   102: #include "sshpty.h"
1.123     djm       103: #include "match.h"
                    104: #include "msg.h"
1.262     djm       105: #include "ssherr.h"
1.267     djm       106: #include "hostfile.h"
1.319     djm       107:
1.39      markus    108: /* import options */
                    109: extern Options options;
                    110:
1.1       deraadt   111: /* Flag indicating that stdin should be redirected from /dev/null. */
                    112: extern int stdin_null_flag;
                    113:
1.116     dtucker   114: /* Flag indicating that no shell has been requested */
                    115: extern int no_shell_flag;
                    116:
1.286     djm       117: /* Flag indicating that ssh should daemonise after authentication is complete */
                    118: extern int fork_after_authentication_flag;
                    119:
1.123     djm       120: /* Control socket */
1.217     djm       121: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123     djm       122:
1.13      markus    123: /*
                    124:  * Name of the host we are connecting to.  This is the name given on the
1.324     jmc       125:  * command line, or the Hostname specified for the user-supplied name in a
1.13      markus    126:  * configuration file.
                    127:  */
1.1       deraadt   128: extern char *host;
                    129:
1.13      markus    130: /*
1.330     djm       131:  * If this field is not NULL, the ForwardAgent socket is this path and different
                    132:  * instead of SSH_AUTH_SOCK.
                    133:  */
                    134: extern char *forward_agent_sock_path;
                    135:
                    136: /*
1.13      markus    137:  * Flag to indicate that we have received a window change signal which has
                    138:  * not yet been processed.  This will cause a message indicating the new
                    139:  * window size to be sent to the server a little later.  This is volatile
                    140:  * because this is updated in a signal handler.
                    141:  */
1.88      markus    142: static volatile sig_atomic_t received_window_change_signal = 0;
                    143: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   144:
1.222     djm       145: /* Time when backgrounded control master using ControlPersist should exit */
                    146: static time_t control_persist_exit_time = 0;
                    147:
1.1       deraadt   148: /* Common data for the client loop code. */
1.217     djm       149: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.11      markus    150: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       151: static int exit_status;                /* Used to store the command exit status. */
1.315     markus    152: static struct sshbuf *stderr_buffer;   /* Used for final exit message. */
1.11      markus    153: static int connection_in;      /* Connection to server (input). */
                    154: static int connection_out;     /* Connection to server (output). */
1.56      markus    155: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221     djm       156: static int session_closed;     /* In SSH2: login session closed. */
1.274     djm       157: static u_int x11_refuse_time;  /* If >0, refuse x11 opens after this time. */
1.345   ! dtucker   158: static time_t server_alive_time;       /* Time to do server_alive_check */
1.1       deraadt   159:
1.321     djm       160: static void client_init_dispatch(struct ssh *ssh);
1.16      markus    161: int    session_ident = -1;
                    162:
1.195     djm       163: /* Track escape per proto2 channel */
                    164: struct escape_filter_ctx {
                    165:        int escape_pending;
                    166:        int escape_char;
                    167: };
                    168:
                    169: /* Context for channel confirmation replies */
1.190     djm       170: struct channel_reply_ctx {
                    171:        const char *request_type;
1.234     djm       172:        int id;
                    173:        enum confirm_action action;
1.190     djm       174: };
                    175:
1.196     djm       176: /* Global request success/failure callbacks */
1.303     djm       177: /* XXX move to struct ssh? */
1.196     djm       178: struct global_confirm {
                    179:        TAILQ_ENTRY(global_confirm) entry;
                    180:        global_confirm_cb *cb;
                    181:        void *ctx;
                    182:        int ref_count;
                    183: };
                    184: TAILQ_HEAD(global_confirms, global_confirm);
                    185: static struct global_confirms global_confirms =
                    186:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    187:
1.315     markus    188: void ssh_process_session2_setup(int, int, int, struct sshbuf *);
1.123     djm       189:
1.13      markus    190: /*
                    191:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    192:  * flag indicating that the window has changed.
                    193:  */
1.157     deraadt   194: /*ARGSUSED */
1.77      itojun    195: static void
1.11      markus    196: window_change_handler(int sig)
1.1       deraadt   197: {
1.11      markus    198:        received_window_change_signal = 1;
1.1       deraadt   199: }
                    200:
1.13      markus    201: /*
                    202:  * Signal handler for signals that cause the program to terminate.  These
                    203:  * signals must be trapped to restore terminal modes.
                    204:  */
1.157     deraadt   205: /*ARGSUSED */
1.77      itojun    206: static void
1.11      markus    207: signal_handler(int sig)
1.1       deraadt   208: {
1.75      markus    209:        received_signal = sig;
                    210:        quit_pending = 1;
1.1       deraadt   211: }
                    212:
1.13      markus    213: /*
1.222     djm       214:  * Sets control_persist_exit_time to the absolute time when the
                    215:  * backgrounded control master should exit due to expiry of the
                    216:  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
                    217:  * control master process, or if there is no ControlPersist timeout.
                    218:  */
                    219: static void
1.303     djm       220: set_control_persist_exit_time(struct ssh *ssh)
1.222     djm       221: {
                    222:        if (muxserver_sock == -1 || !options.control_persist
1.232     djm       223:            || options.control_persist_timeout == 0) {
1.222     djm       224:                /* not using a ControlPersist timeout */
                    225:                control_persist_exit_time = 0;
1.303     djm       226:        } else if (channel_still_open(ssh)) {
1.222     djm       227:                /* some client connections are still open */
                    228:                if (control_persist_exit_time > 0)
                    229:                        debug2("%s: cancel scheduled exit", __func__);
                    230:                control_persist_exit_time = 0;
                    231:        } else if (control_persist_exit_time <= 0) {
                    232:                /* a client connection has recently closed */
1.251     dtucker   233:                control_persist_exit_time = monotime() +
1.222     djm       234:                        (time_t)options.control_persist_timeout;
                    235:                debug2("%s: schedule exit in %d seconds", __func__,
                    236:                    options.control_persist_timeout);
                    237:        }
                    238:        /* else we are already counting down to the timeout */
                    239: }
                    240:
1.238     dtucker   241: #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
                    242: static int
                    243: client_x11_display_valid(const char *display)
                    244: {
                    245:        size_t i, dlen;
                    246:
1.279     djm       247:        if (display == NULL)
                    248:                return 0;
                    249:
1.238     dtucker   250:        dlen = strlen(display);
                    251:        for (i = 0; i < dlen; i++) {
1.256     deraadt   252:                if (!isalnum((u_char)display[i]) &&
1.238     dtucker   253:                    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
                    254:                        debug("Invalid character '%c' in DISPLAY", display[i]);
                    255:                        return 0;
                    256:                }
                    257:        }
                    258:        return 1;
                    259: }
                    260:
1.274     djm       261: #define SSH_X11_PROTO          "MIT-MAGIC-COOKIE-1"
                    262: #define X11_TIMEOUT_SLACK      60
1.279     djm       263: int
1.303     djm       264: client_x11_get_proto(struct ssh *ssh, const char *display,
                    265:     const char *xauth_path, u_int trusted, u_int timeout,
                    266:     char **_proto, char **_data)
1.138     djm       267: {
1.318     djm       268:        char *cmd, line[512], xdisplay[512];
1.279     djm       269:        char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
1.138     djm       270:        static char proto[512], data[512];
                    271:        FILE *f;
1.288     tedu      272:        int got_data = 0, generated = 0, do_unlink = 0, r;
1.138     djm       273:        struct stat st;
1.274     djm       274:        u_int now, x11_timeout_real;
1.138     djm       275:
                    276:        *_proto = proto;
                    277:        *_data = data;
1.279     djm       278:        proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
1.138     djm       279:
1.279     djm       280:        if (!client_x11_display_valid(display)) {
1.283     millert   281:                if (display != NULL)
                    282:                        logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
                    283:                            display);
1.279     djm       284:                return -1;
                    285:        }
                    286:        if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
1.138     djm       287:                debug("No xauth program.");
1.279     djm       288:                xauth_path = NULL;
                    289:        }
                    290:
                    291:        if (xauth_path != NULL) {
1.138     djm       292:                /*
                    293:                 * Handle FamilyLocal case where $DISPLAY does
                    294:                 * not match an authorization entry.  For this we
                    295:                 * just try "xauth list unix:displaynum.screennum".
                    296:                 * XXX: "localhost" match to determine FamilyLocal
                    297:                 *      is not perfect.
                    298:                 */
                    299:                if (strncmp(display, "localhost:", 10) == 0) {
1.279     djm       300:                        if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    301:                            display + 10)) < 0 ||
                    302:                            (size_t)r >= sizeof(xdisplay)) {
                    303:                                error("%s: display name too long", __func__);
                    304:                                return -1;
                    305:                        }
1.138     djm       306:                        display = xdisplay;
                    307:                }
                    308:                if (trusted == 0) {
1.274     djm       309:                        /*
1.279     djm       310:                         * Generate an untrusted X11 auth cookie.
                    311:                         *
1.274     djm       312:                         * The authentication cookie should briefly outlive
                    313:                         * ssh's willingness to forward X11 connections to
                    314:                         * avoid nasty fail-open behaviour in the X server.
                    315:                         */
1.279     djm       316:                        mktemp_proto(xauthdir, sizeof(xauthdir));
                    317:                        if (mkdtemp(xauthdir) == NULL) {
                    318:                                error("%s: mkdtemp: %s",
                    319:                                    __func__, strerror(errno));
                    320:                                return -1;
                    321:                        }
                    322:                        do_unlink = 1;
                    323:                        if ((r = snprintf(xauthfile, sizeof(xauthfile),
                    324:                            "%s/xauthfile", xauthdir)) < 0 ||
                    325:                            (size_t)r >= sizeof(xauthfile)) {
                    326:                                error("%s: xauthfile path too long", __func__);
                    327:                                rmdir(xauthdir);
                    328:                                return -1;
                    329:                        }
                    330:
1.318     djm       331:                        if (timeout == 0) {
                    332:                                /* auth doesn't time out */
                    333:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    334:                                    "untrusted 2>%s",
                    335:                                    xauth_path, xauthfile, display,
                    336:                                    SSH_X11_PROTO, _PATH_DEVNULL);
                    337:                        } else {
                    338:                                /* Add some slack to requested expiry */
                    339:                                if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
                    340:                                        x11_timeout_real = timeout +
                    341:                                            X11_TIMEOUT_SLACK;
                    342:                                else {
                    343:                                        /* Don't overflow on long timeouts */
                    344:                                        x11_timeout_real = UINT_MAX;
                    345:                                }
                    346:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    347:                                    "untrusted timeout %u 2>%s",
                    348:                                    xauth_path, xauthfile, display,
                    349:                                    SSH_X11_PROTO, x11_timeout_real,
                    350:                                    _PATH_DEVNULL);
                    351:                        }
1.322     djm       352:                        debug2("%s: xauth command: %s", __func__, cmd);
1.318     djm       353:
                    354:                        if (timeout != 0 && x11_refuse_time == 0) {
1.279     djm       355:                                now = monotime() + 1;
                    356:                                if (UINT_MAX - timeout < now)
                    357:                                        x11_refuse_time = UINT_MAX;
                    358:                                else
                    359:                                        x11_refuse_time = now + timeout;
1.303     djm       360:                                channel_set_x11_refuse_time(ssh,
                    361:                                    x11_refuse_time);
1.138     djm       362:                        }
1.279     djm       363:                        if (system(cmd) == 0)
                    364:                                generated = 1;
1.318     djm       365:                        free(cmd);
1.138     djm       366:                }
1.181     markus    367:
                    368:                /*
                    369:                 * When in untrusted mode, we read the cookie only if it was
                    370:                 * successfully generated as an untrusted one in the step
                    371:                 * above.
                    372:                 */
                    373:                if (trusted || generated) {
1.318     djm       374:                        xasprintf(&cmd,
1.181     markus    375:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    376:                            xauth_path,
                    377:                            generated ? "-f " : "" ,
                    378:                            generated ? xauthfile : "",
                    379:                            display);
                    380:                        debug2("x11_get_proto: %s", cmd);
                    381:                        f = popen(cmd, "r");
                    382:                        if (f && fgets(line, sizeof(line), f) &&
                    383:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    384:                                got_data = 1;
                    385:                        if (f)
                    386:                                pclose(f);
1.318     djm       387:                        free(cmd);
1.279     djm       388:                }
1.138     djm       389:        }
                    390:
                    391:        if (do_unlink) {
                    392:                unlink(xauthfile);
                    393:                rmdir(xauthdir);
                    394:        }
                    395:
1.279     djm       396:        /* Don't fall back to fake X11 data for untrusted forwarding */
                    397:        if (!trusted && !got_data) {
                    398:                error("Warning: untrusted X11 forwarding setup failed: "
                    399:                    "xauth key data not generated");
                    400:                return -1;
                    401:        }
                    402:
1.138     djm       403:        /*
                    404:         * If we didn't get authentication data, just make up some
                    405:         * data.  The forwarding code will check the validity of the
                    406:         * response anyway, and substitute this data.  The X11
                    407:         * server, however, will ignore this fake data and use
                    408:         * whatever authentication mechanisms it was using otherwise
                    409:         * for the local connection.
                    410:         */
                    411:        if (!got_data) {
1.288     tedu      412:                u_int8_t rnd[16];
                    413:                u_int i;
1.138     djm       414:
                    415:                logit("Warning: No xauth data; "
                    416:                    "using fake authentication data for X11 forwarding.");
                    417:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.288     tedu      418:                arc4random_buf(rnd, sizeof(rnd));
                    419:                for (i = 0; i < sizeof(rnd); i++) {
1.138     djm       420:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.288     tedu      421:                            rnd[i]);
1.138     djm       422:                }
                    423:        }
1.279     djm       424:
                    425:        return 0;
1.1       deraadt   426: }
                    427:
1.13      markus    428: /*
                    429:  * Checks if the client window has changed, and sends a packet about it to
                    430:  * the server if so.  The actual change is detected elsewhere (by a software
                    431:  * interrupt on Unix); this just checks the flag and sends a message if
                    432:  * appropriate.
                    433:  */
1.1       deraadt   434:
1.77      itojun    435: static void
1.303     djm       436: client_check_window_change(struct ssh *ssh)
1.1       deraadt   437: {
1.292     djm       438:        if (!received_window_change_signal)
1.16      markus    439:                return;
                    440:        received_window_change_signal = 0;
1.292     djm       441:        debug2("%s: changed", __func__);
1.303     djm       442:        channel_send_window_changes(ssh);
1.1       deraadt   443: }
                    444:
1.264     markus    445: static int
1.297     markus    446: client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
1.117     markus    447: {
1.196     djm       448:        struct global_confirm *gc;
                    449:
                    450:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
1.264     markus    451:                return 0;
1.196     djm       452:        if (gc->cb != NULL)
1.303     djm       453:                gc->cb(ssh, type, seq, gc->ctx);
1.196     djm       454:        if (--gc->ref_count <= 0) {
                    455:                TAILQ_REMOVE(&global_confirms, gc, entry);
1.342     jsg       456:                freezero(gc, sizeof(*gc));
1.196     djm       457:        }
                    458:
1.320     djm       459:        ssh_packet_set_alive_timeouts(ssh, 0);
1.264     markus    460:        return 0;
1.117     markus    461: }
                    462:
                    463: static void
1.345   ! dtucker   464: schedule_server_alive_check(void)
        !           465: {
        !           466:        if (options.server_alive_interval > 0)
        !           467:                server_alive_time = monotime() + options.server_alive_interval;
        !           468: }
        !           469:
        !           470: static void
1.320     djm       471: server_alive_check(struct ssh *ssh)
1.117     markus    472: {
1.320     djm       473:        int r;
                    474:
                    475:        if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
1.228     djm       476:                logit("Timeout, server %s not responding.", host);
1.176     markus    477:                cleanup_exit(255);
                    478:        }
1.320     djm       479:        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                    480:            (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
                    481:            (r = sshpkt_put_u8(ssh, 1)) != 0 ||         /* boolean: want reply */
                    482:            (r = sshpkt_send(ssh)) != 0)
1.322     djm       483:                fatal("%s: send packet: %s", __func__, ssh_err(r));
1.196     djm       484:        /* Insert an empty placeholder to maintain ordering */
                    485:        client_register_global_confirm(NULL, NULL);
1.345   ! dtucker   486:        schedule_server_alive_check();
1.117     markus    487: }
                    488:
1.13      markus    489: /*
                    490:  * Waits until the client can do something (some data becomes available on
                    491:  * one of the file descriptors).
                    492:  */
1.77      itojun    493: static void
1.303     djm       494: client_wait_until_can_do_something(struct ssh *ssh,
                    495:     fd_set **readsetp, fd_set **writesetp,
1.130     avsm      496:     int *maxfdp, u_int *nallocp, int rekeying)
1.11      markus    497: {
1.117     markus    498:        struct timeval tv, *tvp;
1.222     djm       499:        int timeout_secs;
1.345   ! dtucker   500:        time_t minwait_secs = 0, now = monotime();
1.315     markus    501:        int r, ret;
1.117     markus    502:
1.46      markus    503:        /* Add any selections by the channel mechanism. */
1.321     djm       504:        channel_prepare_select(ssh, readsetp, writesetp, maxfdp,
1.302     djm       505:            nallocp, &minwait_secs);
1.11      markus    506:
1.292     djm       507:        /* channel_prepare_select could have closed the last channel */
1.303     djm       508:        if (session_closed && !channel_still_open(ssh) &&
1.320     djm       509:            !ssh_packet_have_data_to_write(ssh)) {
1.292     djm       510:                /* clear mask since we did not call select() */
                    511:                memset(*readsetp, 0, *nallocp);
                    512:                memset(*writesetp, 0, *nallocp);
                    513:                return;
1.16      markus    514:        }
1.11      markus    515:
1.294     djm       516:        FD_SET(connection_in, *readsetp);
                    517:
1.11      markus    518:        /* Select server connection if have data to write to the server. */
1.320     djm       519:        if (ssh_packet_have_data_to_write(ssh))
1.46      markus    520:                FD_SET(connection_out, *writesetp);
1.11      markus    521:
1.13      markus    522:        /*
                    523:         * Wait for something to happen.  This will suspend the process until
                    524:         * some selected descriptor can be read, written, or has some other
1.222     djm       525:         * event pending, or a timeout expires.
1.13      markus    526:         */
1.11      markus    527:
1.222     djm       528:        timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
1.345   ! dtucker   529:        if (options.server_alive_interval > 0)
        !           530:                timeout_secs = MAXIMUM(server_alive_time - now, 0);
1.292     djm       531:        if (options.rekey_interval > 0 && !rekeying)
1.320     djm       532:                timeout_secs = MINIMUM(timeout_secs,
                    533:                    ssh_packet_get_rekey_timeout(ssh));
1.303     djm       534:        set_control_persist_exit_time(ssh);
1.222     djm       535:        if (control_persist_exit_time > 0) {
1.287     deraadt   536:                timeout_secs = MINIMUM(timeout_secs,
1.249     dtucker   537:                        control_persist_exit_time - now);
1.222     djm       538:                if (timeout_secs < 0)
                    539:                        timeout_secs = 0;
                    540:        }
1.239     djm       541:        if (minwait_secs != 0)
1.287     deraadt   542:                timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
1.222     djm       543:        if (timeout_secs == INT_MAX)
1.117     markus    544:                tvp = NULL;
1.129     deraadt   545:        else {
1.222     djm       546:                tv.tv_sec = timeout_secs;
1.117     markus    547:                tv.tv_usec = 0;
                    548:                tvp = &tv;
                    549:        }
1.222     djm       550:
1.117     markus    551:        ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
1.326     deraadt   552:        if (ret == -1) {
1.51      markus    553:                /*
                    554:                 * We have to clear the select masks, because we return.
                    555:                 * We have to return, because the mainloop checks for the flags
                    556:                 * set by the signal handlers.
                    557:                 */
1.87      markus    558:                memset(*readsetp, 0, *nallocp);
                    559:                memset(*writesetp, 0, *nallocp);
1.11      markus    560:                if (errno == EINTR)
                    561:                        return;
                    562:                /* Note: we might still have data in the buffers. */
1.315     markus    563:                if ((r = sshbuf_putf(stderr_buffer,
                    564:                    "select: %s\r\n", strerror(errno))) != 0)
                    565:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.11      markus    566:                quit_pending = 1;
1.345   ! dtucker   567:        } else if (options.server_alive_interval > 0 && !FD_ISSET(connection_in,
        !           568:             *readsetp) && monotime() >= server_alive_time)
1.249     dtucker   569:                /*
1.345   ! dtucker   570:                 * ServerAlive check is needed. We can't rely on the select
        !           571:                 * timing out since traffic on the client side such as port
        !           572:                 * forwards can keep waking it up.
1.249     dtucker   573:                 */
1.345   ! dtucker   574:                server_alive_check(ssh);
1.11      markus    575: }
                    576:
1.77      itojun    577: static void
1.315     markus    578: client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
1.1       deraadt   579: {
1.11      markus    580:        /* Flush stdout and stderr buffers. */
1.315     markus    581:        if (sshbuf_len(bout) > 0)
                    582:                atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
                    583:                    sshbuf_len(bout));
                    584:        if (sshbuf_len(berr) > 0)
                    585:                atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
                    586:                    sshbuf_len(berr));
1.11      markus    587:
1.233     djm       588:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    589:
1.305     djm       590:        sshbuf_reset(bin);
                    591:        sshbuf_reset(bout);
                    592:        sshbuf_reset(berr);
1.11      markus    593:
                    594:        /* Send the suspend signal to the program itself. */
                    595:        kill(getpid(), SIGTSTP);
                    596:
1.132     djm       597:        /* Reset window sizes in case they have changed */
                    598:        received_window_change_signal = 1;
1.11      markus    599:
1.233     djm       600:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    601: }
                    602:
1.77      itojun    603: static void
1.320     djm       604: client_process_net_input(struct ssh *ssh, fd_set *readset)
1.11      markus    605: {
1.17      markus    606:        char buf[8192];
1.315     markus    607:        int r, len;
1.11      markus    608:
1.13      markus    609:        /*
                    610:         * Read input from the server, and add any such data to the buffer of
                    611:         * the packet subsystem.
                    612:         */
1.11      markus    613:        if (FD_ISSET(connection_in, readset)) {
1.345   ! dtucker   614:                schedule_server_alive_check();
1.11      markus    615:                /* Read as much as possible. */
1.280     markus    616:                len = read(connection_in, buf, sizeof(buf));
                    617:                if (len == 0) {
1.197     djm       618:                        /*
                    619:                         * Received EOF.  The remote host has closed the
                    620:                         * connection.
                    621:                         */
1.315     markus    622:                        if ((r = sshbuf_putf(stderr_buffer,
1.197     djm       623:                            "Connection to %.300s closed by remote host.\r\n",
1.315     markus    624:                            host)) != 0)
                    625:                                fatal("%s: buffer error: %s",
                    626:                                    __func__, ssh_err(r));
1.1       deraadt   627:                        quit_pending = 1;
                    628:                        return;
1.11      markus    629:                }
1.13      markus    630:                /*
                    631:                 * There is a kernel bug on Solaris that causes select to
                    632:                 * sometimes wake up even though there is no data available.
                    633:                 */
1.326     deraadt   634:                if (len == -1 && (errno == EAGAIN || errno == EINTR))
1.11      markus    635:                        len = 0;
                    636:
1.326     deraadt   637:                if (len == -1) {
1.197     djm       638:                        /*
                    639:                         * An error has encountered.  Perhaps there is a
                    640:                         * network problem.
                    641:                         */
1.315     markus    642:                        if ((r = sshbuf_putf(stderr_buffer,
1.197     djm       643:                            "Read from remote host %.300s: %.100s\r\n",
1.315     markus    644:                            host, strerror(errno))) != 0)
                    645:                                fatal("%s: buffer error: %s",
                    646:                                    __func__, ssh_err(r));
1.11      markus    647:                        quit_pending = 1;
                    648:                        return;
                    649:                }
1.320     djm       650:                ssh_packet_process_incoming(ssh, buf, len);
1.11      markus    651:        }
1.17      markus    652: }
1.16      markus    653:
1.97      jakob     654: static void
1.303     djm       655: client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
1.123     djm       656: {
1.190     djm       657:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    658:        char errmsg[256];
1.315     markus    659:        int r, tochan;
1.190     djm       660:
1.234     djm       661:        /*
                    662:         * If a TTY was explicitly requested, then a failure to allocate
                    663:         * one is fatal.
                    664:         */
                    665:        if (cr->action == CONFIRM_TTY &&
                    666:            (options.request_tty == REQUEST_TTY_FORCE ||
                    667:            options.request_tty == REQUEST_TTY_YES))
                    668:                cr->action = CONFIRM_CLOSE;
                    669:
1.312     djm       670:        /* XXX suppress on mux _client_ quietmode */
1.190     djm       671:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       672:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       673:
                    674:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    675:                debug2("%s request accepted on channel %d",
                    676:                    cr->request_type, c->self);
                    677:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    678:                if (tochan) {
                    679:                        snprintf(errmsg, sizeof(errmsg),
                    680:                            "%s request failed\r\n", cr->request_type);
                    681:                } else {
                    682:                        snprintf(errmsg, sizeof(errmsg),
                    683:                            "%s request failed on channel %d",
                    684:                            cr->request_type, c->self);
                    685:                }
                    686:                /* If error occurred on primary session channel, then exit */
1.234     djm       687:                if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190     djm       688:                        fatal("%s", errmsg);
1.234     djm       689:                /*
                    690:                 * If error occurred on mux client, append to
                    691:                 * their stderr.
                    692:                 */
                    693:                if (tochan) {
1.315     markus    694:                        if ((r = sshbuf_put(c->extended, errmsg,
                    695:                            strlen(errmsg))) != 0)
                    696:                                fatal("%s: buffer error %s", __func__,
                    697:                                    ssh_err(r));
1.234     djm       698:                } else
1.190     djm       699:                        error("%s", errmsg);
1.234     djm       700:                if (cr->action == CONFIRM_TTY) {
                    701:                        /*
                    702:                         * If a TTY allocation error occurred, then arrange
                    703:                         * for the correct TTY to leave raw mode.
                    704:                         */
                    705:                        if (c->self == session_ident)
                    706:                                leave_raw_mode(0);
                    707:                        else
1.303     djm       708:                                mux_tty_alloc_failed(ssh, c);
1.234     djm       709:                } else if (cr->action == CONFIRM_CLOSE) {
1.303     djm       710:                        chan_read_failed(ssh, c);
                    711:                        chan_write_failed(ssh, c);
1.190     djm       712:                }
                    713:        }
1.250     djm       714:        free(cr);
1.190     djm       715: }
                    716:
                    717: static void
1.303     djm       718: client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
1.190     djm       719: {
1.250     djm       720:        free(ctx);
1.190     djm       721: }
1.129     deraadt   722:
1.236     djm       723: void
1.303     djm       724: client_expect_confirm(struct ssh *ssh, int id, const char *request,
1.234     djm       725:     enum confirm_action action)
1.190     djm       726: {
1.255     djm       727:        struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123     djm       728:
1.190     djm       729:        cr->request_type = request;
1.234     djm       730:        cr->action = action;
1.123     djm       731:
1.303     djm       732:        channel_register_status_confirm(ssh, id, client_status_confirm,
1.190     djm       733:            client_abandon_status_confirm, cr);
1.196     djm       734: }
                    735:
                    736: void
                    737: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    738: {
1.201     djm       739:        struct global_confirm *gc, *last_gc;
1.196     djm       740:
                    741:        /* Coalesce identical callbacks */
1.201     djm       742:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    743:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    744:                if (++last_gc->ref_count >= INT_MAX)
                    745:                        fatal("%s: last_gc->ref_count = %d",
                    746:                            __func__, last_gc->ref_count);
1.196     djm       747:                return;
                    748:        }
                    749:
1.255     djm       750:        gc = xcalloc(1, sizeof(*gc));
1.196     djm       751:        gc->cb = cb;
                    752:        gc->ctx = ctx;
                    753:        gc->ref_count = 1;
                    754:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       755: }
                    756:
                    757: static void
1.303     djm       758: process_cmdline(struct ssh *ssh)
1.97      jakob     759: {
                    760:        void (*handler)(int);
1.261     millert   761:        char *s, *cmd;
                    762:        int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
                    763:        struct Forward fwd;
1.97      jakob     764:
1.257     tedu      765:        memset(&fwd, 0, sizeof(fwd));
1.183     djm       766:
1.233     djm       767:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.332     dtucker   768:        handler = ssh_signal(SIGINT, SIG_IGN);
1.99      markus    769:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     770:        if (s == NULL)
                    771:                goto out;
1.256     deraadt   772:        while (isspace((u_char)*s))
1.97      jakob     773:                s++;
1.121     djm       774:        if (*s == '-')
                    775:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   776:        if (*s == '\0')
1.97      jakob     777:                goto out;
1.121     djm       778:
1.122     djm       779:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       780:                logit("Commands:");
1.164     djm       781:                logit("      -L[bind_address:]port:host:hostport    "
                    782:                    "Request local forward");
                    783:                logit("      -R[bind_address:]port:host:hostport    "
                    784:                    "Request remote forward");
1.204     stevesk   785:                logit("      -D[bind_address:]port                  "
                    786:                    "Request dynamic forward");
1.237     markus    787:                logit("      -KL[bind_address:]port                 "
                    788:                    "Cancel local forward");
1.165     stevesk   789:                logit("      -KR[bind_address:]port                 "
1.164     djm       790:                    "Cancel remote forward");
1.237     markus    791:                logit("      -KD[bind_address:]port                 "
                    792:                    "Cancel dynamic forward");
1.146     reyk      793:                if (!options.permit_local_command)
                    794:                        goto out;
1.164     djm       795:                logit("      !args                                  "
                    796:                    "Execute local command");
1.146     reyk      797:                goto out;
                    798:        }
                    799:
                    800:        if (*s == '!' && options.permit_local_command) {
                    801:                s++;
                    802:                ssh_local_cmd(s);
1.121     djm       803:                goto out;
                    804:        }
                    805:
                    806:        if (*s == 'K') {
                    807:                delete = 1;
                    808:                s++;
                    809:        }
1.204     stevesk   810:        if (*s == 'L')
                    811:                local = 1;
                    812:        else if (*s == 'R')
                    813:                remote = 1;
                    814:        else if (*s == 'D')
                    815:                dynamic = 1;
                    816:        else {
1.109     itojun    817:                logit("Invalid command.");
1.97      jakob     818:                goto out;
                    819:        }
1.204     stevesk   820:
1.256     deraadt   821:        while (isspace((u_char)*++s))
1.179     tedu      822:                ;
1.97      jakob     823:
1.217     djm       824:        /* XXX update list of forwards in options */
1.121     djm       825:        if (delete) {
1.261     millert   826:                /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
                    827:                if (!parse_forward(&fwd, s, 1, 0)) {
                    828:                        logit("Bad forwarding close specification.");
1.121     djm       829:                        goto out;
                    830:                }
1.237     markus    831:                if (remote)
1.303     djm       832:                        ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1.237     markus    833:                else if (dynamic)
1.303     djm       834:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert   835:                            0, &options.fwd_opts) > 0;
1.237     markus    836:                else
1.303     djm       837:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert   838:                            CHANNEL_CANCEL_PORT_STATIC,
                    839:                            &options.fwd_opts) > 0;
1.237     markus    840:                if (!ok) {
1.290     dtucker   841:                        logit("Unknown port forwarding.");
1.237     markus    842:                        goto out;
                    843:                }
                    844:                logit("Canceled forwarding.");
1.121     djm       845:        } else {
1.209     djm       846:                if (!parse_forward(&fwd, s, dynamic, remote)) {
1.121     djm       847:                        logit("Bad forwarding specification.");
                    848:                        goto out;
                    849:                }
1.204     stevesk   850:                if (local || dynamic) {
1.303     djm       851:                        if (!channel_setup_local_fwd_listener(ssh, &fwd,
1.261     millert   852:                            &options.fwd_opts)) {
1.121     djm       853:                                logit("Port forwarding failed.");
                    854:                                goto out;
                    855:                        }
1.135     djm       856:                } else {
1.303     djm       857:                        if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1.167     markus    858:                                logit("Port forwarding failed.");
                    859:                                goto out;
                    860:                        }
1.135     djm       861:                }
1.121     djm       862:                logit("Forwarding port.");
                    863:        }
                    864:
1.97      jakob     865: out:
1.332     dtucker   866:        ssh_signal(SIGINT, handler);
1.233     djm       867:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250     djm       868:        free(cmd);
                    869:        free(fwd.listen_host);
1.261     millert   870:        free(fwd.listen_path);
1.250     djm       871:        free(fwd.connect_host);
1.261     millert   872:        free(fwd.connect_path);
1.97      jakob     873: }
                    874:
1.244     dtucker   875: /* reasons to suppress output of an escape command in help output */
                    876: #define SUPPRESS_NEVER         0       /* never suppress, always show */
1.292     djm       877: #define SUPPRESS_MUXCLIENT     1       /* don't show in mux client sessions */
                    878: #define SUPPRESS_MUXMASTER     2       /* don't show in mux master sessions */
                    879: #define SUPPRESS_SYSLOG                4       /* don't show when logging to syslog */
1.244     dtucker   880: struct escape_help_text {
                    881:        const char *cmd;
                    882:        const char *text;
                    883:        unsigned int flags;
                    884: };
                    885: static struct escape_help_text esc_txt[] = {
                    886:     {".",  "terminate session", SUPPRESS_MUXMASTER},
                    887:     {".",  "terminate connection (and any multiplexed sessions)",
                    888:        SUPPRESS_MUXCLIENT},
1.292     djm       889:     {"B",  "send a BREAK to the remote system", SUPPRESS_NEVER},
1.244     dtucker   890:     {"C",  "open a command line", SUPPRESS_MUXCLIENT},
1.292     djm       891:     {"R",  "request rekey", SUPPRESS_NEVER},
1.246     dtucker   892:     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244     dtucker   893:     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
                    894:     {"#",  "list forwarded connections", SUPPRESS_NEVER},
                    895:     {"&",  "background ssh (when waiting for connections to terminate)",
                    896:        SUPPRESS_MUXCLIENT},
                    897:     {"?", "this message", SUPPRESS_NEVER},
                    898: };
                    899:
                    900: static void
1.315     markus    901: print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
                    902:     int using_stderr)
1.244     dtucker   903: {
                    904:        unsigned int i, suppress_flags;
1.315     markus    905:        int r;
1.244     dtucker   906:
1.315     markus    907:        if ((r = sshbuf_putf(b,
                    908:            "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
                    909:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.244     dtucker   910:
1.292     djm       911:        suppress_flags =
1.244     dtucker   912:            (mux_client ? SUPPRESS_MUXCLIENT : 0) |
                    913:            (mux_client ? 0 : SUPPRESS_MUXMASTER) |
                    914:            (using_stderr ? 0 : SUPPRESS_SYSLOG);
                    915:
                    916:        for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
                    917:                if (esc_txt[i].flags & suppress_flags)
                    918:                        continue;
1.315     markus    919:                if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
                    920:                    escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
                    921:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.244     dtucker   922:        }
                    923:
1.315     markus    924:        if ((r = sshbuf_putf(b,
1.246     dtucker   925:            " %c%c   - send the escape character by typing it twice\r\n"
1.244     dtucker   926:            "(Note that escapes are only recognized immediately after "
1.315     markus    927:            "newline.)\r\n", escape_char, escape_char)) != 0)
                    928:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.244     dtucker   929: }
                    930:
1.314     djm       931: /*
1.296     naddy     932:  * Process the characters one by one.
1.195     djm       933:  */
1.77      itojun    934: static int
1.303     djm       935: process_escapes(struct ssh *ssh, Channel *c,
1.315     markus    936:     struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1.195     djm       937:     char *buf, int len)
1.31      markus    938: {
                    939:        pid_t pid;
1.315     markus    940:        int r, bytes = 0;
1.42      markus    941:        u_int i;
                    942:        u_char ch;
1.31      markus    943:        char *s;
1.294     djm       944:        struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
                    945:            NULL : (struct escape_filter_ctx *)c->filter_ctx;
1.31      markus    946:
1.294     djm       947:        if (c->filter_ctx == NULL)
                    948:                return 0;
1.314     djm       949:
1.139     djm       950:        if (len <= 0)
                    951:                return (0);
                    952:
                    953:        for (i = 0; i < (u_int)len; i++) {
1.31      markus    954:                /* Get one character at a time. */
                    955:                ch = buf[i];
                    956:
1.294     djm       957:                if (efc->escape_pending) {
1.31      markus    958:                        /* We have previously seen an escape character. */
                    959:                        /* Clear the flag now. */
1.294     djm       960:                        efc->escape_pending = 0;
1.31      markus    961:
                    962:                        /* Process the escaped character. */
                    963:                        switch (ch) {
                    964:                        case '.':
                    965:                                /* Terminate the connection. */
1.315     markus    966:                                if ((r = sshbuf_putf(berr, "%c.\r\n",
                    967:                                    efc->escape_char)) != 0)
                    968:                                        fatal("%s: buffer error: %s",
                    969:                                            __func__, ssh_err(r));
1.217     djm       970:                                if (c && c->ctl_chan != -1) {
1.303     djm       971:                                        chan_read_failed(ssh, c);
                    972:                                        chan_write_failed(ssh, c);
                    973:                                        if (c->detach_user) {
                    974:                                                c->detach_user(ssh,
                    975:                                                    c->self, NULL);
                    976:                                        }
1.253     dtucker   977:                                        c->type = SSH_CHANNEL_ABANDONED;
1.315     markus    978:                                        sshbuf_reset(c->input);
1.303     djm       979:                                        chan_ibuf_empty(ssh, c);
1.195     djm       980:                                        return 0;
                    981:                                } else
                    982:                                        quit_pending = 1;
1.31      markus    983:                                return -1;
                    984:
                    985:                        case 'Z' - 64:
1.195     djm       986:                                /* XXX support this for mux clients */
1.217     djm       987:                                if (c && c->ctl_chan != -1) {
1.245     dtucker   988:                                        char b[16];
1.195     djm       989:  noescape:
1.245     dtucker   990:                                        if (ch == 'Z' - 64)
                    991:                                                snprintf(b, sizeof b, "^Z");
                    992:                                        else
                    993:                                                snprintf(b, sizeof b, "%c", ch);
1.315     markus    994:                                        if ((r = sshbuf_putf(berr,
1.245     dtucker   995:                                            "%c%s escape not available to "
1.195     djm       996:                                            "multiplexed sessions\r\n",
1.315     markus    997:                                            efc->escape_char, b)) != 0)
                    998:                                                fatal("%s: buffer error: %s",
                    999:                                                    __func__, ssh_err(r));
1.195     djm      1000:                                        continue;
                   1001:                                }
1.197     djm      1002:                                /* Suspend the program. Inform the user */
1.315     markus   1003:                                if ((r = sshbuf_putf(berr,
                   1004:                                    "%c^Z [suspend ssh]\r\n",
                   1005:                                    efc->escape_char)) != 0)
                   1006:                                        fatal("%s: buffer error: %s",
                   1007:                                            __func__, ssh_err(r));
1.31      markus   1008:
                   1009:                                /* Restore terminal modes and suspend. */
                   1010:                                client_suspend_self(bin, bout, berr);
                   1011:
                   1012:                                /* We have been continued. */
                   1013:                                continue;
                   1014:
1.111     markus   1015:                        case 'B':
1.315     markus   1016:                                if ((r = sshbuf_putf(berr,
                   1017:                                    "%cB\r\n", efc->escape_char)) != 0)
                   1018:                                        fatal("%s: buffer error: %s",
                   1019:                                            __func__, ssh_err(r));
1.303     djm      1020:                                channel_request_start(ssh, c->self, "break", 0);
1.315     markus   1021:                                if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
                   1022:                                    (r = sshpkt_send(ssh)) != 0)
1.322     djm      1023:                                        fatal("%s: send packet: %s", __func__,
1.315     markus   1024:                                            ssh_err(r));
1.111     markus   1025:                                continue;
                   1026:
1.54      markus   1027:                        case 'R':
1.292     djm      1028:                                if (datafellows & SSH_BUG_NOREKEY)
                   1029:                                        logit("Server does not "
                   1030:                                            "support re-keying");
                   1031:                                else
                   1032:                                        need_rekeying = 1;
1.54      markus   1033:                                continue;
                   1034:
1.242     dtucker  1035:                        case 'V':
                   1036:                                /* FALLTHROUGH */
                   1037:                        case 'v':
                   1038:                                if (c && c->ctl_chan != -1)
                   1039:                                        goto noescape;
                   1040:                                if (!log_is_on_stderr()) {
1.315     markus   1041:                                        if ((r = sshbuf_putf(berr,
1.242     dtucker  1042:                                            "%c%c [Logging to syslog]\r\n",
1.315     markus   1043:                                            efc->escape_char, ch)) != 0)
                   1044:                                                fatal("%s: buffer error: %s",
                   1045:                                                    __func__, ssh_err(r));
1.242     dtucker  1046:                                        continue;
                   1047:                                }
                   1048:                                if (ch == 'V' && options.log_level >
                   1049:                                    SYSLOG_LEVEL_QUIET)
                   1050:                                        log_change_level(--options.log_level);
                   1051:                                if (ch == 'v' && options.log_level <
                   1052:                                    SYSLOG_LEVEL_DEBUG3)
                   1053:                                        log_change_level(++options.log_level);
1.315     markus   1054:                                if ((r = sshbuf_putf(berr,
1.294     djm      1055:                                    "%c%c [LogLevel %s]\r\n",
                   1056:                                    efc->escape_char, ch,
1.315     markus   1057:                                    log_level_name(options.log_level))) != 0)
                   1058:                                        fatal("%s: buffer error: %s",
                   1059:                                            __func__, ssh_err(r));
1.242     dtucker  1060:                                continue;
                   1061:
1.31      markus   1062:                        case '&':
1.217     djm      1063:                                if (c && c->ctl_chan != -1)
1.195     djm      1064:                                        goto noescape;
1.31      markus   1065:                                /*
1.197     djm      1066:                                 * Detach the program (continue to serve
                   1067:                                 * connections, but put in background and no
                   1068:                                 * more new connections).
1.31      markus   1069:                                 */
                   1070:                                /* Restore tty modes. */
1.233     djm      1071:                                leave_raw_mode(
                   1072:                                    options.request_tty == REQUEST_TTY_FORCE);
1.31      markus   1073:
                   1074:                                /* Stop listening for new connections. */
1.303     djm      1075:                                channel_stop_listening(ssh);
1.31      markus   1076:
1.315     markus   1077:                                if ((r = sshbuf_putf(berr,
                   1078:                                    "%c& [backgrounded]\n", efc->escape_char))
                   1079:                                     != 0)
                   1080:                                        fatal("%s: buffer error: %s",
                   1081:                                            __func__, ssh_err(r));
1.31      markus   1082:
                   1083:                                /* Fork into background. */
                   1084:                                pid = fork();
1.326     deraadt  1085:                                if (pid == -1) {
1.31      markus   1086:                                        error("fork: %.100s", strerror(errno));
                   1087:                                        continue;
                   1088:                                }
                   1089:                                if (pid != 0) { /* This is the parent. */
                   1090:                                        /* The parent just exits. */
                   1091:                                        exit(0);
                   1092:                                }
                   1093:                                /* The child continues serving connections. */
1.292     djm      1094:                                /* fake EOF on stdin */
1.315     markus   1095:                                if ((r = sshbuf_put_u8(bin, 4)) != 0)
                   1096:                                        fatal("%s: buffer error: %s",
                   1097:                                            __func__, ssh_err(r));
1.292     djm      1098:                                return -1;
1.31      markus   1099:                        case '?':
1.294     djm      1100:                                print_escape_help(berr, efc->escape_char,
1.244     dtucker  1101:                                    (c && c->ctl_chan != -1),
                   1102:                                    log_is_on_stderr());
1.31      markus   1103:                                continue;
                   1104:
                   1105:                        case '#':
1.315     markus   1106:                                if ((r = sshbuf_putf(berr, "%c#\r\n",
                   1107:                                    efc->escape_char)) != 0)
                   1108:                                        fatal("%s: buffer error: %s",
                   1109:                                            __func__, ssh_err(r));
1.303     djm      1110:                                s = channel_open_message(ssh);
1.315     markus   1111:                                if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
                   1112:                                        fatal("%s: buffer error: %s",
                   1113:                                            __func__, ssh_err(r));
1.250     djm      1114:                                free(s);
1.97      jakob    1115:                                continue;
                   1116:
                   1117:                        case 'C':
1.217     djm      1118:                                if (c && c->ctl_chan != -1)
1.206     djm      1119:                                        goto noescape;
1.303     djm      1120:                                process_cmdline(ssh);
1.31      markus   1121:                                continue;
                   1122:
                   1123:                        default:
1.294     djm      1124:                                if (ch != efc->escape_char) {
1.315     markus   1125:                                        if ((r = sshbuf_put_u8(bin,
                   1126:                                            efc->escape_char)) != 0)
                   1127:                                                fatal("%s: buffer error: %s",
                   1128:                                                    __func__, ssh_err(r));
1.31      markus   1129:                                        bytes++;
                   1130:                                }
                   1131:                                /* Escaped characters fall through here */
                   1132:                                break;
                   1133:                        }
                   1134:                } else {
                   1135:                        /*
1.197     djm      1136:                         * The previous character was not an escape char.
                   1137:                         * Check if this is an escape.
1.31      markus   1138:                         */
1.294     djm      1139:                        if (last_was_cr && ch == efc->escape_char) {
1.197     djm      1140:                                /*
                   1141:                                 * It is. Set the flag and continue to
                   1142:                                 * next character.
                   1143:                                 */
1.294     djm      1144:                                efc->escape_pending = 1;
1.31      markus   1145:                                continue;
                   1146:                        }
                   1147:                }
                   1148:
                   1149:                /*
                   1150:                 * Normal character.  Record whether it was a newline,
                   1151:                 * and append it to the buffer.
                   1152:                 */
                   1153:                last_was_cr = (ch == '\r' || ch == '\n');
1.315     markus   1154:                if ((r = sshbuf_put_u8(bin, ch)) != 0)
                   1155:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.31      markus   1156:                bytes++;
                   1157:        }
                   1158:        return bytes;
                   1159: }
                   1160:
1.13      markus   1161: /*
1.15      markus   1162:  * Get packets from the connection input buffer, and process them as long as
                   1163:  * there are packets available.
                   1164:  *
                   1165:  * Any unknown packets received during the actual
                   1166:  * session cause the session to terminate.  This is
                   1167:  * intended to make debugging easier since no
                   1168:  * confirmations are sent.  Any compatible protocol
                   1169:  * extensions must be negotiated during the
                   1170:  * preparatory phase.
                   1171:  */
                   1172:
1.77      itojun   1173: static void
1.321     djm      1174: client_process_buffered_input_packets(struct ssh *ssh)
1.15      markus   1175: {
1.321     djm      1176:        ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1.15      markus   1177: }
                   1178:
1.31      markus   1179: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1180:
1.195     djm      1181: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1182: void *
                   1183: client_new_escape_filter_ctx(int escape_char)
                   1184: {
                   1185:        struct escape_filter_ctx *ret;
                   1186:
1.255     djm      1187:        ret = xcalloc(1, sizeof(*ret));
1.195     djm      1188:        ret->escape_pending = 0;
                   1189:        ret->escape_char = escape_char;
                   1190:        return (void *)ret;
                   1191: }
                   1192:
1.198     djm      1193: /* Free the escape filter context on channel free */
                   1194: void
1.303     djm      1195: client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1.198     djm      1196: {
1.250     djm      1197:        free(ctx);
1.198     djm      1198: }
                   1199:
1.195     djm      1200: int
1.303     djm      1201: client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1.30      markus   1202: {
1.190     djm      1203:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1204:                return 0;
                   1205:
1.303     djm      1206:        return process_escapes(ssh, c, c->input, c->output, c->extended,
1.195     djm      1207:            buf, len);
1.30      markus   1208: }
                   1209:
1.77      itojun   1210: static void
1.303     djm      1211: client_channel_closed(struct ssh *ssh, int id, void *arg)
1.60      markus   1212: {
1.303     djm      1213:        channel_cancel_cleanup(ssh, id);
1.60      markus   1214:        session_closed = 1;
1.233     djm      1215:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60      markus   1216: }
                   1217:
1.15      markus   1218: /*
1.13      markus   1219:  * Implements the interactive session with the server.  This is called after
                   1220:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1221:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1222:  * used as an escape character for terminating or suspending the session.
1.13      markus   1223:  */
1.20      markus   1224: int
1.303     djm      1225: client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
                   1226:     int ssh2_chan_id)
1.1       deraadt  1227: {
1.46      markus   1228:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus   1229:        double start_time, total_time;
1.284     djm      1230:        int r, max_fd = 0, max_fd2 = 0, len;
1.200     markus   1231:        u_int64_t ibytes, obytes;
1.130     avsm     1232:        u_int nalloc = 0;
1.11      markus   1233:        char buf[100];
                   1234:
                   1235:        debug("Entering interactive session.");
1.277     semarie  1236:
1.278     semarie  1237:        if (options.control_master &&
1.286     djm      1238:            !option_clear_or_none(options.control_path)) {
1.278     semarie  1239:                debug("pledge: id");
1.327     mestre   1240:                if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1.278     semarie  1241:                    NULL) == -1)
                   1242:                        fatal("%s pledge(): %s", __func__, strerror(errno));
                   1243:
                   1244:        } else if (options.forward_x11 || options.permit_local_command) {
1.277     semarie  1245:                debug("pledge: exec");
                   1246:                if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
                   1247:                    NULL) == -1)
                   1248:                        fatal("%s pledge(): %s", __func__, strerror(errno));
                   1249:
                   1250:        } else if (options.update_hostkeys) {
                   1251:                debug("pledge: filesystem full");
                   1252:                if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
                   1253:                    NULL) == -1)
                   1254:                        fatal("%s pledge(): %s", __func__, strerror(errno));
                   1255:
1.286     djm      1256:        } else if (!option_clear_or_none(options.proxy_command) ||
                   1257:            fork_after_authentication_flag) {
1.277     semarie  1258:                debug("pledge: proc");
                   1259:                if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
                   1260:                        fatal("%s pledge(): %s", __func__, strerror(errno));
                   1261:
                   1262:        } else {
                   1263:                debug("pledge: network");
1.300     mestre   1264:                if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1.277     semarie  1265:                        fatal("%s pledge(): %s", __func__, strerror(errno));
                   1266:        }
1.11      markus   1267:
1.307     dtucker  1268:        start_time = monotime_double();
1.11      markus   1269:
                   1270:        /* Initialize variables. */
                   1271:        last_was_cr = 1;
                   1272:        exit_status = -1;
1.320     djm      1273:        connection_in = ssh_packet_get_connection_in(ssh);
                   1274:        connection_out = ssh_packet_get_connection_out(ssh);
1.287     deraadt  1275:        max_fd = MAXIMUM(connection_in, connection_out);
1.46      markus   1276:
1.11      markus   1277:        quit_pending = 0;
                   1278:
1.315     markus   1279:        /* Initialize buffer. */
                   1280:        if ((stderr_buffer = sshbuf_new()) == NULL)
                   1281:                fatal("%s: sshbuf_new failed", __func__);
1.11      markus   1282:
1.321     djm      1283:        client_init_dispatch(ssh);
1.15      markus   1284:
1.105     markus   1285:        /*
                   1286:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1287:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1288:         */
1.332     dtucker  1289:        if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1290:                ssh_signal(SIGHUP, signal_handler);
                   1291:        if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1292:                ssh_signal(SIGINT, signal_handler);
                   1293:        if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1294:                ssh_signal(SIGQUIT, signal_handler);
                   1295:        if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1296:                ssh_signal(SIGTERM, signal_handler);
                   1297:        ssh_signal(SIGWINCH, window_change_handler);
1.11      markus   1298:
                   1299:        if (have_pty)
1.233     djm      1300:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus   1301:
1.292     djm      1302:        session_ident = ssh2_chan_id;
                   1303:        if (session_ident != -1) {
                   1304:                if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1.303     djm      1305:                        channel_register_filter(ssh, session_ident,
1.292     djm      1306:                            client_simple_escape_filter, NULL,
                   1307:                            client_filter_cleanup,
                   1308:                            client_new_escape_filter_ctx(
                   1309:                            escape_char_arg));
1.232     djm      1310:                }
1.303     djm      1311:                channel_register_cleanup(ssh, session_ident,
1.292     djm      1312:                    client_channel_closed, 0);
1.48      markus   1313:        }
1.345   ! dtucker  1314:
        !          1315:        schedule_server_alive_check();
1.30      markus   1316:
1.11      markus   1317:        /* Main loop of the client for the interactive session mode. */
                   1318:        while (!quit_pending) {
                   1319:
1.13      markus   1320:                /* Process buffered packets sent by the server. */
1.321     djm      1321:                client_process_buffered_input_packets(ssh);
1.11      markus   1322:
1.303     djm      1323:                if (session_closed && !channel_still_open(ssh))
1.60      markus   1324:                        break;
                   1325:
1.303     djm      1326:                if (ssh_packet_is_rekeying(ssh)) {
1.56      markus   1327:                        debug("rekeying in progress");
1.284     djm      1328:                } else if (need_rekeying) {
                   1329:                        /* manual rekey request */
                   1330:                        debug("need rekeying");
1.303     djm      1331:                        if ((r = kex_start_rekex(ssh)) != 0)
1.284     djm      1332:                                fatal("%s: kex_start_rekex: %s", __func__,
                   1333:                                    ssh_err(r));
                   1334:                        need_rekeying = 0;
1.56      markus   1335:                } else {
                   1336:                        /*
                   1337:                         * Make packets from buffered channel data, and
                   1338:                         * enqueue them for sending to the server.
                   1339:                         */
1.320     djm      1340:                        if (ssh_packet_not_very_much_data_to_write(ssh))
1.303     djm      1341:                                channel_output_poll(ssh);
1.11      markus   1342:
1.56      markus   1343:                        /*
                   1344:                         * Check if the window size has changed, and buffer a
                   1345:                         * message about it to the server if so.
                   1346:                         */
1.303     djm      1347:                        client_check_window_change(ssh);
1.11      markus   1348:
1.56      markus   1349:                        if (quit_pending)
                   1350:                                break;
                   1351:                }
1.13      markus   1352:                /*
                   1353:                 * Wait until we have something to do (something becomes
                   1354:                 * available on one of the descriptors).
                   1355:                 */
1.81      markus   1356:                max_fd2 = max_fd;
1.303     djm      1357:                client_wait_until_can_do_something(ssh, &readset, &writeset,
                   1358:                    &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1.11      markus   1359:
                   1360:                if (quit_pending)
                   1361:                        break;
                   1362:
1.56      markus   1363:                /* Do channel operations unless rekeying in progress. */
1.303     djm      1364:                if (!ssh_packet_is_rekeying(ssh))
                   1365:                        channel_after_select(ssh, readset, writeset);
1.11      markus   1366:
1.17      markus   1367:                /* Buffer input from the connection.  */
1.320     djm      1368:                client_process_net_input(ssh, readset);
1.17      markus   1369:
                   1370:                if (quit_pending)
                   1371:                        break;
1.11      markus   1372:
1.197     djm      1373:                /*
                   1374:                 * Send as much buffered packet data as possible to the
                   1375:                 * sender.
                   1376:                 */
1.338     djm      1377:                if (FD_ISSET(connection_out, writeset)) {
                   1378:                        if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   1379:                                sshpkt_fatal(ssh, r,
                   1380:                                    "%s: ssh_packet_write_poll", __func__);
                   1381:                        }
                   1382:                }
1.222     djm      1383:
                   1384:                /*
                   1385:                 * If we are a backgrounded control master, and the
                   1386:                 * timeout has expired without any active client
                   1387:                 * connections, then quit.
                   1388:                 */
                   1389:                if (control_persist_exit_time > 0) {
1.251     dtucker  1390:                        if (monotime() >= control_persist_exit_time) {
1.222     djm      1391:                                debug("ControlPersist timeout expired");
                   1392:                                break;
                   1393:                        }
                   1394:                }
1.11      markus   1395:        }
1.250     djm      1396:        free(readset);
                   1397:        free(writeset);
1.11      markus   1398:
                   1399:        /* Terminate the session. */
                   1400:
                   1401:        /* Stop watching for window change. */
1.332     dtucker  1402:        ssh_signal(SIGWINCH, SIG_DFL);
1.211     andreas  1403:
1.320     djm      1404:        if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   1405:            (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
                   1406:            (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
                   1407:            (r = sshpkt_put_cstring(ssh, "")) != 0 ||   /* language tag */
                   1408:            (r = sshpkt_send(ssh)) != 0 ||
                   1409:            (r = ssh_packet_write_wait(ssh)) != 0)
1.322     djm      1410:                fatal("%s: send disconnect: %s", __func__, ssh_err(r));
1.11      markus   1411:
1.303     djm      1412:        channel_free_all(ssh);
1.11      markus   1413:
1.75      markus   1414:        if (have_pty)
1.233     djm      1415:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.75      markus   1416:
                   1417:        /* restore blocking io */
                   1418:        if (!isatty(fileno(stdin)))
                   1419:                unset_nonblock(fileno(stdin));
                   1420:        if (!isatty(fileno(stdout)))
                   1421:                unset_nonblock(fileno(stdout));
                   1422:        if (!isatty(fileno(stderr)))
                   1423:                unset_nonblock(fileno(stderr));
1.116     dtucker  1424:
                   1425:        /*
                   1426:         * If there was no shell or command requested, there will be no remote
                   1427:         * exit status to be returned.  In that case, clear error code if the
                   1428:         * connection was deliberately terminated at this end.
                   1429:         */
                   1430:        if (no_shell_flag && received_signal == SIGTERM) {
                   1431:                received_signal = 0;
                   1432:                exit_status = 0;
                   1433:        }
1.75      markus   1434:
1.301     dtucker  1435:        if (received_signal) {
                   1436:                verbose("Killed by signal %d.", (int) received_signal);
                   1437:                cleanup_exit(0);
                   1438:        }
1.75      markus   1439:
1.13      markus   1440:        /*
                   1441:         * In interactive mode (with pseudo tty) display a message indicating
                   1442:         * that the connection has been closed.
                   1443:         */
1.11      markus   1444:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.315     markus   1445:                if ((r = sshbuf_putf(stderr_buffer,
                   1446:                    "Connection to %.64s closed.\r\n", host)) != 0)
                   1447:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.11      markus   1448:        }
1.70      markus   1449:
1.11      markus   1450:        /* Output any buffered data for stderr. */
1.315     markus   1451:        if (sshbuf_len(stderr_buffer) > 0) {
1.230     djm      1452:                len = atomicio(vwrite, fileno(stderr),
1.315     markus   1453:                    (u_char *)sshbuf_ptr(stderr_buffer),
                   1454:                    sshbuf_len(stderr_buffer));
                   1455:                if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1.11      markus   1456:                        error("Write failed flushing stderr buffer.");
1.315     markus   1457:                else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
                   1458:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.11      markus   1459:        }
                   1460:
                   1461:        /* Clear and free any buffers. */
1.281     jsg      1462:        explicit_bzero(buf, sizeof(buf));
1.315     markus   1463:        sshbuf_free(stderr_buffer);
1.11      markus   1464:
                   1465:        /* Report bytes transferred, and transfer rates. */
1.307     dtucker  1466:        total_time = monotime_double() - start_time;
1.320     djm      1467:        ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.200     markus   1468:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229     djm      1469:            (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11      markus   1470:        if (total_time > 0)
1.200     markus   1471:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1472:                    obytes / total_time, ibytes / total_time);
1.11      markus   1473:        /* Return the exit status of the program. */
                   1474:        debug("Exit status %d", exit_status);
                   1475:        return exit_status;
1.15      markus   1476: }
                   1477:
                   1478: /*********/
                   1479:
1.77      itojun   1480: static Channel *
1.303     djm      1481: client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
                   1482:     int rchan, u_int rwindow, u_int rmaxpack)
1.40      markus   1483: {
1.103     deraadt  1484:        Channel *c = NULL;
1.289     markus   1485:        struct sshbuf *b = NULL;
1.40      markus   1486:        char *listen_address, *originator_address;
1.320     djm      1487:        u_int listen_port, originator_port;
1.289     markus   1488:        int r;
1.40      markus   1489:
                   1490:        /* Get rest of the packet */
1.320     djm      1491:        if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
                   1492:            (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
                   1493:            (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
                   1494:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
                   1495:            (r = sshpkt_get_end(ssh)) != 0)
1.322     djm      1496:                fatal("%s: parse packet: %s", __func__, ssh_err(r));
1.40      markus   1497:
1.261     millert  1498:        debug("%s: listen %s port %d, originator %s port %d", __func__,
                   1499:            listen_address, listen_port, originator_address, originator_port);
1.191     djm      1500:
1.320     djm      1501:        if (listen_port > 0xffff)
                   1502:                error("%s: invalid listen port", __func__);
                   1503:        else if (originator_port > 0xffff)
                   1504:                error("%s: invalid originator port", __func__);
                   1505:        else {
                   1506:                c = channel_connect_by_listen_address(ssh,
                   1507:                    listen_address, listen_port, "forwarded-tcpip",
                   1508:                    originator_address);
                   1509:        }
1.40      markus   1510:
1.289     markus   1511:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1512:                if ((b = sshbuf_new()) == NULL) {
                   1513:                        error("%s: alloc reply", __func__);
                   1514:                        goto out;
                   1515:                }
                   1516:                /* reconstruct and send to muxclient */
                   1517:                if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
                   1518:                    (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1519:                    (r = sshbuf_put_cstring(b, request_type)) != 0 ||
                   1520:                    (r = sshbuf_put_u32(b, rchan)) != 0 ||
                   1521:                    (r = sshbuf_put_u32(b, rwindow)) != 0 ||
                   1522:                    (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
                   1523:                    (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
                   1524:                    (r = sshbuf_put_u32(b, listen_port)) != 0 ||
                   1525:                    (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
                   1526:                    (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1.303     djm      1527:                    (r = sshbuf_put_stringb(c->output, b)) != 0) {
1.289     markus   1528:                        error("%s: compose for muxclient %s", __func__,
                   1529:                            ssh_err(r));
                   1530:                        goto out;
                   1531:                }
                   1532:        }
                   1533:
                   1534:  out:
                   1535:        sshbuf_free(b);
1.250     djm      1536:        free(originator_address);
                   1537:        free(listen_address);
1.40      markus   1538:        return c;
                   1539: }
                   1540:
1.103     deraadt  1541: static Channel *
1.303     djm      1542: client_request_forwarded_streamlocal(struct ssh *ssh,
                   1543:     const char *request_type, int rchan)
1.261     millert  1544: {
                   1545:        Channel *c = NULL;
                   1546:        char *listen_path;
1.320     djm      1547:        int r;
1.261     millert  1548:
                   1549:        /* Get the remote path. */
1.320     djm      1550:        if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
                   1551:            (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 ||    /* reserved */
                   1552:            (r = sshpkt_get_end(ssh)) != 0)
1.322     djm      1553:                fatal("%s: parse packet: %s", __func__, ssh_err(r));
1.261     millert  1554:
1.322     djm      1555:        debug("%s: request: %s", __func__, listen_path);
1.261     millert  1556:
1.303     djm      1557:        c = channel_connect_by_listen_path(ssh, listen_path,
1.261     millert  1558:            "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
                   1559:        free(listen_path);
                   1560:        return c;
                   1561: }
                   1562:
                   1563: static Channel *
1.303     djm      1564: client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1565: {
                   1566:        Channel *c = NULL;
                   1567:        char *originator;
1.321     djm      1568:        u_int originator_port;
1.320     djm      1569:        int r, sock;
1.40      markus   1570:
                   1571:        if (!options.forward_x11) {
                   1572:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1573:                error("Warning: this is probably a break-in attempt by a "
                   1574:                    "malicious server.");
1.221     djm      1575:                return NULL;
                   1576:        }
1.274     djm      1577:        if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1.221     djm      1578:                verbose("Rejected X11 connection after ForwardX11Timeout "
                   1579:                    "expired");
1.40      markus   1580:                return NULL;
                   1581:        }
1.320     djm      1582:        if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1.321     djm      1583:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1.320     djm      1584:            (r = sshpkt_get_end(ssh)) != 0)
1.322     djm      1585:                fatal("%s: parse packet: %s", __func__, ssh_err(r));
1.40      markus   1586:        /* XXX check permission */
1.321     djm      1587:        /* XXX range check originator port? */
                   1588:        debug("client_request_x11: request from %s %u", originator,
1.47      markus   1589:            originator_port);
1.250     djm      1590:        free(originator);
1.303     djm      1591:        sock = x11_connect_display(ssh);
1.67      markus   1592:        if (sock < 0)
                   1593:                return NULL;
1.303     djm      1594:        c = channel_new(ssh, "x11",
1.67      markus   1595:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1596:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1597:        c->force_drain = 1;
1.40      markus   1598:        return c;
                   1599: }
                   1600:
1.103     deraadt  1601: static Channel *
1.303     djm      1602: client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1603: {
                   1604:        Channel *c = NULL;
1.262     djm      1605:        int r, sock;
1.40      markus   1606:
                   1607:        if (!options.forward_agent) {
                   1608:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1609:                error("Warning: this is probably a break-in attempt by a "
                   1610:                    "malicious server.");
1.40      markus   1611:                return NULL;
                   1612:        }
1.330     djm      1613:        if (forward_agent_sock_path == NULL) {
                   1614:                r = ssh_get_authentication_socket(&sock);
                   1615:        } else {
                   1616:                r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
                   1617:        }
                   1618:        if (r != 0) {
1.262     djm      1619:                if (r != SSH_ERR_AGENT_NOT_PRESENT)
                   1620:                        debug("%s: ssh_get_authentication_socket: %s",
                   1621:                            __func__, ssh_err(r));
1.67      markus   1622:                return NULL;
1.262     djm      1623:        }
1.303     djm      1624:        c = channel_new(ssh, "authentication agent connection",
1.67      markus   1625:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1626:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1627:            "authentication agent connection", 1);
1.82      markus   1628:        c->force_drain = 1;
1.40      markus   1629:        return c;
1.180     djm      1630: }
                   1631:
1.306     djm      1632: char *
1.303     djm      1633: client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1.343     djm      1634:     int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1.180     djm      1635: {
                   1636:        Channel *c;
1.320     djm      1637:        int r, fd;
1.306     djm      1638:        char *ifname = NULL;
1.180     djm      1639:
                   1640:        if (tun_mode == SSH_TUNMODE_NO)
                   1641:                return 0;
                   1642:
                   1643:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1644:
                   1645:        /* Open local tunnel device */
1.306     djm      1646:        if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1.180     djm      1647:                error("Tunnel device open failed.");
1.306     djm      1648:                return NULL;
1.180     djm      1649:        }
1.306     djm      1650:        debug("Tunnel forwarding using interface %s", ifname);
1.180     djm      1651:
1.303     djm      1652:        c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1.180     djm      1653:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1654:        c->datagram = 1;
1.343     djm      1655:
                   1656:        if (cb != NULL)
                   1657:                channel_register_open_confirm(ssh, c->self, cb, cbctx);
1.180     djm      1658:
1.320     djm      1659:        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1660:            (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
                   1661:            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1662:            (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
                   1663:            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1664:            (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
                   1665:            (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
                   1666:            (r = sshpkt_send(ssh)) != 0)
1.321     djm      1667:                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.180     djm      1668:
1.306     djm      1669:        return ifname;
1.40      markus   1670: }
                   1671:
1.22      markus   1672: /* XXXX move to generic input handler */
1.264     markus   1673: static int
1.297     markus   1674: client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1.22      markus   1675: {
                   1676:        Channel *c = NULL;
1.320     djm      1677:        char *ctype = NULL;
                   1678:        int r;
                   1679:        u_int rchan;
                   1680:        size_t len;
                   1681:        u_int rmaxpack, rwindow;
                   1682:
                   1683:        if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
                   1684:            (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
                   1685:            (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
                   1686:            (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
                   1687:                goto out;
1.22      markus   1688:
1.24      markus   1689:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1690:            ctype, rchan, rwindow, rmaxpack);
                   1691:
1.40      markus   1692:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
1.303     djm      1693:                c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1.289     markus   1694:                    rmaxpack);
1.261     millert  1695:        } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1.303     djm      1696:                c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1.40      markus   1697:        } else if (strcmp(ctype, "x11") == 0) {
1.303     djm      1698:                c = client_request_x11(ssh, ctype, rchan);
1.40      markus   1699:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1.303     djm      1700:                c = client_request_agent(ssh, ctype, rchan);
1.22      markus   1701:        }
1.289     markus   1702:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1703:                debug3("proxied to downstream: %s", ctype);
                   1704:        } else if (c != NULL) {
1.22      markus   1705:                debug("confirm %s", ctype);
                   1706:                c->remote_id = rchan;
1.304     djm      1707:                c->have_remote_id = 1;
1.22      markus   1708:                c->remote_window = rwindow;
                   1709:                c->remote_maxpacket = rmaxpack;
1.69      markus   1710:                if (c->type != SSH_CHANNEL_CONNECTING) {
1.320     djm      1711:                        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
                   1712:                            (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1713:                            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1714:                            (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
                   1715:                            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1716:                            (r = sshpkt_send(ssh)) != 0)
                   1717:                                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.69      markus   1718:                }
1.22      markus   1719:        } else {
                   1720:                debug("failure %s", ctype);
1.320     djm      1721:                if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
                   1722:                    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
                   1723:                    (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
                   1724:                    (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
                   1725:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   1726:                    (r = sshpkt_send(ssh)) != 0)
                   1727:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.22      markus   1728:        }
1.320     djm      1729:        r = 0;
                   1730:  out:
1.250     djm      1731:        free(ctype);
1.320     djm      1732:        return r;
1.22      markus   1733: }
1.267     djm      1734:
1.264     markus   1735: static int
1.297     markus   1736: client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1.48      markus   1737: {
                   1738:        Channel *c = NULL;
1.320     djm      1739:        char *rtype = NULL;
                   1740:        u_char reply;
                   1741:        u_int id, exitval;
                   1742:        int r, success = 0;
                   1743:
                   1744:        if ((r = sshpkt_get_u32(ssh, &id)) != 0)
                   1745:                return r;
                   1746:        if (id <= INT_MAX)
                   1747:                c = channel_lookup(ssh, id);
1.297     markus   1748:        if (channel_proxy_upstream(c, type, seq, ssh))
1.289     markus   1749:                return 0;
1.320     djm      1750:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   1751:            (r = sshpkt_get_u8(ssh, &reply)) != 0)
                   1752:                goto out;
1.48      markus   1753:
1.320     djm      1754:        debug("client_input_channel_req: channel %u rtype %s reply %d",
1.48      markus   1755:            id, rtype, reply);
                   1756:
1.320     djm      1757:        if (c == NULL) {
1.197     djm      1758:                error("client_input_channel_req: channel %d: "
                   1759:                    "unknown channel", id);
1.193     markus   1760:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1.320     djm      1761:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1762:                        goto out;
1.303     djm      1763:                chan_rcvd_eow(ssh, c);
1.48      markus   1764:        } else if (strcmp(rtype, "exit-status") == 0) {
1.320     djm      1765:                if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
                   1766:                        goto out;
1.217     djm      1767:                if (c->ctl_chan != -1) {
1.303     djm      1768:                        mux_exit_message(ssh, c, exitval);
1.215     djm      1769:                        success = 1;
1.320     djm      1770:                } else if ((int)id == session_ident) {
1.215     djm      1771:                        /* Record exit value of local session */
1.123     djm      1772:                        success = 1;
                   1773:                        exit_status = exitval;
1.215     djm      1774:                } else {
1.218     djm      1775:                        /* Probably for a mux channel that has already closed */
                   1776:                        debug("%s: no sink for exit-status on channel %d",
                   1777:                            __func__, id);
1.123     djm      1778:                }
1.320     djm      1779:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1780:                        goto out;
1.48      markus   1781:        }
1.259     djm      1782:        if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.304     djm      1783:                if (!c->have_remote_id)
                   1784:                        fatal("%s: channel %d: no remote_id",
                   1785:                            __func__, c->self);
1.320     djm      1786:                if ((r = sshpkt_start(ssh, success ?
                   1787:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
                   1788:                    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1789:                    (r = sshpkt_send(ssh)) != 0)
                   1790:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.48      markus   1791:        }
1.320     djm      1792:        r = 0;
                   1793:  out:
1.250     djm      1794:        free(rtype);
1.320     djm      1795:        return r;
1.48      markus   1796: }
1.267     djm      1797:
1.269     djm      1798: struct hostkeys_update_ctx {
                   1799:        /* The hostname and (optionally) IP address string for the server */
                   1800:        char *host_str, *ip_str;
                   1801:
                   1802:        /*
                   1803:         * Keys received from the server and a flag for each indicating
                   1804:         * whether they already exist in known_hosts.
                   1805:         * keys_seen is filled in by hostkeys_find() and later (for new
                   1806:         * keys) by client_global_hostkeys_private_confirm().
                   1807:         */
                   1808:        struct sshkey **keys;
                   1809:        int *keys_seen;
1.314     djm      1810:        size_t nkeys, nnew;
1.269     djm      1811:
                   1812:        /*
                   1813:         * Keys that are in known_hosts, but were not present in the update
                   1814:         * from the server (i.e. scheduled to be deleted).
                   1815:         * Filled in by hostkeys_find().
                   1816:         */
                   1817:        struct sshkey **old_keys;
                   1818:        size_t nold;
                   1819: };
                   1820:
                   1821: static void
                   1822: hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
                   1823: {
                   1824:        size_t i;
                   1825:
                   1826:        if (ctx == NULL)
                   1827:                return;
                   1828:        for (i = 0; i < ctx->nkeys; i++)
                   1829:                sshkey_free(ctx->keys[i]);
                   1830:        free(ctx->keys);
                   1831:        free(ctx->keys_seen);
                   1832:        for (i = 0; i < ctx->nold; i++)
                   1833:                sshkey_free(ctx->old_keys[i]);
                   1834:        free(ctx->old_keys);
                   1835:        free(ctx->host_str);
                   1836:        free(ctx->ip_str);
                   1837:        free(ctx);
                   1838: }
                   1839:
                   1840: static int
                   1841: hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
                   1842: {
                   1843:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   1844:        size_t i;
                   1845:        struct sshkey **tmp;
                   1846:
1.293     djm      1847:        if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1.269     djm      1848:                return 0;
                   1849:
                   1850:        /* Mark off keys we've already seen for this host */
                   1851:        for (i = 0; i < ctx->nkeys; i++) {
                   1852:                if (sshkey_equal(l->key, ctx->keys[i])) {
                   1853:                        debug3("%s: found %s key at %s:%ld", __func__,
                   1854:                            sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
                   1855:                        ctx->keys_seen[i] = 1;
                   1856:                        return 0;
                   1857:                }
                   1858:        }
                   1859:        /* This line contained a key that not offered by the server */
                   1860:        debug3("%s: deprecated %s key at %s:%ld", __func__,
                   1861:            sshkey_ssh_name(l->key), l->path, l->linenum);
1.299     deraadt  1862:        if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1.269     djm      1863:            sizeof(*ctx->old_keys))) == NULL)
1.299     deraadt  1864:                fatal("%s: recallocarray failed nold = %zu",
1.269     djm      1865:                    __func__, ctx->nold);
                   1866:        ctx->old_keys = tmp;
                   1867:        ctx->old_keys[ctx->nold++] = l->key;
                   1868:        l->key = NULL;
                   1869:
                   1870:        return 0;
                   1871: }
                   1872:
                   1873: static void
1.337     djm      1874: hostkey_change_preamble(LogLevel loglevel)
1.269     djm      1875: {
1.336     djm      1876:        do_log2(loglevel, "The server has updated its host keys.");
                   1877:        do_log2(loglevel, "These changes were verified by the server's "
                   1878:            "existing trusted key.");
                   1879: }
                   1880:
                   1881: static void
                   1882: update_known_hosts(struct hostkeys_update_ctx *ctx)
                   1883: {
                   1884:        int r, was_raw = 0, first = 1;
                   1885:        int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
                   1886:        LogLevel loglevel = asking ?  SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1.269     djm      1887:        char *fp, *response;
                   1888:        size_t i;
1.333     djm      1889:        struct stat sb;
1.269     djm      1890:
                   1891:        for (i = 0; i < ctx->nkeys; i++) {
                   1892:                if (ctx->keys_seen[i] != 2)
                   1893:                        continue;
                   1894:                if ((fp = sshkey_fingerprint(ctx->keys[i],
                   1895:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
                   1896:                        fatal("%s: sshkey_fingerprint failed", __func__);
1.336     djm      1897:                if (first && asking)
1.337     djm      1898:                        hostkey_change_preamble(loglevel);
1.269     djm      1899:                do_log2(loglevel, "Learned new hostkey: %s %s",
                   1900:                    sshkey_type(ctx->keys[i]), fp);
1.336     djm      1901:                first = 0;
1.269     djm      1902:                free(fp);
                   1903:        }
                   1904:        for (i = 0; i < ctx->nold; i++) {
                   1905:                if ((fp = sshkey_fingerprint(ctx->old_keys[i],
                   1906:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
                   1907:                        fatal("%s: sshkey_fingerprint failed", __func__);
1.336     djm      1908:                if (first && asking)
1.337     djm      1909:                        hostkey_change_preamble(loglevel);
1.269     djm      1910:                do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
                   1911:                    sshkey_type(ctx->old_keys[i]), fp);
1.336     djm      1912:                first = 0;
1.269     djm      1913:                free(fp);
                   1914:        }
                   1915:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1.271     djm      1916:                if (get_saved_tio() != NULL) {
                   1917:                        leave_raw_mode(1);
                   1918:                        was_raw = 1;
                   1919:                }
1.269     djm      1920:                response = NULL;
                   1921:                for (i = 0; !quit_pending && i < 3; i++) {
                   1922:                        free(response);
                   1923:                        response = read_passphrase("Accept updated hostkeys? "
                   1924:                            "(yes/no): ", RP_ECHO);
                   1925:                        if (strcasecmp(response, "yes") == 0)
                   1926:                                break;
                   1927:                        else if (quit_pending || response == NULL ||
                   1928:                            strcasecmp(response, "no") == 0) {
                   1929:                                options.update_hostkeys = 0;
                   1930:                                break;
                   1931:                        } else {
                   1932:                                do_log2(loglevel, "Please enter "
                   1933:                                    "\"yes\" or \"no\"");
                   1934:                        }
                   1935:                }
                   1936:                if (quit_pending || i >= 3 || response == NULL)
                   1937:                        options.update_hostkeys = 0;
                   1938:                free(response);
1.271     djm      1939:                if (was_raw)
                   1940:                        enter_raw_mode(1);
1.269     djm      1941:        }
1.333     djm      1942:        if (options.update_hostkeys == 0)
                   1943:                return;
1.269     djm      1944:        /*
                   1945:         * Now that all the keys are verified, we can go ahead and replace
                   1946:         * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
                   1947:         * cancel the operation).
                   1948:         */
1.333     djm      1949:        for (i = 0; i < options.num_user_hostfiles; i++) {
                   1950:                /*
                   1951:                 * NB. keys are only added to hostfiles[0], for the rest we
                   1952:                 * just delete the hostname entries.
                   1953:                 */
                   1954:                if (stat(options.user_hostfiles[i], &sb) != 0) {
                   1955:                        if (errno == ENOENT) {
                   1956:                                debug("%s: known hosts file %s does not exist",
                   1957:                                    __func__, strerror(errno));
                   1958:                        } else {
                   1959:                                error("%s: known hosts file %s inaccessible",
                   1960:                                    __func__, strerror(errno));
                   1961:                        }
                   1962:                        continue;
                   1963:                }
                   1964:                if ((r = hostfile_replace_entries(options.user_hostfiles[i],
                   1965:                    ctx->host_str, ctx->ip_str,
                   1966:                    i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
                   1967:                    options.hash_known_hosts, 0,
                   1968:                    options.fingerprint_hash)) != 0) {
                   1969:                        error("%s: hostfile_replace_entries failed for %s: %s",
                   1970:                            __func__, options.user_hostfiles[i], ssh_err(r));
                   1971:                }
                   1972:        }
1.269     djm      1973: }
                   1974:
                   1975: static void
1.303     djm      1976: client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
                   1977:     u_int32_t seq, void *_ctx)
1.269     djm      1978: {
                   1979:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   1980:        size_t i, ndone;
                   1981:        struct sshbuf *signdata;
1.309     djm      1982:        int r, kexsigtype, use_kexsigtype;
1.269     djm      1983:        const u_char *sig;
                   1984:        size_t siglen;
                   1985:
                   1986:        if (ctx->nnew == 0)
                   1987:                fatal("%s: ctx->nnew == 0", __func__); /* sanity */
                   1988:        if (type != SSH2_MSG_REQUEST_SUCCESS) {
                   1989:                error("Server failed to confirm ownership of "
                   1990:                    "private host keys");
                   1991:                hostkeys_update_ctx_free(ctx);
                   1992:                return;
                   1993:        }
1.309     djm      1994:        kexsigtype = sshkey_type_plain(
                   1995:            sshkey_type_from_name(ssh->kex->hostkey_alg));
                   1996:
1.269     djm      1997:        if ((signdata = sshbuf_new()) == NULL)
                   1998:                fatal("%s: sshbuf_new failed", __func__);
                   1999:        /* Don't want to accidentally accept an unbound signature */
                   2000:        if (ssh->kex->session_id_len == 0)
                   2001:                fatal("%s: ssh->kex->session_id_len == 0", __func__);
                   2002:        /*
                   2003:         * Expect a signature for each of the ctx->nnew private keys we
                   2004:         * haven't seen before. They will be in the same order as the
                   2005:         * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
                   2006:         */
                   2007:        for (ndone = i = 0; i < ctx->nkeys; i++) {
                   2008:                if (ctx->keys_seen[i])
                   2009:                        continue;
                   2010:                /* Prepare data to be signed: session ID, unique string, key */
                   2011:                sshbuf_reset(signdata);
1.270     djm      2012:                if ( (r = sshbuf_put_cstring(signdata,
                   2013:                    "hostkeys-prove-00@openssh.com")) != 0 ||
                   2014:                    (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1.269     djm      2015:                    ssh->kex->session_id_len)) != 0 ||
                   2016:                    (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
                   2017:                        fatal("%s: failed to prepare signature: %s",
                   2018:                            __func__, ssh_err(r));
                   2019:                /* Extract and verify signature */
                   2020:                if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
                   2021:                        error("%s: couldn't parse message: %s",
                   2022:                            __func__, ssh_err(r));
                   2023:                        goto out;
                   2024:                }
1.309     djm      2025:                /*
                   2026:                 * For RSA keys, prefer to use the signature type negotiated
                   2027:                 * during KEX to the default (SHA1).
                   2028:                 */
                   2029:                use_kexsigtype = kexsigtype == KEY_RSA &&
                   2030:                    sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
1.269     djm      2031:                if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1.308     djm      2032:                    sshbuf_ptr(signdata), sshbuf_len(signdata),
1.329     djm      2033:                    use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0,
                   2034:                    NULL)) != 0) {
1.269     djm      2035:                        error("%s: server gave bad signature for %s key %zu",
                   2036:                            __func__, sshkey_type(ctx->keys[i]), i);
                   2037:                        goto out;
                   2038:                }
                   2039:                /* Key is good. Mark it as 'seen' */
                   2040:                ctx->keys_seen[i] = 2;
                   2041:                ndone++;
                   2042:        }
                   2043:        if (ndone != ctx->nnew)
                   2044:                fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
                   2045:                    ndone, ctx->nnew);  /* Shouldn't happen */
1.320     djm      2046:        if ((r = sshpkt_get_end(ssh)) != 0) {
                   2047:                error("%s: protocol error", __func__);
                   2048:                goto out;
                   2049:        }
1.269     djm      2050:
                   2051:        /* Make the edits to known_hosts */
                   2052:        update_known_hosts(ctx);
                   2053:  out:
                   2054:        hostkeys_update_ctx_free(ctx);
                   2055: }
                   2056:
1.267     djm      2057: /*
1.291     djm      2058:  * Returns non-zero if the key is accepted by HostkeyAlgorithms.
                   2059:  * Made slightly less trivial by the multiple RSA signature algorithm names.
                   2060:  */
                   2061: static int
                   2062: key_accepted_by_hostkeyalgs(const struct sshkey *key)
                   2063: {
                   2064:        const char *ktype = sshkey_ssh_name(key);
1.331     dtucker  2065:        const char *hostkeyalgs = options.hostkeyalgorithms;
1.291     djm      2066:
                   2067:        if (key == NULL || key->type == KEY_UNSPEC)
                   2068:                return 0;
                   2069:        if (key->type == KEY_RSA &&
                   2070:            (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
                   2071:            match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
                   2072:                return 1;
                   2073:        return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
                   2074: }
                   2075:
                   2076: /*
1.270     djm      2077:  * Handle hostkeys-00@openssh.com global request to inform the client of all
1.267     djm      2078:  * the server's hostkeys. The keys are checked against the user's
                   2079:  * HostkeyAlgorithms preference before they are accepted.
                   2080:  */
                   2081: static int
1.321     djm      2082: client_input_hostkeys(struct ssh *ssh)
1.267     djm      2083: {
                   2084:        const u_char *blob = NULL;
1.269     djm      2085:        size_t i, len = 0;
1.267     djm      2086:        struct sshbuf *buf = NULL;
1.269     djm      2087:        struct sshkey *key = NULL, **tmp;
                   2088:        int r;
                   2089:        char *fp;
1.267     djm      2090:        static int hostkeys_seen = 0; /* XXX use struct ssh */
1.268     djm      2091:        extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1.272     djm      2092:        struct hostkeys_update_ctx *ctx = NULL;
1.267     djm      2093:
                   2094:        if (hostkeys_seen)
                   2095:                fatal("%s: server already sent hostkeys", __func__);
1.269     djm      2096:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
                   2097:            options.batch_mode)
                   2098:                return 1; /* won't ask in batchmode, so don't even try */
1.267     djm      2099:        if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
                   2100:                return 1;
1.272     djm      2101:
                   2102:        ctx = xcalloc(1, sizeof(*ctx));
1.269     djm      2103:        while (ssh_packet_remaining(ssh) > 0) {
1.267     djm      2104:                sshkey_free(key);
                   2105:                key = NULL;
1.269     djm      2106:                if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
                   2107:                        error("%s: couldn't parse message: %s",
                   2108:                            __func__, ssh_err(r));
                   2109:                        goto out;
                   2110:                }
1.270     djm      2111:                if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
1.335     djm      2112:                        do_log2(r == SSH_ERR_KEY_TYPE_UNKNOWN ?
                   2113:                            SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
                   2114:                            "%s: parse key: %s", __func__, ssh_err(r));
                   2115:                        continue;
1.270     djm      2116:                }
1.267     djm      2117:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                   2118:                    SSH_FP_DEFAULT);
                   2119:                debug3("%s: received %s key %s", __func__,
                   2120:                    sshkey_type(key), fp);
                   2121:                free(fp);
1.275     markus   2122:
1.291     djm      2123:                if (!key_accepted_by_hostkeyalgs(key)) {
1.267     djm      2124:                        debug3("%s: %s key not permitted by HostkeyAlgorithms",
                   2125:                            __func__, sshkey_ssh_name(key));
                   2126:                        continue;
                   2127:                }
1.269     djm      2128:                /* Skip certs */
                   2129:                if (sshkey_is_cert(key)) {
                   2130:                        debug3("%s: %s key is a certificate; skipping",
                   2131:                            __func__, sshkey_ssh_name(key));
                   2132:                        continue;
                   2133:                }
                   2134:                /* Ensure keys are unique */
                   2135:                for (i = 0; i < ctx->nkeys; i++) {
                   2136:                        if (sshkey_equal(key, ctx->keys[i])) {
                   2137:                                error("%s: received duplicated %s host key",
                   2138:                                    __func__, sshkey_ssh_name(key));
                   2139:                                goto out;
                   2140:                        }
                   2141:                }
                   2142:                /* Key is good, record it */
1.299     deraadt  2143:                if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
1.269     djm      2144:                    sizeof(*ctx->keys))) == NULL)
1.299     deraadt  2145:                        fatal("%s: recallocarray failed nkeys = %zu",
1.269     djm      2146:                            __func__, ctx->nkeys);
                   2147:                ctx->keys = tmp;
                   2148:                ctx->keys[ctx->nkeys++] = key;
1.267     djm      2149:                key = NULL;
                   2150:        }
                   2151:
1.269     djm      2152:        if (ctx->nkeys == 0) {
1.270     djm      2153:                debug("%s: server sent no hostkeys", __func__);
1.267     djm      2154:                goto out;
                   2155:        }
1.270     djm      2156:
1.269     djm      2157:        if ((ctx->keys_seen = calloc(ctx->nkeys,
                   2158:            sizeof(*ctx->keys_seen))) == NULL)
                   2159:                fatal("%s: calloc failed", __func__);
1.267     djm      2160:
1.268     djm      2161:        get_hostfile_hostname_ipaddr(host,
                   2162:            options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
1.269     djm      2163:            options.port, &ctx->host_str,
                   2164:            options.check_host_ip ? &ctx->ip_str : NULL);
1.268     djm      2165:
1.269     djm      2166:        /* Find which keys we already know about. */
1.333     djm      2167:        for (i = 0; i < options.num_user_hostfiles; i++) {
                   2168:                debug("%s: searching %s for %s / %s", __func__,
1.339     dtucker  2169:                    options.user_hostfiles[i], ctx->host_str,
1.340     dtucker  2170:                    ctx->ip_str ? ctx->ip_str : "(none)");
1.333     djm      2171:                if ((r = hostkeys_foreach(options.user_hostfiles[i],
                   2172:                    hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
                   2173:                    HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
                   2174:                        if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.334     djm      2175:                                debug("%s: hostkeys file %s does not exist",
1.333     djm      2176:                                    __func__, options.user_hostfiles[i]);
                   2177:                                continue;
                   2178:                        }
                   2179:                        error("%s: hostkeys_foreach failed for %s: %s",
                   2180:                            __func__, options.user_hostfiles[i], ssh_err(r));
                   2181:                        goto out;
                   2182:                }
1.267     djm      2183:        }
                   2184:
1.269     djm      2185:        /* Figure out if we have any new keys to add */
                   2186:        ctx->nnew = 0;
                   2187:        for (i = 0; i < ctx->nkeys; i++) {
                   2188:                if (!ctx->keys_seen[i])
                   2189:                        ctx->nnew++;
                   2190:        }
                   2191:
                   2192:        debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
                   2193:            __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
                   2194:
                   2195:        if (ctx->nnew == 0 && ctx->nold != 0) {
                   2196:                /* We have some keys to remove. Just do it. */
                   2197:                update_known_hosts(ctx);
                   2198:        } else if (ctx->nnew != 0) {
                   2199:                /*
                   2200:                 * We have received hitherto-unseen keys from the server.
                   2201:                 * Ask the server to confirm ownership of the private halves.
                   2202:                 */
                   2203:                debug3("%s: asking server to prove ownership for %zu keys",
                   2204:                    __func__, ctx->nnew);
                   2205:                if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   2206:                    (r = sshpkt_put_cstring(ssh,
1.270     djm      2207:                    "hostkeys-prove-00@openssh.com")) != 0 ||
1.269     djm      2208:                    (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
                   2209:                        fatal("%s: cannot prepare packet: %s",
                   2210:                            __func__, ssh_err(r));
                   2211:                if ((buf = sshbuf_new()) == NULL)
                   2212:                        fatal("%s: sshbuf_new", __func__);
                   2213:                for (i = 0; i < ctx->nkeys; i++) {
                   2214:                        if (ctx->keys_seen[i])
                   2215:                                continue;
                   2216:                        sshbuf_reset(buf);
                   2217:                        if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
                   2218:                                fatal("%s: sshkey_putb: %s",
                   2219:                                    __func__, ssh_err(r));
                   2220:                        if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
                   2221:                                fatal("%s: sshpkt_put_string: %s",
                   2222:                                    __func__, ssh_err(r));
                   2223:                }
                   2224:                if ((r = sshpkt_send(ssh)) != 0)
                   2225:                        fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
                   2226:                client_register_global_confirm(
                   2227:                    client_global_hostkeys_private_confirm, ctx);
                   2228:                ctx = NULL;  /* will be freed in callback */
                   2229:        }
                   2230:
1.267     djm      2231:        /* Success */
                   2232:  out:
1.269     djm      2233:        hostkeys_update_ctx_free(ctx);
1.267     djm      2234:        sshkey_free(key);
                   2235:        sshbuf_free(buf);
1.269     djm      2236:        /*
                   2237:         * NB. Return success for all cases. The server doesn't need to know
                   2238:         * what the client does with its hosts file.
                   2239:         */
                   2240:        return 1;
1.267     djm      2241: }
                   2242:
1.264     markus   2243: static int
1.297     markus   2244: client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
1.95      markus   2245: {
                   2246:        char *rtype;
1.320     djm      2247:        u_char want_reply;
                   2248:        int r, success = 0;
1.95      markus   2249:
1.320     djm      2250:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   2251:            (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
                   2252:                goto out;
1.117     markus   2253:        debug("client_input_global_request: rtype %s want_reply %d",
                   2254:            rtype, want_reply);
1.270     djm      2255:        if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
1.321     djm      2256:                success = client_input_hostkeys(ssh);
1.95      markus   2257:        if (want_reply) {
1.320     djm      2258:                if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
                   2259:                    SSH2_MSG_REQUEST_FAILURE)) != 0 ||
                   2260:                    (r = sshpkt_send(ssh)) != 0 ||
                   2261:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   2262:                        goto out;
1.95      markus   2263:        }
1.320     djm      2264:        r = 0;
                   2265:  out:
1.250     djm      2266:        free(rtype);
1.320     djm      2267:        return r;
1.95      markus   2268: }
1.22      markus   2269:
1.123     djm      2270: void
1.303     djm      2271: client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
1.315     markus   2272:     const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
                   2273:     char **env)
1.123     djm      2274: {
1.320     djm      2275:        int i, j, matched, len, r;
1.313     djm      2276:        char *name, *val;
1.132     djm      2277:        Channel *c = NULL;
1.123     djm      2278:
                   2279:        debug2("%s: id %d", __func__, id);
                   2280:
1.303     djm      2281:        if ((c = channel_lookup(ssh, id)) == NULL)
                   2282:                fatal("%s: channel %d: unknown channel", __func__, id);
1.224     djm      2283:
1.320     djm      2284:        ssh_packet_set_interactive(ssh, want_tty,
1.224     djm      2285:            options.ip_qos_interactive, options.ip_qos_bulk);
1.132     djm      2286:
1.123     djm      2287:        if (want_tty) {
                   2288:                struct winsize ws;
                   2289:
                   2290:                /* Store window size in the packet. */
1.326     deraadt  2291:                if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
1.123     djm      2292:                        memset(&ws, 0, sizeof(ws));
                   2293:
1.303     djm      2294:                channel_request_start(ssh, id, "pty-req", 1);
                   2295:                client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
1.320     djm      2296:                if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
                   2297:                    != 0 ||
                   2298:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
                   2299:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
                   2300:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
                   2301:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
1.322     djm      2302:                        fatal("%s: build packet: %s", __func__, ssh_err(r));
1.194     djm      2303:                if (tiop == NULL)
                   2304:                        tiop = get_saved_tio();
1.316     markus   2305:                ssh_tty_make_modes(ssh, -1, tiop);
1.320     djm      2306:                if ((r = sshpkt_send(ssh)) != 0)
1.322     djm      2307:                        fatal("%s: send packet: %s", __func__, ssh_err(r));
1.123     djm      2308:                /* XXX wait for reply */
1.132     djm      2309:                c->client_tty = 1;
1.123     djm      2310:        }
                   2311:
                   2312:        /* Transfer any environment variables from client to server */
1.126     djm      2313:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      2314:                debug("Sending environment.");
1.126     djm      2315:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      2316:                        /* Split */
1.126     djm      2317:                        name = xstrdup(env[i]);
1.123     djm      2318:                        if ((val = strchr(name, '=')) == NULL) {
1.250     djm      2319:                                free(name);
1.123     djm      2320:                                continue;
                   2321:                        }
                   2322:                        *val++ = '\0';
                   2323:
                   2324:                        matched = 0;
                   2325:                        for (j = 0; j < options.num_send_env; j++) {
                   2326:                                if (match_pattern(name, options.send_env[j])) {
                   2327:                                        matched = 1;
                   2328:                                        break;
                   2329:                                }
                   2330:                        }
                   2331:                        if (!matched) {
                   2332:                                debug3("Ignored env %s", name);
1.250     djm      2333:                                free(name);
1.123     djm      2334:                                continue;
                   2335:                        }
                   2336:
                   2337:                        debug("Sending env %s = %s", name, val);
1.303     djm      2338:                        channel_request_start(ssh, id, "env", 0);
1.320     djm      2339:                        if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
                   2340:                            (r = sshpkt_put_cstring(ssh, val)) != 0 ||
1.322     djm      2341:                            (r = sshpkt_send(ssh)) != 0) {
                   2342:                                fatal("%s: send packet: %s",
                   2343:                                    __func__, ssh_err(r));
                   2344:                        }
1.250     djm      2345:                        free(name);
1.123     djm      2346:                }
1.313     djm      2347:        }
                   2348:        for (i = 0; i < options.num_setenv; i++) {
                   2349:                /* Split */
                   2350:                name = xstrdup(options.setenv[i]);
                   2351:                if ((val = strchr(name, '=')) == NULL) {
                   2352:                        free(name);
                   2353:                        continue;
                   2354:                }
                   2355:                *val++ = '\0';
                   2356:
                   2357:                debug("Setting env %s = %s", name, val);
                   2358:                channel_request_start(ssh, id, "env", 0);
1.320     djm      2359:                if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
                   2360:                    (r = sshpkt_put_cstring(ssh, val)) != 0 ||
                   2361:                    (r = sshpkt_send(ssh)) != 0)
1.322     djm      2362:                        fatal("%s: send packet: %s", __func__, ssh_err(r));
1.313     djm      2363:                free(name);
1.123     djm      2364:        }
                   2365:
1.315     markus   2366:        len = sshbuf_len(cmd);
1.123     djm      2367:        if (len > 0) {
                   2368:                if (len > 900)
                   2369:                        len = 900;
                   2370:                if (want_subsystem) {
1.190     djm      2371:                        debug("Sending subsystem: %.*s",
1.315     markus   2372:                            len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2373:                        channel_request_start(ssh, id, "subsystem", 1);
                   2374:                        client_expect_confirm(ssh, id, "subsystem",
                   2375:                            CONFIRM_CLOSE);
1.123     djm      2376:                } else {
1.190     djm      2377:                        debug("Sending command: %.*s",
1.315     markus   2378:                            len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2379:                        channel_request_start(ssh, id, "exec", 1);
                   2380:                        client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
1.123     djm      2381:                }
1.320     djm      2382:                if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
                   2383:                    (r = sshpkt_send(ssh)) != 0)
1.322     djm      2384:                        fatal("%s: send command: %s", __func__, ssh_err(r));
1.123     djm      2385:        } else {
1.303     djm      2386:                channel_request_start(ssh, id, "shell", 1);
                   2387:                client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
1.322     djm      2388:                if ((r = sshpkt_send(ssh)) != 0) {
                   2389:                        fatal("%s: send shell request: %s",
                   2390:                            __func__, ssh_err(r));
                   2391:                }
1.123     djm      2392:        }
                   2393: }
                   2394:
1.77      itojun   2395: static void
1.321     djm      2396: client_init_dispatch(struct ssh *ssh)
1.16      markus   2397: {
1.321     djm      2398:        ssh_dispatch_init(ssh, &dispatch_protocol_error);
1.100     markus   2399:
1.321     djm      2400:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   2401:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   2402:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   2403:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
                   2404:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
                   2405:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2406:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2407:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
                   2408:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
                   2409:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2410:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
                   2411:        ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2412:
                   2413:        /* rekeying */
1.321     djm      2414:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2415:
                   2416:        /* global request reply messages */
1.321     djm      2417:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2418:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.232     djm      2419: }
                   2420:
                   2421: void
                   2422: client_stop_mux(void)
                   2423: {
                   2424:        if (options.control_path != NULL && muxserver_sock != -1)
                   2425:                unlink(options.control_path);
                   2426:        /*
1.247     dtucker  2427:         * If we are in persist mode, or don't have a shell, signal that we
                   2428:         * should close when all active channels are closed.
1.232     djm      2429:         */
1.247     dtucker  2430:        if (options.control_persist || no_shell_flag) {
1.232     djm      2431:                session_closed = 1;
1.235     djm      2432:                setproctitle("[stopped mux]");
                   2433:        }
1.113     markus   2434: }
                   2435:
                   2436: /* client specific fatal cleanup */
                   2437: void
1.114     markus   2438: cleanup_exit(int i)
1.113     markus   2439: {
1.233     djm      2440:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.192     djm      2441:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2442:                unlink(options.control_path);
1.223     djm      2443:        ssh_kill_proxy_command();
1.114     markus   2444:        _exit(i);
1.1       deraadt  2445: }