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

1.221   ! djm         1: /* $OpenBSD: clientloop.c,v 1.220 2010/04/10 02:08:44 djm Exp $ */
1.1       deraadt     2: /*
1.12      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.33      deraadt     6:  * The main loop for the interactive session (client side).
1.20      markus      7:  *
1.33      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
                     13:  *
                     14:  *
                     15:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     16:  *
                     17:  * Redistribution and use in source and binary forms, with or without
                     18:  * modification, are permitted provided that the following conditions
                     19:  * are met:
                     20:  * 1. Redistributions of source code must retain the above copyright
                     21:  *    notice, this list of conditions and the following disclaimer.
                     22:  * 2. Redistributions in binary form must reproduce the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer in the
                     24:  *    documentation and/or other materials provided with the distribution.
                     25:  *
                     26:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     27:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     28:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     29:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     30:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     31:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     32:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     33:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     34:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     35:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.20      markus     36:  *
                     37:  *
1.33      deraadt    38:  * SSH2 support added by Markus Friedl.
1.78      markus     39:  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
1.20      markus     40:  *
1.33      deraadt    41:  * Redistribution and use in source and binary forms, with or without
                     42:  * modification, are permitted provided that the following conditions
                     43:  * are met:
                     44:  * 1. Redistributions of source code must retain the above copyright
                     45:  *    notice, this list of conditions and the following disclaimer.
                     46:  * 2. Redistributions in binary form must reproduce the above copyright
                     47:  *    notice, this list of conditions and the following disclaimer in the
                     48:  *    documentation and/or other materials provided with the distribution.
                     49:  *
                     50:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     51:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     52:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     53:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     54:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     55:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     56:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     57:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     58:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     59:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.12      deraadt    60:  */
1.1       deraadt    61:
1.152     stevesk    62:
1.175     deraadt    63: #include <sys/types.h>
1.152     stevesk    64: #include <sys/ioctl.h>
1.154     stevesk    65: #include <sys/stat.h>
1.166     stevesk    66: #include <sys/socket.h>
1.171     stevesk    67: #include <sys/time.h>
1.172     stevesk    68: #include <sys/param.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.1       deraadt    81:
1.175     deraadt    82: #include "xmalloc.h"
1.45      markus     83: #include "ssh.h"
                     84: #include "ssh1.h"
                     85: #include "ssh2.h"
1.1       deraadt    86: #include "packet.h"
                     87: #include "buffer.h"
1.15      markus     88: #include "compat.h"
1.74      markus     89: #include "channels.h"
1.15      markus     90: #include "dispatch.h"
1.40      markus     91: #include "key.h"
1.175     deraadt    92: #include "cipher.h"
1.54      markus     93: #include "kex.h"
1.45      markus     94: #include "log.h"
                     95: #include "readconf.h"
                     96: #include "clientloop.h"
1.147     djm        97: #include "sshconnect.h"
1.40      markus     98: #include "authfd.h"
1.45      markus     99: #include "atomicio.h"
1.118     deraadt   100: #include "sshpty.h"
1.63      markus    101: #include "misc.h"
1.123     djm       102: #include "match.h"
                    103: #include "msg.h"
1.212     andreas   104: #include "roaming.h"
1.39      markus    105:
                    106: /* import options */
                    107: extern Options options;
                    108:
1.1       deraadt   109: /* Flag indicating that stdin should be redirected from /dev/null. */
                    110: extern int stdin_null_flag;
                    111:
1.116     dtucker   112: /* Flag indicating that no shell has been requested */
                    113: extern int no_shell_flag;
                    114:
1.123     djm       115: /* Control socket */
1.217     djm       116: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123     djm       117:
1.13      markus    118: /*
                    119:  * Name of the host we are connecting to.  This is the name given on the
                    120:  * command line, or the HostName specified for the user-supplied name in a
                    121:  * configuration file.
                    122:  */
1.1       deraadt   123: extern char *host;
                    124:
1.216     djm       125: /* Force TTY allocation */
                    126: extern int force_tty_flag;
                    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:
                    140: /* Common data for the client loop code. */
1.217     djm       141: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.195     djm       142: static int escape_char1;       /* Escape character. (proto1 only) */
                    143: static int escape_pending1;    /* Last character was an escape (proto1 only) */
1.11      markus    144: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       145: static int exit_status;                /* Used to store the command exit status. */
                    146: static int stdin_eof;          /* EOF has been encountered on stderr. */
1.11      markus    147: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                    148: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                    149: static Buffer stderr_buffer;   /* Buffer for stderr data. */
1.221   ! djm       150: static u_int buffer_high;      /* Soft max buffer size. */
1.11      markus    151: static int connection_in;      /* Connection to server (input). */
                    152: static int connection_out;     /* Connection to server (output). */
1.56      markus    153: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221   ! djm       154: static int session_closed;     /* In SSH2: login session closed. */
        !           155: static int x11_refuse_time;    /* If >0, refuse x11 opens after this time. */
1.1       deraadt   156:
1.77      itojun    157: static void client_init_dispatch(void);
1.16      markus    158: int    session_ident = -1;
                    159:
1.214     andreas   160: int    session_resumed = 0;
                    161:
1.195     djm       162: /* Track escape per proto2 channel */
                    163: struct escape_filter_ctx {
                    164:        int escape_pending;
                    165:        int escape_char;
                    166: };
                    167:
                    168: /* Context for channel confirmation replies */
1.190     djm       169: struct channel_reply_ctx {
                    170:        const char *request_type;
                    171:        int id, do_close;
                    172: };
                    173:
1.196     djm       174: /* Global request success/failure callbacks */
                    175: struct global_confirm {
                    176:        TAILQ_ENTRY(global_confirm) entry;
                    177:        global_confirm_cb *cb;
                    178:        void *ctx;
                    179:        int ref_count;
                    180: };
                    181: TAILQ_HEAD(global_confirms, global_confirm);
                    182: static struct global_confirms global_confirms =
                    183:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    184:
1.54      markus    185: /*XXX*/
                    186: extern Kex *xxx_kex;
                    187:
1.123     djm       188: void ssh_process_session2_setup(int, int, int, Buffer *);
                    189:
1.1       deraadt   190: /* Restores stdin to blocking mode. */
                    191:
1.77      itojun    192: static void
1.49      itojun    193: leave_non_blocking(void)
1.1       deraadt   194: {
1.11      markus    195:        if (in_non_blocking_mode) {
1.125     djm       196:                unset_nonblock(fileno(stdin));
1.11      markus    197:                in_non_blocking_mode = 0;
                    198:        }
1.1       deraadt   199: }
                    200:
1.11      markus    201: /* Puts stdin terminal in non-blocking mode. */
                    202:
1.77      itojun    203: static void
1.49      itojun    204: enter_non_blocking(void)
1.1       deraadt   205: {
1.11      markus    206:        in_non_blocking_mode = 1;
1.124     djm       207:        set_nonblock(fileno(stdin));
1.1       deraadt   208: }
                    209:
1.13      markus    210: /*
                    211:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    212:  * flag indicating that the window has changed.
                    213:  */
1.157     deraadt   214: /*ARGSUSED */
1.77      itojun    215: static void
1.11      markus    216: window_change_handler(int sig)
1.1       deraadt   217: {
1.11      markus    218:        received_window_change_signal = 1;
                    219:        signal(SIGWINCH, window_change_handler);
1.1       deraadt   220: }
                    221:
1.13      markus    222: /*
                    223:  * Signal handler for signals that cause the program to terminate.  These
                    224:  * signals must be trapped to restore terminal modes.
                    225:  */
1.157     deraadt   226: /*ARGSUSED */
1.77      itojun    227: static void
1.11      markus    228: signal_handler(int sig)
1.1       deraadt   229: {
1.75      markus    230:        received_signal = sig;
                    231:        quit_pending = 1;
1.1       deraadt   232: }
                    233:
1.13      markus    234: /*
                    235:  * Returns current time in seconds from Jan 1, 1970 with the maximum
                    236:  * available resolution.
                    237:  */
1.1       deraadt   238:
1.77      itojun    239: static double
1.49      itojun    240: get_current_time(void)
1.1       deraadt   241: {
1.11      markus    242:        struct timeval tv;
                    243:        gettimeofday(&tv, NULL);
                    244:        return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
1.138     djm       245: }
                    246:
                    247: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
                    248: void
                    249: client_x11_get_proto(const char *display, const char *xauth_path,
1.221   ! djm       250:     u_int trusted, u_int timeout, char **_proto, char **_data)
1.138     djm       251: {
                    252:        char cmd[1024];
                    253:        char line[512];
                    254:        char xdisplay[512];
                    255:        static char proto[512], data[512];
                    256:        FILE *f;
                    257:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    258:        char *xauthdir, *xauthfile;
                    259:        struct stat st;
1.221   ! djm       260:        u_int now;
1.138     djm       261:
                    262:        xauthdir = xauthfile = NULL;
                    263:        *_proto = proto;
                    264:        *_data = data;
                    265:        proto[0] = data[0] = '\0';
                    266:
                    267:        if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
                    268:                debug("No xauth program.");
                    269:        } else {
                    270:                if (display == NULL) {
                    271:                        debug("x11_get_proto: DISPLAY not set");
                    272:                        return;
                    273:                }
                    274:                /*
                    275:                 * Handle FamilyLocal case where $DISPLAY does
                    276:                 * not match an authorization entry.  For this we
                    277:                 * just try "xauth list unix:displaynum.screennum".
                    278:                 * XXX: "localhost" match to determine FamilyLocal
                    279:                 *      is not perfect.
                    280:                 */
                    281:                if (strncmp(display, "localhost:", 10) == 0) {
                    282:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    283:                            display + 10);
                    284:                        display = xdisplay;
                    285:                }
                    286:                if (trusted == 0) {
                    287:                        xauthdir = xmalloc(MAXPATHLEN);
                    288:                        xauthfile = xmalloc(MAXPATHLEN);
                    289:                        strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
                    290:                        if (mkdtemp(xauthdir) != NULL) {
                    291:                                do_unlink = 1;
                    292:                                snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
                    293:                                    xauthdir);
                    294:                                snprintf(cmd, sizeof(cmd),
                    295:                                    "%s -f %s generate %s " SSH_X11_PROTO
1.221   ! djm       296:                                    " untrusted timeout %u 2>" _PATH_DEVNULL,
        !           297:                                    xauth_path, xauthfile, display, timeout);
1.138     djm       298:                                debug2("x11_get_proto: %s", cmd);
                    299:                                if (system(cmd) == 0)
                    300:                                        generated = 1;
1.221   ! djm       301:                                if (x11_refuse_time == 0) {
        !           302:                                        now = time(NULL) + 1;
        !           303:                                        if (UINT_MAX - timeout < now)
        !           304:                                                x11_refuse_time = UINT_MAX;
        !           305:                                        else
        !           306:                                                x11_refuse_time = now + timeout;
        !           307:                                }
1.138     djm       308:                        }
                    309:                }
