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

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