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

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