1.181     markus    310:
                    311:                /*
                    312:                 * When in untrusted mode, we read the cookie only if it was
                    313:                 * successfully generated as an untrusted one in the step
                    314:                 * above.
                    315:                 */
                    316:                if (trusted || generated) {
                    317:                        snprintf(cmd, sizeof(cmd),
                    318:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    319:                            xauth_path,
                    320:                            generated ? "-f " : "" ,
                    321:                            generated ? xauthfile : "",
                    322:                            display);
                    323:                        debug2("x11_get_proto: %s", cmd);
                    324:                        f = popen(cmd, "r");
                    325:                        if (f && fgets(line, sizeof(line), f) &&
                    326:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    327:                                got_data = 1;
                    328:                        if (f)
                    329:                                pclose(f);
                    330:                } else
                    331:                        error("Warning: untrusted X11 forwarding setup failed: "
                    332:                            "xauth key data not generated");
1.138     djm       333:        }
                    334:
                    335:        if (do_unlink) {
                    336:                unlink(xauthfile);
                    337:                rmdir(xauthdir);
                    338:        }
                    339:        if (xauthdir)
                    340:                xfree(xauthdir);
                    341:        if (xauthfile)
                    342:                xfree(xauthfile);
                    343:
                    344:        /*
                    345:         * If we didn't get authentication data, just make up some
                    346:         * data.  The forwarding code will check the validity of the
                    347:         * response anyway, and substitute this data.  The X11
                    348:         * server, however, will ignore this fake data and use
                    349:         * whatever authentication mechanisms it was using otherwise
                    350:         * for the local connection.
                    351:         */
                    352:        if (!got_data) {
                    353:                u_int32_t rnd = 0;
                    354:
                    355:                logit("Warning: No xauth data; "
                    356:                    "using fake authentication data for X11 forwarding.");
                    357:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
                    358:                for (i = 0; i < 16; i++) {
                    359:                        if (i % 4 == 0)
                    360:                                rnd = arc4random();
                    361:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
                    362:                            rnd & 0xff);
                    363:                        rnd >>= 8;
                    364:                }
                    365:        }
1.1       deraadt   366: }
                    367:
1.13      markus    368: /*
                    369:  * This is called when the interactive is entered.  This checks if there is
                    370:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    371:  * not appear to wake up when redirecting from /dev/null.
                    372:  */
1.1       deraadt   373:
1.77      itojun    374: static void
1.49      itojun    375: client_check_initial_eof_on_stdin(void)
1.1       deraadt   376: {
1.11      markus    377:        int len;
                    378:        char buf[1];
1.1       deraadt   379:
1.13      markus    380:        /*
                    381:         * If standard input is to be "redirected from /dev/null", we simply
                    382:         * mark that we have seen an EOF and send an EOF message to the
                    383:         * server. Otherwise, we try to read a single character; it appears
                    384:         * that for some files, such /dev/null, select() never wakes up for
                    385:         * read for this descriptor, which means that we never get EOF.  This
                    386:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    387:         */
1.11      markus    388:        if (stdin_null_flag) {
                    389:                /* Fake EOF on stdin. */
                    390:                debug("Sending eof.");
                    391:                stdin_eof = 1;
                    392:                packet_start(SSH_CMSG_EOF);
                    393:                packet_send();
                    394:        } else {
                    395:                enter_non_blocking();
                    396:
                    397:                /* Check for immediate EOF on stdin. */
                    398:                len = read(fileno(stdin), buf, 1);
                    399:                if (len == 0) {
1.197     djm       400:                        /*
                    401:                         * EOF.  Record that we have seen it and send
                    402:                         * EOF to server.
                    403:                         */
1.11      markus    404:                        debug("Sending eof.");
                    405:                        stdin_eof = 1;
                    406:                        packet_start(SSH_CMSG_EOF);
                    407:                        packet_send();
                    408:                } else if (len > 0) {
1.13      markus    409:                        /*
                    410:                         * Got data.  We must store the data in the buffer,
                    411:                         * and also process it as an escape character if
                    412:                         * appropriate.
                    413:                         */
1.195     djm       414:                        if ((u_char) buf[0] == escape_char1)
                    415:                                escape_pending1 = 1;
1.52      markus    416:                        else
1.11      markus    417:                                buffer_append(&stdin_buffer, buf, 1);
                    418:                }
                    419:                leave_non_blocking();
                    420:        }
1.1       deraadt   421: }
                    422:
                    423:
1.13      markus    424: /*
                    425:  * Make packets from buffered stdin data, and buffer them for sending to the
                    426:  * connection.
                    427:  */
1.1       deraadt   428:
1.77      itojun    429: static void
1.49      itojun    430: client_make_packets_from_stdin_data(void)
1.1       deraadt   431: {
1.42      markus    432:        u_int len;
1.1       deraadt   433:
1.11      markus    434:        /* Send buffered stdin data to the server. */
                    435:        while (buffer_len(&stdin_buffer) > 0 &&
1.90      deraadt   436:            packet_not_very_much_data_to_write()) {
1.11      markus    437:                len = buffer_len(&stdin_buffer);
                    438:                /* Keep the packets at reasonable size. */
                    439:                if (len > packet_get_maxsize())
                    440:                        len = packet_get_maxsize();
                    441:                packet_start(SSH_CMSG_STDIN_DATA);
                    442:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    443:                packet_send();
                    444:                buffer_consume(&stdin_buffer, len);
                    445:                /* If we have a pending EOF, send it now. */
                    446:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    447:                        packet_start(SSH_CMSG_EOF);
                    448:                        packet_send();
                    449:                }
1.1       deraadt   450:        }
                    451: }
                    452:
1.13      markus    453: /*
                    454:  * Checks if the client window has changed, and sends a packet about it to
                    455:  * the server if so.  The actual change is detected elsewhere (by a software
                    456:  * interrupt on Unix); this just checks the flag and sends a message if
                    457:  * appropriate.
                    458:  */
1.1       deraadt   459:
1.77      itojun    460: static void
1.49      itojun    461: client_check_window_change(void)
1.1       deraadt   462: {
1.16      markus    463:        struct winsize ws;
                    464:
                    465:        if (! received_window_change_signal)
                    466:                return;
                    467:        /** XXX race */
                    468:        received_window_change_signal = 0;
                    469:
1.37      markus    470:        debug2("client_check_window_change: changed");
1.16      markus    471:
                    472:        if (compat20) {
1.123     djm       473:                channel_send_window_changes();
1.16      markus    474:        } else {
1.123     djm       475:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    476:                        return;
1.16      markus    477:                packet_start(SSH_CMSG_WINDOW_SIZE);
1.158     deraadt   478:                packet_put_int((u_int)ws.ws_row);
                    479:                packet_put_int((u_int)ws.ws_col);
                    480:                packet_put_int((u_int)ws.ws_xpixel);
                    481:                packet_put_int((u_int)ws.ws_ypixel);
1.16      markus    482:                packet_send();
1.1       deraadt   483:        }
                    484: }
                    485:
1.117     markus    486: static void
                    487: client_global_request_reply(int type, u_int32_t seq, void *ctxt)
                    488: {
1.196     djm       489:        struct global_confirm *gc;
                    490:
                    491:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
                    492:                return;
                    493:        if (gc->cb != NULL)
                    494:                gc->cb(type, seq, gc->ctx);
                    495:        if (--gc->ref_count <= 0) {
                    496:                TAILQ_REMOVE(&global_confirms, gc, entry);
                    497:                bzero(gc, sizeof(*gc));
                    498:                xfree(gc);
                    499:        }
                    500:
1.210     andreas   501:        packet_set_alive_timeouts(0);
1.117     markus    502: }
                    503:
                    504: static void
                    505: server_alive_check(void)
                    506: {
1.210     andreas   507:        if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
1.176     markus    508:                logit("Timeout, server not responding.");
                    509:                cleanup_exit(255);
                    510:        }
1.117     markus    511:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                    512:        packet_put_cstring("keepalive@openssh.com");
                    513:        packet_put_char(1);     /* boolean: want reply */
                    514:        packet_send();
1.196     djm       515:        /* Insert an empty placeholder to maintain ordering */
                    516:        client_register_global_confirm(NULL, NULL);
1.117     markus    517: }
                    518:
1.13      markus    519: /*
                    520:  * Waits until the client can do something (some data becomes available on
                    521:  * one of the file descriptors).
                    522:  */
