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

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