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

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