1.77      itojun    523: static void
1.46      markus    524: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.130     avsm      525:     int *maxfdp, u_int *nallocp, int rekeying)
1.11      markus    526: {
1.117     markus    527:        struct timeval tv, *tvp;
                    528:        int ret;
                    529:
1.46      markus    530:        /* Add any selections by the channel mechanism. */
1.81      markus    531:        channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
1.11      markus    532:
1.16      markus    533:        if (!compat20) {
1.17      markus    534:                /* Read from the connection, unless our buffers are full. */
1.16      markus    535:                if (buffer_len(&stdout_buffer) < buffer_high &&
                    536:                    buffer_len(&stderr_buffer) < buffer_high &&
                    537:                    channel_not_very_much_buffered_data())
1.46      markus    538:                        FD_SET(connection_in, *readsetp);
1.17      markus    539:                /*
                    540:                 * Read from stdin, unless we have seen EOF or have very much
                    541:                 * buffered data to send to the server.
                    542:                 */
                    543:                if (!stdin_eof && packet_not_very_much_data_to_write())
1.46      markus    544:                        FD_SET(fileno(stdin), *readsetp);
1.17      markus    545:
                    546:                /* Select stdout/stderr if have data in buffer. */
                    547:                if (buffer_len(&stdout_buffer) > 0)
1.46      markus    548:                        FD_SET(fileno(stdout), *writesetp);
1.17      markus    549:                if (buffer_len(&stderr_buffer) > 0)
1.46      markus    550:                        FD_SET(fileno(stderr), *writesetp);
1.16      markus    551:        } else {
1.71      markus    552:                /* channel_prepare_select could have closed the last channel */
1.84      markus    553:                if (session_closed && !channel_still_open() &&
                    554:                    !packet_have_data_to_write()) {
                    555:                        /* clear mask since we did not call select() */
1.87      markus    556:                        memset(*readsetp, 0, *nallocp);
                    557:                        memset(*writesetp, 0, *nallocp);
1.84      markus    558:                        return;
1.71      markus    559:                } else {
                    560:                        FD_SET(connection_in, *readsetp);
                    561:                }
1.16      markus    562:        }
1.11      markus    563:
                    564:        /* Select server connection if have data to write to the server. */
                    565:        if (packet_have_data_to_write())
1.46      markus    566:                FD_SET(connection_out, *writesetp);
1.11      markus    567:
1.13      markus    568:        /*
                    569:         * Wait for something to happen.  This will suspend the process until
                    570:         * some selected descriptor can be read, written, or has some other
1.117     markus    571:         * event pending.
1.13      markus    572:         */
1.11      markus    573:
1.117     markus    574:        if (options.server_alive_interval == 0 || !compat20)
                    575:                tvp = NULL;
1.129     deraadt   576:        else {
1.117     markus    577:                tv.tv_sec = options.server_alive_interval;
                    578:                tv.tv_usec = 0;
                    579:                tvp = &tv;
                    580:        }
                    581:        ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
                    582:        if (ret < 0) {
1.11      markus    583:                char buf[100];
1.51      markus    584:
                    585:                /*
                    586:                 * We have to clear the select masks, because we return.
                    587:                 * We have to return, because the mainloop checks for the flags
                    588:                 * set by the signal handlers.
                    589:                 */
1.87      markus    590:                memset(*readsetp, 0, *nallocp);
                    591:                memset(*writesetp, 0, *nallocp);
1.50      deraadt   592:
1.11      markus    593:                if (errno == EINTR)
                    594:                        return;
                    595:                /* Note: we might still have data in the buffers. */
                    596:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    597:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    598:                quit_pending = 1;
1.117     markus    599:        } else if (ret == 0)
                    600:                server_alive_check();
1.11      markus    601: }
                    602:
1.77      itojun    603: static void
1.31      markus    604: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1       deraadt   605: {
1.11      markus    606:        /* Flush stdout and stderr buffers. */
1.31      markus    607:        if (buffer_len(bout) > 0)
1.197     djm       608:                atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
                    609:                    buffer_len(bout));
1.31      markus    610:        if (buffer_len(berr) > 0)
1.197     djm       611:                atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
                    612:                    buffer_len(berr));
1.11      markus    613:
1.216     djm       614:        leave_raw_mode(force_tty_flag);
1.11      markus    615:
1.13      markus    616:        /*
                    617:         * Free (and clear) the buffer to reduce the amount of data that gets
                    618:         * written to swap.
                    619:         */
1.31      markus    620:        buffer_free(bin);
                    621:        buffer_free(bout);
                    622:        buffer_free(berr);
1.11      markus    623:
                    624:        /* Send the suspend signal to the program itself. */
                    625:        kill(getpid(), SIGTSTP);
                    626:
1.132     djm       627:        /* Reset window sizes in case they have changed */
                    628:        received_window_change_signal = 1;
1.11      markus    629:
                    630:        /* OK, we have been continued by the user. Reinitialize buffers. */
1.31      markus    631:        buffer_init(bin);
                    632:        buffer_init(bout);
                    633:        buffer_init(berr);
1.11      markus    634:
1.216     djm       635:        enter_raw_mode(force_tty_flag);
1.11      markus    636: }
                    637:
1.77      itojun    638: static void
1.161     deraadt   639: client_process_net_input(fd_set *readset)
1.11      markus    640: {
1.212     andreas   641:        int len, cont = 0;
1.17      markus    642:        char buf[8192];
1.11      markus    643:
1.13      markus    644:        /*
                    645:         * Read input from the server, and add any such data to the buffer of
                    646:         * the packet subsystem.
                    647:         */
1.11      markus    648:        if (FD_ISSET(connection_in, readset)) {
                    649:                /* Read as much as possible. */
1.212     andreas   650:                len = roaming_read(connection_in, buf, sizeof(buf), &cont);
                    651:                if (len == 0 && cont == 0) {
1.197     djm       652:                        /*
                    653:                         * Received EOF.  The remote host has closed the
                    654:                         * connection.
                    655:                         */
                    656:                        snprintf(buf, sizeof buf,
                    657:                            "Connection to %.300s closed by remote host.\r\n",
                    658:                            host);
1.1       deraadt   659:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    660:                        quit_pending = 1;
                    661:                        return;
1.11      markus    662:                }
1.13      markus    663:                /*
                    664:                 * There is a kernel bug on Solaris that causes select to
                    665:                 * sometimes wake up even though there is no data available.
                    666:                 */
1.53      millert   667:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11      markus    668:                        len = 0;
                    669:
                    670:                if (len < 0) {
1.197     djm       671:                        /*
                    672:                         * An error has encountered.  Perhaps there is a
                    673:                         * network problem.
                    674:                         */
                    675:                        snprintf(buf, sizeof buf,
                    676:                            "Read from remote host %.300s: %.100s\r\n",
                    677:                            host, strerror(errno));
1.11      markus    678:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    679:                        quit_pending = 1;
                    680:                        return;
                    681:                }
                    682:                packet_process_incoming(buf, len);
                    683:        }
1.17      markus    684: }
1.16      markus    685:
1.97      jakob     686: static void
1.190     djm       687: client_status_confirm(int type, Channel *c, void *ctx)
1.123     djm       688: {
1.190     djm       689:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    690:        char errmsg[256];
                    691:        int tochan;
                    692:
                    693:        /* XXX supress on mux _client_ quietmode */
                    694:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       695:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       696:
                    697:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    698:                debug2("%s request accepted on channel %d",
                    699:                    cr->request_type, c->self);
                    700:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    701:                if (tochan) {
                    702:                        snprintf(errmsg, sizeof(errmsg),
                    703:                            "%s request failed\r\n", cr->request_type);
                    704:                } else {
                    705:                        snprintf(errmsg, sizeof(errmsg),
                    706:                            "%s request failed on channel %d",
                    707:                            cr->request_type, c->self);
                    708:                }
                    709:                /* If error occurred on primary session channel, then exit */
                    710:                if (cr->do_close && c->self == session_ident)
                    711:                        fatal("%s", errmsg);
                    712:                /* If error occurred on mux client, append to their stderr */
                    713:                if (tochan)
                    714:                        buffer_append(&c->extended, errmsg, strlen(errmsg));
                    715:                else
                    716:                        error("%s", errmsg);
                    717:                if (cr->do_close) {
                    718:                        chan_read_failed(c);
                    719:                        chan_write_failed(c);
                    720:                }
                    721:        }
                    722:        xfree(cr);
                    723: }
                    724:
                    725: static void
                    726: client_abandon_status_confirm(Channel *c, void *ctx)
                    727: {
                    728:        xfree(ctx);
                    729: }
1.129     deraadt   730:
1.190     djm       731: static void
                    732: client_expect_confirm(int id, const char *request, int do_close)
                    733: {
                    734:        struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
1.123     djm       735:
1.190     djm       736:        cr->request_type = request;
                    737:        cr->do_close = do_close;
1.123     djm       738:
1.190     djm       739:        channel_register_status_confirm(id, client_status_confirm,
                    740:            client_abandon_status_confirm, cr);
1.196     djm       741: }
                    742:
                    743: void
                    744: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    745: {
1.201     djm       746:        struct global_confirm *gc, *last_gc;
1.196     djm       747:
                    748:        /* Coalesce identical callbacks */
1.201     djm       749:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    750:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    751:                if (++last_gc->ref_count >= INT_MAX)
                    752:                        fatal("%s: last_gc->ref_count = %d",
                    753:                            __func__, last_gc->ref_count);
1.196     djm       754:                return;
                    755:        }
                    756:
                    757:        gc = xmalloc(sizeof(*gc));
                    758:        gc->cb = cb;
                    759:        gc->ctx = ctx;
                    760:        gc->ref_count = 1;
                    761:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       762: }
                    763:
                    764: static void
1.99      markus    765: process_cmdline(void)
1.97      jakob     766: {
                    767:        void (*handler)(int);
1.135     djm       768:        char *s, *cmd, *cancel_host;
1.121     djm       769:        int delete = 0;
1.204     stevesk   770:        int local = 0, remote = 0, dynamic = 0;
1.208     djm       771:        int cancel_port;
1.135     djm       772:        Forward fwd;
1.97      jakob     773:
1.183     djm       774:        bzero(&fwd, sizeof(fwd));
                    775:        fwd.listen_host = fwd.connect_host = NULL;
                    776:
1.216     djm       777:        leave_raw_mode(force_tty_flag);
1.101     markus    778:        handler = signal(SIGINT, SIG_IGN);
1.99      markus    779:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     780:        if (s == NULL)
                    781:                goto out;
1.179     tedu      782:        while (isspace(*s))
1.97      jakob     783:                s++;
1.121     djm       784:        if (*s == '-')
                    785:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   786:        if (*s == '\0')
1.97      jakob     787:                goto out;
1.121     djm       788:
1.122     djm       789:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       790:                logit("Commands:");
1.164     djm       791:                logit("      -L[bind_address:]port:host:hostport    "
                    792:                    "Request local forward");
                    793:                logit("      -R[bind_address:]port:host:hostport    "
                    794:                    "Request remote forward");
1.204     stevesk   795:                logit("      -D[bind_address:]port                  "
                    796:                    "Request dynamic forward");
1.165     stevesk   797:                logit("      -KR[bind_address:]port                 "
1.164     djm       798:                    "Cancel remote forward");
1.146     reyk      799:                if (!options.permit_local_command)
                    800:                        goto out;
1.164     djm       801:                logit("      !args                                  "
                    802:                    "Execute local command");
1.146     reyk      803:                goto out;
                    804:        }
                    805:
                    806:        if (*s == '!' && options.permit_local_command) {
                    807:                s++;
                    808:                ssh_local_cmd(s);
1.121     djm       809:                goto out;
                    810:        }
                    811:
                    812:        if (*s == 'K') {
                    813:                delete = 1;
                    814:                s++;
                    815:        }
