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

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