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

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