1.204     stevesk   816:        if (*s == 'L')
                    817:                local = 1;
                    818:        else if (*s == 'R')
                    819:                remote = 1;
                    820:        else if (*s == 'D')
                    821:                dynamic = 1;
                    822:        else {
1.109     itojun    823:                logit("Invalid command.");
1.97      jakob     824:                goto out;
                    825:        }
1.204     stevesk   826:
                    827:        if ((local || dynamic) && delete) {
1.121     djm       828:                logit("Not supported.");
                    829:                goto out;
                    830:        }
1.204     stevesk   831:        if (remote && delete && !compat20) {
1.109     itojun    832:                logit("Not supported for SSH protocol version 1.");
1.97      jakob     833:                goto out;
                    834:        }
1.121     djm       835:
1.179     tedu      836:        while (isspace(*++s))
                    837:                ;
1.97      jakob     838:
1.217     djm       839:        /* XXX update list of forwards in options */
1.121     djm       840:        if (delete) {
1.135     djm       841:                cancel_port = 0;
                    842:                cancel_host = hpdelim(&s);      /* may be NULL */
                    843:                if (s != NULL) {
                    844:                        cancel_port = a2port(s);
                    845:                        cancel_host = cleanhostname(cancel_host);
                    846:                } else {
                    847:                        cancel_port = a2port(cancel_host);
                    848:                        cancel_host = NULL;
1.121     djm       849:                }
1.208     djm       850:                if (cancel_port <= 0) {
1.135     djm       851:                        logit("Bad forwarding close port");
1.121     djm       852:                        goto out;
                    853:                }
1.135     djm       854:                channel_request_rforward_cancel(cancel_host, cancel_port);
1.121     djm       855:        } else {
1.209     djm       856:                if (!parse_forward(&fwd, s, dynamic, remote)) {
1.121     djm       857:                        logit("Bad forwarding specification.");
                    858:                        goto out;
                    859:                }
1.204     stevesk   860:                if (local || dynamic) {
1.135     djm       861:                        if (channel_setup_local_fwd_listener(fwd.listen_host,
                    862:                            fwd.listen_port, fwd.connect_host,
                    863:                            fwd.connect_port, options.gateway_ports) < 0) {
1.121     djm       864:                                logit("Port forwarding failed.");
                    865:                                goto out;
                    866:                        }
1.135     djm       867:                } else {
1.167     markus    868:                        if (channel_request_remote_forwarding(fwd.listen_host,
1.135     djm       869:                            fwd.listen_port, fwd.connect_host,
1.167     markus    870:                            fwd.connect_port) < 0) {
                    871:                                logit("Port forwarding failed.");
                    872:                                goto out;
                    873:                        }
1.135     djm       874:                }
                    875:
1.121     djm       876:                logit("Forwarding port.");
                    877:        }
                    878:
1.97      jakob     879: out:
                    880:        signal(SIGINT, handler);
1.216     djm       881:        enter_raw_mode(force_tty_flag);
1.97      jakob     882:        if (cmd)
                    883:                xfree(cmd);
1.183     djm       884:        if (fwd.listen_host != NULL)
                    885:                xfree(fwd.listen_host);
                    886:        if (fwd.connect_host != NULL)
                    887:                xfree(fwd.connect_host);
1.97      jakob     888: }
                    889:
1.195     djm       890: /*
                    891:  * Process the characters one by one, call with c==NULL for proto1 case.
                    892:  */
1.77      itojun    893: static int
1.195     djm       894: process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
                    895:     char *buf, int len)
1.31      markus    896: {
1.32      markus    897:        char string[1024];
1.31      markus    898:        pid_t pid;
                    899:        int bytes = 0;
1.42      markus    900:        u_int i;
                    901:        u_char ch;
1.31      markus    902:        char *s;
1.195     djm       903:        int *escape_pendingp, escape_char;
                    904:        struct escape_filter_ctx *efc;
1.31      markus    905:
1.195     djm       906:        if (c == NULL) {
                    907:                escape_pendingp = &escape_pending1;
                    908:                escape_char = escape_char1;
                    909:        } else {
                    910:                if (c->filter_ctx == NULL)
                    911:                        return 0;
                    912:                efc = (struct escape_filter_ctx *)c->filter_ctx;
                    913:                escape_pendingp = &efc->escape_pending;
                    914:                escape_char = efc->escape_char;
                    915:        }
                    916:
1.139     djm       917:        if (len <= 0)
                    918:                return (0);
                    919:
                    920:        for (i = 0; i < (u_int)len; i++) {
1.31      markus    921:                /* Get one character at a time. */
                    922:                ch = buf[i];
                    923:
1.195     djm       924:                if (*escape_pendingp) {
1.31      markus    925:                        /* We have previously seen an escape character. */
                    926:                        /* Clear the flag now. */
1.195     djm       927:                        *escape_pendingp = 0;
1.31      markus    928:
                    929:                        /* Process the escaped character. */
                    930:                        switch (ch) {
                    931:                        case '.':
                    932:                                /* Terminate the connection. */
1.195     djm       933:                                snprintf(string, sizeof string, "%c.\r\n",
                    934:                                    escape_char);
1.32      markus    935:                                buffer_append(berr, string, strlen(string));
1.31      markus    936:
1.217     djm       937:                                if (c && c->ctl_chan != -1) {
1.195     djm       938:                                        chan_read_failed(c);
                    939:                                        chan_write_failed(c);
                    940:                                        return 0;
                    941:                                } else
                    942:                                        quit_pending = 1;
1.31      markus    943:                                return -1;
                    944:
                    945:                        case 'Z' - 64:
1.195     djm       946:                                /* XXX support this for mux clients */
1.217     djm       947:                                if (c && c->ctl_chan != -1) {
1.195     djm       948:  noescape:
                    949:                                        snprintf(string, sizeof string,
                    950:                                            "%c%c escape not available to "
                    951:                                            "multiplexed sessions\r\n",
                    952:                                            escape_char, ch);
                    953:                                        buffer_append(berr, string,
                    954:                                            strlen(string));
                    955:                                        continue;
                    956:                                }
1.197     djm       957:                                /* Suspend the program. Inform the user */
1.195     djm       958:                                snprintf(string, sizeof string,
                    959:                                    "%c^Z [suspend ssh]\r\n", escape_char);
1.32      markus    960:                                buffer_append(berr, string, strlen(string));
1.31      markus    961:
                    962:                                /* Restore terminal modes and suspend. */
                    963:                                client_suspend_self(bin, bout, berr);
                    964:
                    965:                                /* We have been continued. */
                    966:                                continue;
                    967:
1.111     markus    968:                        case 'B':
                    969:                                if (compat20) {
                    970:                                        snprintf(string, sizeof string,
                    971:                                            "%cB\r\n", escape_char);
                    972:                                        buffer_append(berr, string,
                    973:                                            strlen(string));
                    974:                                        channel_request_start(session_ident,
                    975:                                            "break", 0);
                    976:                                        packet_put_int(1000);
                    977:                                        packet_send();
                    978:                                }
                    979:                                continue;
                    980:
1.54      markus    981:                        case 'R':
1.59      markus    982:                                if (compat20) {
                    983:                                        if (datafellows & SSH_BUG_NOREKEY)
1.197     djm       984:                                                logit("Server does not "
                    985:                                                    "support re-keying");
1.59      markus    986:                                        else
                    987:                                                need_rekeying = 1;
                    988:                                }
1.54      markus    989:                                continue;
                    990:
1.31      markus    991:                        case '&':
1.217     djm       992:                                if (c && c->ctl_chan != -1)
1.195     djm       993:                                        goto noescape;
1.31      markus    994:                                /*
1.197     djm       995:                                 * Detach the program (continue to serve
                    996:                                 * connections, but put in background and no
                    997:                                 * more new connections).
1.31      markus    998:                                 */
                    999:                                /* Restore tty modes. */
1.216     djm      1000:                                leave_raw_mode(force_tty_flag);
1.31      markus   1001:
                   1002:                                /* Stop listening for new connections. */
1.86      markus   1003:                                channel_stop_listening();
1.31      markus   1004:
1.86      markus   1005:                                snprintf(string, sizeof string,
                   1006:                                    "%c& [backgrounded]\n", escape_char);
                   1007:                                buffer_append(berr, string, strlen(string));
1.31      markus   1008:
                   1009:                                /* Fork into background. */
                   1010:                                pid = fork();
                   1011:                                if (pid < 0) {
                   1012:                                        error("fork: %.100s", strerror(errno));
                   1013:                                        continue;
                   1014:                                }
                   1015:                                if (pid != 0) { /* This is the parent. */
                   1016:                                        /* The parent just exits. */
                   1017:                                        exit(0);
                   1018:                                }
                   1019:                                /* The child continues serving connections. */
1.86      markus   1020:                                if (compat20) {
                   1021:                                        buffer_append(bin, "\004", 1);
                   1022:                                        /* fake EOF on stdin */
                   1023:                                        return -1;
                   1024:                                } else if (!stdin_eof) {
                   1025:                                        /*
1.197     djm      1026:                                         * Sending SSH_CMSG_EOF alone does not
                   1027:                                         * always appear to be enough.  So we
                   1028:                                         * try to send an EOF character first.
1.86      markus   1029:                                         */
                   1030:                                        packet_start(SSH_CMSG_STDIN_DATA);
                   1031:                                        packet_put_string("\004", 1);
                   1032:                                        packet_send();
                   1033:                                        /* Close stdin. */
                   1034:                                        stdin_eof = 1;
                   1035:                                        if (buffer_len(bin) == 0) {
                   1036:                                                packet_start(SSH_CMSG_EOF);
                   1037:                                                packet_send();
                   1038:                                        }
                   1039:                                }
                   1040:                                continue;
1.31      markus   1041:
                   1042:                        case '?':
1.217     djm      1043:                                if (c && c->ctl_chan != -1) {
1.195     djm      1044:                                        snprintf(string, sizeof string,
                   1045: "%c?\r\n\
                   1046: Supported escape sequences:\r\n\
                   1047:   %c.  - terminate session\r\n\
                   1048:   %cB  - send a BREAK to the remote system\r\n\
                   1049:   %cR  - Request rekey (SSH protocol 2 only)\r\n\
                   1050:   %c#  - list forwarded connections\r\n\
                   1051:   %c?  - this message\r\n\
                   1052:   %c%c  - send the escape character by typing it twice\r\n\
                   1053: (Note that escapes are only recognized immediately after newline.)\r\n",
                   1054:                                            escape_char, escape_char,
                   1055:                                            escape_char, escape_char,
                   1056:                                            escape_char, escape_char,
1.206     djm      1057:                                            escape_char, escape_char);
1.195     djm      1058:                                } else {
                   1059:                                        snprintf(string, sizeof string,
1.31      markus   1060: "%c?\r\n\
                   1061: Supported escape sequences:\r\n\
1.195     djm      1062:   %c.  - terminate connection (and any multiplexed sessions)\r\n\
                   1063:   %cB  - send a BREAK to the remote system\r\n\
                   1064:   %cC  - open a command line\r\n\
                   1065:   %cR  - Request rekey (SSH protocol 2 only)\r\n\
                   1066:   %c^Z - suspend ssh\r\n\
                   1067:   %c#  - list forwarded connections\r\n\
                   1068:   %c&  - background ssh (when waiting for connections to terminate)\r\n\
                   1069:   %c?  - this message\r\n\
                   1070:   %c%c  - send the escape character by typing it twice\r\n\
1.31      markus   1071: (Note that escapes are only recognized immediately after newline.)\r\n",
1.195     djm      1072:                                            escape_char, escape_char,
                   1073:                                            escape_char, escape_char,
                   1074:                                            escape_char, escape_char,
                   1075:                                            escape_char, escape_char,
                   1076:                                            escape_char, escape_char,
                   1077:                                            escape_char);
                   1078:                                }
1.32      markus   1079:                                buffer_append(berr, string, strlen(string));
1.31      markus   1080:                                continue;
                   1081:
                   1082:                        case '#':
1.195     djm      1083:                                snprintf(string, sizeof string, "%c#\r\n",
                   1084:                                    escape_char);
1.32      markus   1085:                                buffer_append(berr, string, strlen(string));
1.31      markus   1086:                                s = channel_open_message();
                   1087:                                buffer_append(berr, s, strlen(s));
                   1088:                                xfree(s);
1.97      jakob    1089:                                continue;
                   1090:
                   1091:                        case 'C':
1.217     djm      1092:                                if (c && c->ctl_chan != -1)
1.206     djm      1093:                                        goto noescape;
1.99      markus   1094:                                process_cmdline();
1.31      markus   1095:                                continue;
                   1096:
                   1097:                        default:
                   1098:                                if (ch != escape_char) {
                   1099:                                        buffer_put_char(bin, escape_char);
                   1100:                                        bytes++;
                   1101:                                }
                   1102:                                /* Escaped characters fall through here */
                   1103:                                break;
                   1104:                        }
                   1105:                } else {
                   1106:                        /*
1.197     djm      1107:                         * The previous character was not an escape char.
                   1108:                         * Check if this is an escape.
1.31      markus   1109:                         */
                   1110:                        if (last_was_cr && ch == escape_char) {
1.197     djm      1111:                                /*
                   1112:                                 * It is. Set the flag and continue to
                   1113:                                 * next character.
                   1114:                                 */
1.195     djm      1115:                                *escape_pendingp = 1;
1.31      markus   1116:                                continue;
                   1117:                        }
                   1118:                }
                   1119:
                   1120:                /*
                   1121:                 * Normal character.  Record whether it was a newline,
                   1122:                 * and append it to the buffer.
                   1123:                 */
                   1124:                last_was_cr = (ch == '\r' || ch == '\n');
                   1125:                buffer_put_char(bin, ch);
                   1126:                bytes++;
                   1127:        }
                   1128:        return bytes;
                   1129: }
                   1130:
1.77      itojun   1131: static void
1.161     deraadt  1132: client_process_input(fd_set *readset)
1.17      markus   1133: {
1.21      deraadt  1134:        int len;
1.31      markus   1135:        char buf[8192];
1.16      markus   1136:
1.11      markus   1137:        /* Read input from stdin. */
                   1138:        if (FD_ISSET(fileno(stdin), readset)) {
                   1139:                /* Read as much as possible. */
                   1140:                len = read(fileno(stdin), buf, sizeof(buf));
1.64      markus   1141:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
                   1142:                        return;         /* we'll try again later */
1.11      markus   1143:                if (len <= 0) {
1.13      markus   1144:                        /*
                   1145:                         * Received EOF or error.  They are treated
                   1146:                         * similarly, except that an error message is printed
                   1147:                         * if it was an error condition.
                   1148:                         */
1.11      markus   1149:                        if (len < 0) {
1.197     djm      1150:                                snprintf(buf, sizeof buf, "read: %.100s\r\n",
                   1151:                                    strerror(errno));
1.11      markus   1152:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1153:                        }
                   1154:                        /* Mark that we have seen EOF. */
                   1155:                        stdin_eof = 1;
1.13      markus   1156:                        /*
                   1157:                         * Send an EOF message to the server unless there is
                   1158:                         * data in the buffer.  If there is data in the
                   1159:                         * buffer, no message will be sent now.  Code
                   1160:                         * elsewhere will send the EOF when the buffer
                   1161:                         * becomes empty if stdin_eof is set.
                   1162:                         */
1.11      markus   1163:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt  1164:                                packet_start(SSH_CMSG_EOF);
                   1165:                                packet_send();
1.11      markus   1166:                        }
1.195     djm      1167:                } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1.13      markus   1168:                        /*
                   1169:                         * Normal successful read, and no escape character.
                   1170:                         * Just append the data to buffer.
                   1171:                         */
1.11      markus   1172:                        buffer_append(&stdin_buffer, buf, len);
                   1173:                } else {
1.13      markus   1174:                        /*
1.197     djm      1175:                         * Normal, successful read.  But we have an escape
                   1176:                         * character and have to process the characters one
                   1177:                         * by one.
1.13      markus   1178:                         */
1.195     djm      1179:                        if (process_escapes(NULL, &stdin_buffer,
                   1180:                            &stdout_buffer, &stderr_buffer, buf, len) == -1)
1.31      markus   1181:                                return;
1.11      markus   1182:                }
                   1183:        }
                   1184: }
                   1185:
1.77      itojun   1186: static void
1.161     deraadt  1187: client_process_output(fd_set *writeset)
1.11      markus   1188: {
                   1189:        int len;
                   1190:        char buf[100];
1.1       deraadt  1191:
1.11      markus   1192:        /* Write buffered output to stdout. */
                   1193:        if (FD_ISSET(fileno(stdout), writeset)) {
                   1194:                /* Write as much data as possible. */
                   1195:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1196:                    buffer_len(&stdout_buffer));
1.11      markus   1197:                if (len <= 0) {
1.64      markus   1198:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1199:                                len = 0;
                   1200:                        else {
1.13      markus   1201:                                /*
                   1202:                                 * An error or EOF was encountered.  Put an
                   1203:                                 * error message to stderr buffer.
                   1204:                                 */
1.197     djm      1205:                                snprintf(buf, sizeof buf,
                   1206:                                    "write stdout: %.50s\r\n", strerror(errno));
1.11      markus   1207:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1208:                                quit_pending = 1;
                   1209:                                return;
                   1210:                        }
                   1211:                }
                   1212:                /* Consume printed data from the buffer. */
                   1213:                buffer_consume(&stdout_buffer, len);
                   1214:        }
                   1215:        /* Write buffered output to stderr. */
                   1216:        if (FD_ISSET(fileno(stderr), writeset)) {
                   1217:                /* Write as much data as possible. */
                   1218:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1219:                    buffer_len(&stderr_buffer));
1.11      markus   1220:                if (len <= 0) {
1.64      markus   1221:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1222:                                len = 0;
                   1223:                        else {
1.197     djm      1224:                                /*
                   1225:                                 * EOF or error, but can't even print
                   1226:                                 * error message.
                   1227:                                 */
1.11      markus   1228:                                quit_pending = 1;
                   1229:                                return;
                   1230:                        }
                   1231:                }
                   1232:                /* Consume printed characters from the buffer. */
                   1233:                buffer_consume(&stderr_buffer, len);
                   1234:        }
1.1       deraadt  1235: }
                   1236:
1.13      markus   1237: /*
1.15      markus   1238:  * Get packets from the connection input buffer, and process them as long as
                   1239:  * there are packets available.
                   1240:  *
                   1241:  * Any unknown packets received during the actual
                   1242:  * session cause the session to terminate.  This is
                   1243:  * intended to make debugging easier since no
                   1244:  * confirmations are sent.  Any compatible protocol
                   1245:  * extensions must be negotiated during the
                   1246:  * preparatory phase.
                   1247:  */
                   1248:
1.77      itojun   1249: static void
1.49      itojun   1250: client_process_buffered_input_packets(void)
1.15      markus   1251: {
1.197     djm      1252:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
                   1253:            compat20 ? xxx_kex : NULL);
1.15      markus   1254: }
                   1255:
1.31      markus   1256: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1257:
1.195     djm      1258: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1259: void *
                   1260: client_new_escape_filter_ctx(int escape_char)
                   1261: {
                   1262:        struct escape_filter_ctx *ret;
                   1263:
                   1264:        ret = xmalloc(sizeof(*ret));
                   1265:        ret->escape_pending = 0;
                   1266:        ret->escape_char = escape_char;
                   1267:        return (void *)ret;
                   1268: }
                   1269:
1.198     djm      1270: /* Free the escape filter context on channel free */
                   1271: void
                   1272: client_filter_cleanup(int cid, void *ctx)
                   1273: {
                   1274:        xfree(ctx);
                   1275: }
                   1276:
1.195     djm      1277: int
                   1278: client_simple_escape_filter(Channel *c, char *buf, int len)
1.30      markus   1279: {
1.190     djm      1280:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1281:                return 0;
                   1282:
1.195     djm      1283:        return process_escapes(c, &c->input, &c->output, &c->extended,
                   1284:            buf, len);
1.30      markus   1285: }
                   1286:
1.77      itojun   1287: static void
1.60      markus   1288: client_channel_closed(int id, void *arg)
                   1289: {
1.83      markus   1290:        channel_cancel_cleanup(id);
1.60      markus   1291:        session_closed = 1;
1.216     djm      1292:        leave_raw_mode(force_tty_flag);
1.60      markus   1293: }
                   1294:
1.15      markus   1295: /*
1.13      markus   1296:  * Implements the interactive session with the server.  This is called after
                   1297:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1298:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1299:  * used as an escape character for terminating or suspending the session.
1.13      markus   1300:  */
1.1       deraadt  1301:
1.20      markus   1302: int
1.30      markus   1303: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1       deraadt  1304: {
1.46      markus   1305:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus   1306:        double start_time, total_time;
1.130     avsm     1307:        int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1.200     markus   1308:        u_int64_t ibytes, obytes;
1.130     avsm     1309:        u_int nalloc = 0;
1.11      markus   1310:        char buf[100];
                   1311:
                   1312:        debug("Entering interactive session.");
                   1313:
                   1314:        start_time = get_current_time();
                   1315:
                   1316:        /* Initialize variables. */
1.195     djm      1317:        escape_pending1 = 0;
1.11      markus   1318:        last_was_cr = 1;
                   1319:        exit_status = -1;
                   1320:        stdin_eof = 0;
                   1321:        buffer_high = 64 * 1024;
                   1322:        connection_in = packet_get_connection_in();
                   1323:        connection_out = packet_get_connection_out();
1.46      markus   1324:        max_fd = MAX(connection_in, connection_out);
                   1325:
                   1326:        if (!compat20) {
1.63      markus   1327:                /* enable nonblocking unless tty */
                   1328:                if (!isatty(fileno(stdin)))
                   1329:                        set_nonblock(fileno(stdin));
                   1330:                if (!isatty(fileno(stdout)))
                   1331:                        set_nonblock(fileno(stdout));
                   1332:                if (!isatty(fileno(stderr)))
                   1333:                        set_nonblock(fileno(stderr));
1.46      markus   1334:                max_fd = MAX(max_fd, fileno(stdin));
                   1335:                max_fd = MAX(max_fd, fileno(stdout));
                   1336:                max_fd = MAX(max_fd, fileno(stderr));
                   1337:        }
1.11      markus   1338:        quit_pending = 0;
1.195     djm      1339:        escape_char1 = escape_char_arg;
1.11      markus   1340:
                   1341:        /* Initialize buffers. */
                   1342:        buffer_init(&stdin_buffer);
                   1343:        buffer_init(&stdout_buffer);
                   1344:        buffer_init(&stderr_buffer);
                   1345:
1.15      markus   1346:        client_init_dispatch();
                   1347:
1.105     markus   1348:        /*
                   1349:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1350:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1351:         */
1.131     djm      1352:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1353:                signal(SIGHUP, signal_handler);
1.105     markus   1354:        if (signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1355:                signal(SIGINT, signal_handler);
                   1356:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1357:                signal(SIGQUIT, signal_handler);
                   1358:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1359:                signal(SIGTERM, signal_handler);
1.132     djm      1360:        signal(SIGWINCH, window_change_handler);
1.11      markus   1361:
                   1362:        if (have_pty)
1.216     djm      1363:                enter_raw_mode(force_tty_flag);
1.11      markus   1364:
1.48      markus   1365:        if (compat20) {
                   1366:                session_ident = ssh2_chan_id;
1.195     djm      1367:                if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1.48      markus   1368:                        channel_register_filter(session_ident,
1.195     djm      1369:                            client_simple_escape_filter, NULL,
1.198     djm      1370:                            client_filter_cleanup,
1.195     djm      1371:                            client_new_escape_filter_ctx(escape_char_arg));
1.60      markus   1372:                if (session_ident != -1)
                   1373:                        channel_register_cleanup(session_ident,
1.143     djm      1374:                            client_channel_closed, 0);
1.48      markus   1375:        } else {
                   1376:                /* Check if we should immediately send eof on stdin. */
1.16      markus   1377:                client_check_initial_eof_on_stdin();
1.48      markus   1378:        }
1.30      markus   1379:
1.11      markus   1380:        /* Main loop of the client for the interactive session mode. */
                   1381:        while (!quit_pending) {
                   1382:
1.13      markus   1383:                /* Process buffered packets sent by the server. */
1.11      markus   1384:                client_process_buffered_input_packets();
                   1385:
1.60      markus   1386:                if (compat20 && session_closed && !channel_still_open())
                   1387:                        break;
                   1388:
1.56      markus   1389:                rekeying = (xxx_kex != NULL && !xxx_kex->done);
1.16      markus   1390:
1.56      markus   1391:                if (rekeying) {
                   1392:                        debug("rekeying in progress");
                   1393:                } else {
                   1394:                        /*
                   1395:                         * Make packets of buffered stdin data, and buffer
                   1396:                         * them for sending to the server.
                   1397:                         */
                   1398:                        if (!compat20)
                   1399:                                client_make_packets_from_stdin_data();
1.11      markus   1400:
1.56      markus   1401:                        /*
                   1402:                         * Make packets from buffered channel data, and
                   1403:                         * enqueue them for sending to the server.
                   1404:                         */
                   1405:                        if (packet_not_very_much_data_to_write())
                   1406:                                channel_output_poll();
1.11      markus   1407:
1.56      markus   1408:                        /*
                   1409:                         * Check if the window size has changed, and buffer a
                   1410:                         * message about it to the server if so.
                   1411:                         */
                   1412:                        client_check_window_change();
1.11      markus   1413:
1.56      markus   1414:                        if (quit_pending)
                   1415:                                break;
                   1416:                }
1.13      markus   1417:                /*
                   1418:                 * Wait until we have something to do (something becomes
                   1419:                 * available on one of the descriptors).
                   1420:                 */
1.81      markus   1421:                max_fd2 = max_fd;
1.56      markus   1422:                client_wait_until_can_do_something(&readset, &writeset,
1.81      markus   1423:                    &max_fd2, &nalloc, rekeying);
1.11      markus   1424:
                   1425:                if (quit_pending)
                   1426:                        break;
                   1427:
1.56      markus   1428:                /* Do channel operations unless rekeying in progress. */
                   1429:                if (!rekeying) {
                   1430:                        channel_after_select(readset, writeset);
1.108     markus   1431:                        if (need_rekeying || packet_need_rekeying()) {
                   1432:                                debug("need rekeying");
1.56      markus   1433:                                xxx_kex->done = 0;
                   1434:                                kex_send_kexinit(xxx_kex);
                   1435:                                need_rekeying = 0;
                   1436:                        }
                   1437:                }
1.11      markus   1438:
1.17      markus   1439:                /* Buffer input from the connection.  */
1.46      markus   1440:                client_process_net_input(readset);
1.17      markus   1441:
                   1442:                if (quit_pending)
                   1443:                        break;
1.11      markus   1444:
1.17      markus   1445:                if (!compat20) {
                   1446:                        /* Buffer data from stdin */
1.46      markus   1447:                        client_process_input(readset);
1.17      markus   1448:                        /*
                   1449:                         * Process output to stdout and stderr.  Output to
                   1450:                         * the connection is processed elsewhere (above).
                   1451:                         */
1.46      markus   1452:                        client_process_output(writeset);
1.214     andreas  1453:                }
                   1454:
                   1455:                if (session_resumed) {
                   1456:                        connection_in = packet_get_connection_in();
                   1457:                        connection_out = packet_get_connection_out();
                   1458:                        max_fd = MAX(max_fd, connection_out);
                   1459:                        max_fd = MAX(max_fd, connection_in);
                   1460:                        session_resumed = 0;
1.17      markus   1461:                }
1.11      markus   1462:
1.197     djm      1463:                /*
                   1464:                 * Send as much buffered packet data as possible to the
                   1465:                 * sender.
                   1466:                 */
1.46      markus   1467:                if (FD_ISSET(connection_out, writeset))
1.11      markus   1468:                        packet_write_poll();
                   1469:        }
1.46      markus   1470:        if (readset)
                   1471:                xfree(readset);
                   1472:        if (writeset)
                   1473:                xfree(writeset);
1.11      markus   1474:
                   1475:        /* Terminate the session. */
                   1476:
                   1477:        /* Stop watching for window change. */
1.132     djm      1478:        signal(SIGWINCH, SIG_DFL);
1.211     andreas  1479:
1.213     stevesk  1480:        if (compat20) {
                   1481:                packet_start(SSH2_MSG_DISCONNECT);
                   1482:                packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
                   1483:                packet_put_cstring("disconnected by user");
1.219     djm      1484:                packet_put_cstring(""); /* language tag */
1.213     stevesk  1485:                packet_send();
                   1486:                packet_write_wait();
                   1487:        }
1.11      markus   1488:
1.76      markus   1489:        channel_free_all();
1.11      markus   1490:
1.75      markus   1491:        if (have_pty)
1.216     djm      1492:                leave_raw_mode(force_tty_flag);
1.75      markus   1493:
                   1494:        /* restore blocking io */
                   1495:        if (!isatty(fileno(stdin)))
                   1496:                unset_nonblock(fileno(stdin));
                   1497:        if (!isatty(fileno(stdout)))
                   1498:                unset_nonblock(fileno(stdout));
                   1499:        if (!isatty(fileno(stderr)))
                   1500:                unset_nonblock(fileno(stderr));
1.116     dtucker  1501:
                   1502:        /*
                   1503:         * If there was no shell or command requested, there will be no remote
                   1504:         * exit status to be returned.  In that case, clear error code if the
                   1505:         * connection was deliberately terminated at this end.
                   1506:         */
                   1507:        if (no_shell_flag && received_signal == SIGTERM) {
                   1508:                received_signal = 0;
                   1509:                exit_status = 0;
                   1510:        }
1.75      markus   1511:
1.113     markus   1512:        if (received_signal)
1.89      itojun   1513:                fatal("Killed by signal %d.", (int) received_signal);
1.75      markus   1514:
1.13      markus   1515:        /*
                   1516:         * In interactive mode (with pseudo tty) display a message indicating
                   1517:         * that the connection has been closed.
                   1518:         */
1.11      markus   1519:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.197     djm      1520:                snprintf(buf, sizeof buf,
                   1521:                    "Connection to %.64s closed.\r\n", host);
1.11      markus   1522:                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1523:        }
1.70      markus   1524:
1.11      markus   1525:        /* Output any buffered data for stdout. */
1.70      markus   1526:        while (buffer_len(&stdout_buffer) > 0) {
                   1527:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1528:                    buffer_len(&stdout_buffer));
1.70      markus   1529:                if (len <= 0) {
1.11      markus   1530:                        error("Write failed flushing stdout buffer.");
1.70      markus   1531:                        break;
                   1532:                }
1.11      markus   1533:                buffer_consume(&stdout_buffer, len);
                   1534:        }
                   1535:
                   1536:        /* Output any buffered data for stderr. */
1.70      markus   1537:        while (buffer_len(&stderr_buffer) > 0) {
                   1538:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1539:                    buffer_len(&stderr_buffer));
1.70      markus   1540:                if (len <= 0) {
1.11      markus   1541:                        error("Write failed flushing stderr buffer.");
1.70      markus   1542:                        break;
                   1543:                }
1.11      markus   1544:                buffer_consume(&stderr_buffer, len);
                   1545:        }
                   1546:
                   1547:        /* Clear and free any buffers. */
                   1548:        memset(buf, 0, sizeof(buf));
                   1549:        buffer_free(&stdin_buffer);
                   1550:        buffer_free(&stdout_buffer);
                   1551:        buffer_free(&stderr_buffer);
                   1552:
                   1553:        /* Report bytes transferred, and transfer rates. */
                   1554:        total_time = get_current_time() - start_time;
1.200     markus   1555:        packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
                   1556:        packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
                   1557:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
                   1558:            obytes, ibytes, total_time);
1.11      markus   1559:        if (total_time > 0)
1.200     markus   1560:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1561:                    obytes / total_time, ibytes / total_time);
1.11      markus   1562:        /* Return the exit status of the program. */
                   1563:        debug("Exit status %d", exit_status);
                   1564:        return exit_status;
1.15      markus   1565: }
                   1566:
                   1567: /*********/
                   1568:
1.77      itojun   1569: static void
1.94      markus   1570: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1571: {
1.42      markus   1572:        u_int data_len;
1.15      markus   1573:        char *data = packet_get_string(&data_len);
1.93      markus   1574:        packet_check_eom();
1.15      markus   1575:        buffer_append(&stdout_buffer, data, data_len);
                   1576:        memset(data, 0, data_len);
                   1577:        xfree(data);
                   1578: }
1.77      itojun   1579: static void
1.94      markus   1580: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1581: {
1.42      markus   1582:        u_int data_len;
1.15      markus   1583:        char *data = packet_get_string(&data_len);
1.93      markus   1584:        packet_check_eom();
1.15      markus   1585:        buffer_append(&stderr_buffer, data, data_len);
                   1586:        memset(data, 0, data_len);
                   1587:        xfree(data);
                   1588: }
1.77      itojun   1589: static void
1.94      markus   1590: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15      markus   1591: {
                   1592:        exit_status = packet_get_int();
1.93      markus   1593:        packet_check_eom();
1.15      markus   1594:        /* Acknowledge the exit. */
                   1595:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                   1596:        packet_send();
                   1597:        /*
                   1598:         * Must wait for packet to be sent since we are
                   1599:         * exiting the loop.
                   1600:         */
                   1601:        packet_write_wait();
                   1602:        /* Flag that we want to exit. */
                   1603:        quit_pending = 1;
                   1604: }
1.115     markus   1605: static void
                   1606: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
                   1607: {
                   1608:        Channel *c = NULL;
                   1609:        int remote_id, sock;
                   1610:
                   1611:        /* Read the remote channel number from the message. */
                   1612:        remote_id = packet_get_int();
                   1613:        packet_check_eom();
                   1614:
                   1615:        /*
                   1616:         * Get a connection to the local authentication agent (this may again
                   1617:         * get forwarded).
                   1618:         */
                   1619:        sock = ssh_get_authentication_socket();
                   1620:
                   1621:        /*
                   1622:         * If we could not connect the agent, send an error message back to
                   1623:         * the server. This should never happen unless the agent dies,
                   1624:         * because authentication forwarding is only enabled if we have an
                   1625:         * agent.
                   1626:         */
                   1627:        if (sock >= 0) {
                   1628:                c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
                   1629:                    -1, 0, 0, 0, "authentication agent connection", 1);
                   1630:                c->remote_id = remote_id;
                   1631:                c->force_drain = 1;
                   1632:        }
                   1633:        if (c == NULL) {
                   1634:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1635:                packet_put_int(remote_id);
                   1636:        } else {
                   1637:                /* Send a confirmation to the remote host. */
                   1638:                debug("Forwarding authentication connection.");
                   1639:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1640:                packet_put_int(remote_id);
                   1641:                packet_put_int(c->self);
                   1642:        }
                   1643:        packet_send();
                   1644: }
1.15      markus   1645:
1.77      itojun   1646: static Channel *
1.40      markus   1647: client_request_forwarded_tcpip(const char *request_type, int rchan)
                   1648: {
1.103     deraadt  1649:        Channel *c = NULL;
1.40      markus   1650:        char *listen_address, *originator_address;
1.208     djm      1651:        u_short listen_port, originator_port;
1.40      markus   1652:
                   1653:        /* Get rest of the packet */
                   1654:        listen_address = packet_get_string(NULL);
                   1655:        listen_port = packet_get_int();
                   1656:        originator_address = packet_get_string(NULL);
                   1657:        originator_port = packet_get_int();
1.93      markus   1658:        packet_check_eom();
1.40      markus   1659:
1.191     djm      1660:        debug("client_request_forwarded_tcpip: listen %s port %d, "
                   1661:            "originator %s port %d", listen_address, listen_port,
                   1662:            originator_address, originator_port);
                   1663:
                   1664:        c = channel_connect_by_listen_address(listen_port,
                   1665:            "forwarded-tcpip", originator_address);
1.40      markus   1666:
                   1667:        xfree(originator_address);
                   1668:        xfree(listen_address);
                   1669:        return c;
                   1670: }
                   1671:
1.103     deraadt  1672: static Channel *
1.40      markus   1673: client_request_x11(const char *request_type, int rchan)
                   1674: {
                   1675:        Channel *c = NULL;
                   1676:        char *originator;
1.208     djm      1677:        u_short originator_port;
1.67      markus   1678:        int sock;
1.40      markus   1679:
                   1680:        if (!options.forward_x11) {
                   1681:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1682:                error("Warning: this is probably a break-in attempt by a "
                   1683:                    "malicious server.");
1.221   ! djm      1684:                return NULL;
        !          1685:        }
        !          1686:        if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
        !          1687:                verbose("Rejected X11 connection after ForwardX11Timeout "
        !          1688:                    "expired");
1.40      markus   1689:                return NULL;
                   1690:        }
                   1691:        originator = packet_get_string(NULL);
                   1692:        if (datafellows & SSH_BUG_X11FWD) {
                   1693:                debug2("buggy server: x11 request w/o originator_port");
                   1694:                originator_port = 0;
                   1695:        } else {
                   1696:                originator_port = packet_get_int();
                   1697:        }
1.93      markus   1698:        packet_check_eom();
1.40      markus   1699:        /* XXX check permission */
1.47      markus   1700:        debug("client_request_x11: request from %s %d", originator,
                   1701:            originator_port);
1.67      markus   1702:        xfree(originator);
1.40      markus   1703:        sock = x11_connect_display();
1.67      markus   1704:        if (sock < 0)
                   1705:                return NULL;
                   1706:        c = channel_new("x11",
                   1707:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1708:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1709:        c->force_drain = 1;
1.40      markus   1710:        return c;
                   1711: }
                   1712:
1.103     deraadt  1713: static Channel *
1.40      markus   1714: client_request_agent(const char *request_type, int rchan)
                   1715: {
                   1716:        Channel *c = NULL;
1.67      markus   1717:        int sock;
1.40      markus   1718:
                   1719:        if (!options.forward_agent) {
                   1720:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1721:                error("Warning: this is probably a break-in attempt by a "
                   1722:                    "malicious server.");
1.40      markus   1723:                return NULL;
                   1724:        }
1.177     stevesk  1725:        sock = ssh_get_authentication_socket();
1.67      markus   1726:        if (sock < 0)
                   1727:                return NULL;
                   1728:        c = channel_new("authentication agent connection",
                   1729:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1730:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1731:            "authentication agent connection", 1);
1.82      markus   1732:        c->force_drain = 1;
1.40      markus   1733:        return c;
1.180     djm      1734: }
                   1735:
                   1736: int
                   1737: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
                   1738: {
                   1739:        Channel *c;
                   1740:        int fd;
                   1741:
                   1742:        if (tun_mode == SSH_TUNMODE_NO)
                   1743:                return 0;
                   1744:
                   1745:        if (!compat20) {
1.207     stevesk  1746:                error("Tunnel forwarding is not supported for protocol 1");
1.180     djm      1747:                return -1;
                   1748:        }
                   1749:
                   1750:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1751:
                   1752:        /* Open local tunnel device */
                   1753:        if ((fd = tun_open(local_tun, tun_mode)) == -1) {
                   1754:                error("Tunnel device open failed.");
                   1755:                return -1;
                   1756:        }
                   1757:
                   1758:        c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
                   1759:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1760:        c->datagram = 1;
                   1761:
                   1762:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1763:        packet_put_cstring("tun@openssh.com");
                   1764:        packet_put_int(c->self);
                   1765:        packet_put_int(c->local_window_max);
                   1766:        packet_put_int(c->local_maxpacket);
                   1767:        packet_put_int(tun_mode);
                   1768:        packet_put_int(remote_tun);
                   1769:        packet_send();
                   1770:
                   1771:        return 0;
1.40      markus   1772: }
                   1773:
1.22      markus   1774: /* XXXX move to generic input handler */
1.77      itojun   1775: static void
1.94      markus   1776: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22      markus   1777: {
                   1778:        Channel *c = NULL;
                   1779:        char *ctype;
                   1780:        int rchan;
1.102     markus   1781:        u_int rmaxpack, rwindow, len;
1.22      markus   1782:
                   1783:        ctype = packet_get_string(&len);
                   1784:        rchan = packet_get_int();
                   1785:        rwindow = packet_get_int();
                   1786:        rmaxpack = packet_get_int();
                   1787:
1.24      markus   1788:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1789:            ctype, rchan, rwindow, rmaxpack);
                   1790:
1.40      markus   1791:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
                   1792:                c = client_request_forwarded_tcpip(ctype, rchan);
                   1793:        } else if (strcmp(ctype, "x11") == 0) {
                   1794:                c = client_request_x11(ctype, rchan);
                   1795:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
                   1796:                c = client_request_agent(ctype, rchan);
1.22      markus   1797:        }
                   1798: /* XXX duplicate : */
                   1799:        if (c != NULL) {
                   1800:                debug("confirm %s", ctype);
                   1801:                c->remote_id = rchan;
                   1802:                c->remote_window = rwindow;
                   1803:                c->remote_maxpacket = rmaxpack;
1.69      markus   1804:                if (c->type != SSH_CHANNEL_CONNECTING) {
                   1805:                        packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1806:                        packet_put_int(c->remote_id);
                   1807:                        packet_put_int(c->self);
                   1808:                        packet_put_int(c->local_window);
                   1809:                        packet_put_int(c->local_maxpacket);
                   1810:                        packet_send();
                   1811:                }
1.22      markus   1812:        } else {
                   1813:                debug("failure %s", ctype);
                   1814:                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1815:                packet_put_int(rchan);
                   1816:                packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66      markus   1817:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69      markus   1818:                        packet_put_cstring("open failed");
1.66      markus   1819:                        packet_put_cstring("");
                   1820:                }
1.22      markus   1821:                packet_send();
                   1822:        }
                   1823:        xfree(ctype);
                   1824: }
1.77      itojun   1825: static void
1.94      markus   1826: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48      markus   1827: {
                   1828:        Channel *c = NULL;
1.123     djm      1829:        int exitval, id, reply, success = 0;
1.48      markus   1830:        char *rtype;
                   1831:
                   1832:        id = packet_get_int();
                   1833:        rtype = packet_get_string(NULL);
                   1834:        reply = packet_get_char();
                   1835:
                   1836:        debug("client_input_channel_req: channel %d rtype %s reply %d",
                   1837:            id, rtype, reply);
                   1838:
1.128     djm      1839:        if (id == -1) {
                   1840:                error("client_input_channel_req: request for channel -1");
                   1841:        } else if ((c = channel_lookup(id)) == NULL) {
1.197     djm      1842:                error("client_input_channel_req: channel %d: "
                   1843:                    "unknown channel", id);
1.193     markus   1844:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
                   1845:                packet_check_eom();
                   1846:                chan_rcvd_eow(c);
1.48      markus   1847:        } else if (strcmp(rtype, "exit-status") == 0) {
1.123     djm      1848:                exitval = packet_get_int();
1.217     djm      1849:                if (c->ctl_chan != -1) {
                   1850:                        mux_exit_message(c, exitval);
1.215     djm      1851:                        success = 1;
                   1852:                } else if (id == session_ident) {
                   1853:                        /* Record exit value of local session */
1.123     djm      1854:                        success = 1;
                   1855:                        exit_status = exitval;
1.215     djm      1856:                } else {
1.218     djm      1857:                        /* Probably for a mux channel that has already closed */
                   1858:                        debug("%s: no sink for exit-status on channel %d",
                   1859:                            __func__, id);
1.123     djm      1860:                }
1.93      markus   1861:                packet_check_eom();
1.48      markus   1862:        }
                   1863:        if (reply) {
                   1864:                packet_start(success ?
                   1865:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.205     markus   1866:                packet_put_int(c->remote_id);
1.48      markus   1867:                packet_send();
                   1868:        }
                   1869:        xfree(rtype);
                   1870: }
1.95      markus   1871: static void
                   1872: client_input_global_request(int type, u_int32_t seq, void *ctxt)
                   1873: {
                   1874:        char *rtype;
                   1875:        int want_reply;
                   1876:        int success = 0;
                   1877:
                   1878:        rtype = packet_get_string(NULL);
                   1879:        want_reply = packet_get_char();
1.117     markus   1880:        debug("client_input_global_request: rtype %s want_reply %d",
                   1881:            rtype, want_reply);
1.95      markus   1882:        if (want_reply) {
                   1883:                packet_start(success ?
                   1884:                    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
                   1885:                packet_send();
                   1886:                packet_write_wait();
                   1887:        }
                   1888:        xfree(rtype);
                   1889: }
1.22      markus   1890:
1.123     djm      1891: void
1.129     deraadt  1892: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190     djm      1893:     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123     djm      1894: {
                   1895:        int len;
1.132     djm      1896:        Channel *c = NULL;
1.123     djm      1897:
                   1898:        debug2("%s: id %d", __func__, id);
                   1899:
1.132     djm      1900:        if ((c = channel_lookup(id)) == NULL)
                   1901:                fatal("client_session2_setup: channel %d: unknown channel", id);
                   1902:
1.123     djm      1903:        if (want_tty) {
                   1904:                struct winsize ws;
                   1905:
                   1906:                /* Store window size in the packet. */
                   1907:                if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
                   1908:                        memset(&ws, 0, sizeof(ws));
                   1909:
1.190     djm      1910:                channel_request_start(id, "pty-req", 1);
1.220     djm      1911:                client_expect_confirm(id, "PTY allocation", 1);
1.123     djm      1912:                packet_put_cstring(term != NULL ? term : "");
1.158     deraadt  1913:                packet_put_int((u_int)ws.ws_col);
                   1914:                packet_put_int((u_int)ws.ws_row);
                   1915:                packet_put_int((u_int)ws.ws_xpixel);
                   1916:                packet_put_int((u_int)ws.ws_ypixel);
1.194     djm      1917:                if (tiop == NULL)
                   1918:                        tiop = get_saved_tio();
                   1919:                tty_make_modes(-1, tiop);
1.123     djm      1920:                packet_send();
                   1921:                /* XXX wait for reply */
1.132     djm      1922:                c->client_tty = 1;
1.123     djm      1923:        }
                   1924:
                   1925:        /* Transfer any environment variables from client to server */
1.126     djm      1926:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      1927:                int i, j, matched;
                   1928:                char *name, *val;
                   1929:
                   1930:                debug("Sending environment.");
1.126     djm      1931:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      1932:                        /* Split */
1.126     djm      1933:                        name = xstrdup(env[i]);
1.123     djm      1934:                        if ((val = strchr(name, '=')) == NULL) {
1.144     stevesk  1935:                                xfree(name);
1.123     djm      1936:                                continue;
                   1937:                        }
                   1938:                        *val++ = '\0';
                   1939:
                   1940:                        matched = 0;
                   1941:                        for (j = 0; j < options.num_send_env; j++) {
                   1942:                                if (match_pattern(name, options.send_env[j])) {
                   1943:                                        matched = 1;
                   1944:                                        break;
                   1945:                                }
                   1946:                        }
                   1947:                        if (!matched) {
                   1948:                                debug3("Ignored env %s", name);
1.144     stevesk  1949:                                xfree(name);
1.123     djm      1950:                                continue;
                   1951:                        }
                   1952:
                   1953:                        debug("Sending env %s = %s", name, val);
                   1954:                        channel_request_start(id, "env", 0);
                   1955:                        packet_put_cstring(name);
                   1956:                        packet_put_cstring(val);
                   1957:                        packet_send();
1.144     stevesk  1958:                        xfree(name);
1.123     djm      1959:                }
                   1960:        }
                   1961:
                   1962:        len = buffer_len(cmd);
                   1963:        if (len > 0) {
                   1964:                if (len > 900)
                   1965:                        len = 900;
                   1966:                if (want_subsystem) {
1.190     djm      1967:                        debug("Sending subsystem: %.*s",
                   1968:                            len, (u_char*)buffer_ptr(cmd));
                   1969:                        channel_request_start(id, "subsystem", 1);
                   1970:                        client_expect_confirm(id, "subsystem", 1);
1.123     djm      1971:                } else {
1.190     djm      1972:                        debug("Sending command: %.*s",
                   1973:                            len, (u_char*)buffer_ptr(cmd));
                   1974:                        channel_request_start(id, "exec", 1);
                   1975:                        client_expect_confirm(id, "exec", 1);
1.123     djm      1976:                }
                   1977:                packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
                   1978:                packet_send();
                   1979:        } else {
1.190     djm      1980:                channel_request_start(id, "shell", 1);
                   1981:                client_expect_confirm(id, "shell", 1);
1.123     djm      1982:                packet_send();
                   1983:        }
                   1984: }
                   1985:
1.77      itojun   1986: static void
1.49      itojun   1987: client_init_dispatch_20(void)
1.16      markus   1988: {
1.55      markus   1989:        dispatch_init(&dispatch_protocol_error);
1.100     markus   1990:
1.16      markus   1991:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   1992:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   1993:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   1994:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22      markus   1995:        dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16      markus   1996:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   1997:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48      markus   1998:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16      markus   1999:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189     djm      2000:        dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2001:        dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95      markus   2002:        dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2003:
                   2004:        /* rekeying */
                   2005:        dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2006:
                   2007:        /* global request reply messages */
                   2008:        dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2009:        dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16      markus   2010: }
1.197     djm      2011:
1.77      itojun   2012: static void
1.49      itojun   2013: client_init_dispatch_13(void)
1.15      markus   2014: {
                   2015:        dispatch_init(NULL);
                   2016:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                   2017:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                   2018:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                   2019:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2020:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2021:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                   2022:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                   2023:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                   2024:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39      markus   2025:
                   2026:        dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115     markus   2027:            &client_input_agent_open : &deny_input_open);
1.39      markus   2028:        dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
                   2029:            &x11_input_open : &deny_input_open);
1.15      markus   2030: }
1.197     djm      2031:
1.77      itojun   2032: static void
1.49      itojun   2033: client_init_dispatch_15(void)
1.15      markus   2034: {
                   2035:        client_init_dispatch_13();
                   2036:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                   2037:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                   2038: }
1.197     djm      2039:
1.79      stevesk  2040: static void
1.49      itojun   2041: client_init_dispatch(void)
1.15      markus   2042: {
1.16      markus   2043:        if (compat20)
                   2044:                client_init_dispatch_20();
                   2045:        else if (compat13)
1.15      markus   2046:                client_init_dispatch_13();
                   2047:        else
                   2048:                client_init_dispatch_15();
1.113     markus   2049: }
                   2050:
                   2051: /* client specific fatal cleanup */
                   2052: void
1.114     markus   2053: cleanup_exit(int i)
1.113     markus   2054: {
1.216     djm      2055:        leave_raw_mode(force_tty_flag);
1.113     markus   2056:        leave_non_blocking();
1.192     djm      2057:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2058:                unlink(options.control_path);
1.114     markus   2059:        _exit(i);
1.1       deraadt  2060: }