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

1.393   ! djm         1: /* $OpenBSD: clientloop.c,v 1.392 2023/04/03 08:10:54 dtucker 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.374     djm        73: #include <poll.h>
1.153     stevesk    74: #include <signal.h>
1.174     stevesk    75: #include <stdio.h>
1.173     stevesk    76: #include <stdlib.h>
1.170     stevesk    77: #include <string.h>
1.328     deraadt    78: #include <stdarg.h>
1.150     stevesk    79: #include <termios.h>
1.175     deraadt    80: #include <pwd.h>
1.169     stevesk    81: #include <unistd.h>
1.266     deraadt    82: #include <limits.h>
1.1       deraadt    83:
1.175     deraadt    84: #include "xmalloc.h"
1.45      markus     85: #include "ssh.h"
                     86: #include "ssh2.h"
1.1       deraadt    87: #include "packet.h"
1.315     markus     88: #include "sshbuf.h"
1.15      markus     89: #include "compat.h"
1.74      markus     90: #include "channels.h"
1.15      markus     91: #include "dispatch.h"
1.317     markus     92: #include "sshkey.h"
1.175     deraadt    93: #include "cipher.h"
1.54      markus     94: #include "kex.h"
1.275     markus     95: #include "myproposal.h"
1.45      markus     96: #include "log.h"
1.261     millert    97: #include "misc.h"
1.45      markus     98: #include "readconf.h"
                     99: #include "clientloop.h"
1.147     djm       100: #include "sshconnect.h"
1.40      markus    101: #include "authfd.h"
1.45      markus    102: #include "atomicio.h"
1.118     deraadt   103: #include "sshpty.h"
1.123     djm       104: #include "match.h"
                    105: #include "msg.h"
1.262     djm       106: #include "ssherr.h"
1.267     djm       107: #include "hostfile.h"
1.319     djm       108:
1.375     djm       109: /* Permitted RSA signature algorithms for UpdateHostkeys proofs */
                    110: #define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256"
                    111:
1.39      markus    112: /* import options */
                    113: extern Options options;
1.1       deraadt   114:
1.123     djm       115: /* Control socket */
1.217     djm       116: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123     djm       117:
1.13      markus    118: /*
                    119:  * Name of the host we are connecting to.  This is the name given on the
1.324     jmc       120:  * command line, or the Hostname specified for the user-supplied name in a
1.13      markus    121:  * configuration file.
                    122:  */
1.1       deraadt   123: extern char *host;
                    124:
1.13      markus    125: /*
1.330     djm       126:  * If this field is not NULL, the ForwardAgent socket is this path and different
                    127:  * instead of SSH_AUTH_SOCK.
                    128:  */
                    129: extern char *forward_agent_sock_path;
                    130:
                    131: /*
1.13      markus    132:  * Flag to indicate that we have received a window change signal which has
                    133:  * not yet been processed.  This will cause a message indicating the new
                    134:  * window size to be sent to the server a little later.  This is volatile
                    135:  * because this is updated in a signal handler.
                    136:  */
1.88      markus    137: static volatile sig_atomic_t received_window_change_signal = 0;
                    138: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   139:
1.222     djm       140: /* Time when backgrounded control master using ControlPersist should exit */
                    141: static time_t control_persist_exit_time = 0;
                    142:
1.1       deraadt   143: /* Common data for the client loop code. */
1.217     djm       144: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.11      markus    145: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       146: static int exit_status;                /* Used to store the command exit status. */
1.315     markus    147: static struct sshbuf *stderr_buffer;   /* Used for final exit message. */
1.11      markus    148: static int connection_in;      /* Connection to server (input). */
                    149: static int connection_out;     /* Connection to server (output). */
1.56      markus    150: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221     djm       151: static int session_closed;     /* In SSH2: login session closed. */
1.388     dtucker   152: static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */
1.345     dtucker   153: static time_t server_alive_time;       /* Time to do server_alive_check */
1.384     djm       154: static int hostkeys_update_complete;
                    155: static int session_setup_complete;
1.1       deraadt   156:
1.321     djm       157: static void client_init_dispatch(struct ssh *ssh);
1.16      markus    158: int    session_ident = -1;
                    159:
1.195     djm       160: /* Track escape per proto2 channel */
                    161: struct escape_filter_ctx {
                    162:        int escape_pending;
                    163:        int escape_char;
                    164: };
                    165:
                    166: /* Context for channel confirmation replies */
1.190     djm       167: struct channel_reply_ctx {
                    168:        const char *request_type;
1.234     djm       169:        int id;
                    170:        enum confirm_action action;
1.190     djm       171: };
                    172:
1.196     djm       173: /* Global request success/failure callbacks */
1.303     djm       174: /* XXX move to struct ssh? */
1.196     djm       175: struct global_confirm {
                    176:        TAILQ_ENTRY(global_confirm) entry;
                    177:        global_confirm_cb *cb;
                    178:        void *ctx;
                    179:        int ref_count;
                    180: };
                    181: TAILQ_HEAD(global_confirms, global_confirm);
                    182: static struct global_confirms global_confirms =
                    183:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    184:
1.315     markus    185: void ssh_process_session2_setup(int, int, int, struct sshbuf *);
1.377     djm       186: static void quit_message(const char *fmt, ...)
                    187:     __attribute__((__format__ (printf, 1, 2)));
                    188:
                    189: static void
                    190: quit_message(const char *fmt, ...)
                    191: {
                    192:        char *msg;
                    193:        va_list args;
                    194:        int r;
                    195:
                    196:        va_start(args, fmt);
                    197:        xvasprintf(&msg, fmt, args);
                    198:        va_end(args);
                    199:
                    200:        if ((r = sshbuf_putf(stderr_buffer, "%s\r\n", msg)) != 0)
                    201:                fatal_fr(r, "sshbuf_putf");
                    202:        quit_pending = 1;
                    203: }
1.123     djm       204:
1.13      markus    205: /*
                    206:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    207:  * flag indicating that the window has changed.
                    208:  */
1.77      itojun    209: static void
1.11      markus    210: window_change_handler(int sig)
1.1       deraadt   211: {
1.11      markus    212:        received_window_change_signal = 1;
1.1       deraadt   213: }
                    214:
1.13      markus    215: /*
                    216:  * Signal handler for signals that cause the program to terminate.  These
                    217:  * signals must be trapped to restore terminal modes.
                    218:  */
1.77      itojun    219: static void
1.11      markus    220: signal_handler(int sig)
1.1       deraadt   221: {
1.75      markus    222:        received_signal = sig;
                    223:        quit_pending = 1;
1.1       deraadt   224: }
                    225:
1.13      markus    226: /*
1.222     djm       227:  * Sets control_persist_exit_time to the absolute time when the
                    228:  * backgrounded control master should exit due to expiry of the
                    229:  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
                    230:  * control master process, or if there is no ControlPersist timeout.
                    231:  */
                    232: static void
1.303     djm       233: set_control_persist_exit_time(struct ssh *ssh)
1.222     djm       234: {
                    235:        if (muxserver_sock == -1 || !options.control_persist
1.232     djm       236:            || options.control_persist_timeout == 0) {
1.222     djm       237:                /* not using a ControlPersist timeout */
                    238:                control_persist_exit_time = 0;
1.303     djm       239:        } else if (channel_still_open(ssh)) {
1.222     djm       240:                /* some client connections are still open */
                    241:                if (control_persist_exit_time > 0)
1.354     djm       242:                        debug2_f("cancel scheduled exit");
1.222     djm       243:                control_persist_exit_time = 0;
                    244:        } else if (control_persist_exit_time <= 0) {
                    245:                /* a client connection has recently closed */
1.251     dtucker   246:                control_persist_exit_time = monotime() +
1.222     djm       247:                        (time_t)options.control_persist_timeout;
1.354     djm       248:                debug2_f("schedule exit in %d seconds",
1.222     djm       249:                    options.control_persist_timeout);
                    250:        }
                    251:        /* else we are already counting down to the timeout */
                    252: }
                    253:
1.238     dtucker   254: #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
                    255: static int
                    256: client_x11_display_valid(const char *display)
                    257: {
                    258:        size_t i, dlen;
                    259:
1.279     djm       260:        if (display == NULL)
                    261:                return 0;
                    262:
1.238     dtucker   263:        dlen = strlen(display);
                    264:        for (i = 0; i < dlen; i++) {
1.256     deraadt   265:                if (!isalnum((u_char)display[i]) &&
1.238     dtucker   266:                    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
                    267:                        debug("Invalid character '%c' in DISPLAY", display[i]);
                    268:                        return 0;
                    269:                }
                    270:        }
                    271:        return 1;
                    272: }
                    273:
1.274     djm       274: #define SSH_X11_PROTO          "MIT-MAGIC-COOKIE-1"
                    275: #define X11_TIMEOUT_SLACK      60
1.279     djm       276: int
1.303     djm       277: client_x11_get_proto(struct ssh *ssh, const char *display,
                    278:     const char *xauth_path, u_int trusted, u_int timeout,
                    279:     char **_proto, char **_data)
1.138     djm       280: {
1.318     djm       281:        char *cmd, line[512], xdisplay[512];
1.279     djm       282:        char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
1.138     djm       283:        static char proto[512], data[512];
                    284:        FILE *f;
1.288     tedu      285:        int got_data = 0, generated = 0, do_unlink = 0, r;
1.138     djm       286:        struct stat st;
1.274     djm       287:        u_int now, x11_timeout_real;
1.138     djm       288:
                    289:        *_proto = proto;
                    290:        *_data = data;
1.279     djm       291:        proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
1.138     djm       292:
1.279     djm       293:        if (!client_x11_display_valid(display)) {
1.283     millert   294:                if (display != NULL)
                    295:                        logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
                    296:                            display);
1.279     djm       297:                return -1;
                    298:        }
                    299:        if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
1.138     djm       300:                debug("No xauth program.");
1.279     djm       301:                xauth_path = NULL;
                    302:        }
                    303:
                    304:        if (xauth_path != NULL) {
1.138     djm       305:                /*
                    306:                 * Handle FamilyLocal case where $DISPLAY does
                    307:                 * not match an authorization entry.  For this we
                    308:                 * just try "xauth list unix:displaynum.screennum".
                    309:                 * XXX: "localhost" match to determine FamilyLocal
                    310:                 *      is not perfect.
                    311:                 */
                    312:                if (strncmp(display, "localhost:", 10) == 0) {
1.279     djm       313:                        if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    314:                            display + 10)) < 0 ||
                    315:                            (size_t)r >= sizeof(xdisplay)) {
1.354     djm       316:                                error_f("display name too long");
1.279     djm       317:                                return -1;
                    318:                        }
1.138     djm       319:                        display = xdisplay;
                    320:                }
                    321:                if (trusted == 0) {
1.274     djm       322:                        /*
1.279     djm       323:                         * Generate an untrusted X11 auth cookie.
                    324:                         *
1.274     djm       325:                         * The authentication cookie should briefly outlive
                    326:                         * ssh's willingness to forward X11 connections to
                    327:                         * avoid nasty fail-open behaviour in the X server.
                    328:                         */
1.279     djm       329:                        mktemp_proto(xauthdir, sizeof(xauthdir));
                    330:                        if (mkdtemp(xauthdir) == NULL) {
1.354     djm       331:                                error_f("mkdtemp: %s", strerror(errno));
1.279     djm       332:                                return -1;
                    333:                        }
                    334:                        do_unlink = 1;
                    335:                        if ((r = snprintf(xauthfile, sizeof(xauthfile),
                    336:                            "%s/xauthfile", xauthdir)) < 0 ||
                    337:                            (size_t)r >= sizeof(xauthfile)) {
1.354     djm       338:                                error_f("xauthfile path too long");
1.279     djm       339:                                rmdir(xauthdir);
                    340:                                return -1;
                    341:                        }
                    342:
1.318     djm       343:                        if (timeout == 0) {
                    344:                                /* auth doesn't time out */
                    345:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    346:                                    "untrusted 2>%s",
                    347:                                    xauth_path, xauthfile, display,
                    348:                                    SSH_X11_PROTO, _PATH_DEVNULL);
                    349:                        } else {
                    350:                                /* Add some slack to requested expiry */
                    351:                                if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
                    352:                                        x11_timeout_real = timeout +
                    353:                                            X11_TIMEOUT_SLACK;
                    354:                                else {
                    355:                                        /* Don't overflow on long timeouts */
                    356:                                        x11_timeout_real = UINT_MAX;
                    357:                                }
                    358:                                xasprintf(&cmd, "%s -f %s generate %s %s "
                    359:                                    "untrusted timeout %u 2>%s",
                    360:                                    xauth_path, xauthfile, display,
                    361:                                    SSH_X11_PROTO, x11_timeout_real,
                    362:                                    _PATH_DEVNULL);
                    363:                        }
1.354     djm       364:                        debug2_f("xauth command: %s", cmd);
1.318     djm       365:
                    366:                        if (timeout != 0 && x11_refuse_time == 0) {
1.279     djm       367:                                now = monotime() + 1;
1.388     dtucker   368:                                if (SSH_TIME_T_MAX - timeout < now)
                    369:                                        x11_refuse_time = SSH_TIME_T_MAX;
1.279     djm       370:                                else
                    371:                                        x11_refuse_time = now + timeout;
1.303     djm       372:                                channel_set_x11_refuse_time(ssh,
                    373:                                    x11_refuse_time);
1.138     djm       374:                        }
1.279     djm       375:                        if (system(cmd) == 0)
                    376:                                generated = 1;
1.318     djm       377:                        free(cmd);
1.138     djm       378:                }
1.181     markus    379:
                    380:                /*
                    381:                 * When in untrusted mode, we read the cookie only if it was
                    382:                 * successfully generated as an untrusted one in the step
                    383:                 * above.
                    384:                 */
                    385:                if (trusted || generated) {
1.318     djm       386:                        xasprintf(&cmd,
1.181     markus    387:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    388:                            xauth_path,
                    389:                            generated ? "-f " : "" ,
                    390:                            generated ? xauthfile : "",
                    391:                            display);
                    392:                        debug2("x11_get_proto: %s", cmd);
                    393:                        f = popen(cmd, "r");
                    394:                        if (f && fgets(line, sizeof(line), f) &&
                    395:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    396:                                got_data = 1;
                    397:                        if (f)
                    398:                                pclose(f);
1.318     djm       399:                        free(cmd);
1.279     djm       400:                }
1.138     djm       401:        }
                    402:
                    403:        if (do_unlink) {
                    404:                unlink(xauthfile);
                    405:                rmdir(xauthdir);
                    406:        }
                    407:
1.279     djm       408:        /* Don't fall back to fake X11 data for untrusted forwarding */
                    409:        if (!trusted && !got_data) {
                    410:                error("Warning: untrusted X11 forwarding setup failed: "
                    411:                    "xauth key data not generated");
                    412:                return -1;
                    413:        }
                    414:
1.138     djm       415:        /*
                    416:         * If we didn't get authentication data, just make up some
                    417:         * data.  The forwarding code will check the validity of the
                    418:         * response anyway, and substitute this data.  The X11
                    419:         * server, however, will ignore this fake data and use
                    420:         * whatever authentication mechanisms it was using otherwise
                    421:         * for the local connection.
                    422:         */
                    423:        if (!got_data) {
1.288     tedu      424:                u_int8_t rnd[16];
                    425:                u_int i;
1.138     djm       426:
                    427:                logit("Warning: No xauth data; "
                    428:                    "using fake authentication data for X11 forwarding.");
                    429:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.288     tedu      430:                arc4random_buf(rnd, sizeof(rnd));
                    431:                for (i = 0; i < sizeof(rnd); i++) {
1.138     djm       432:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.288     tedu      433:                            rnd[i]);
1.138     djm       434:                }
                    435:        }
1.279     djm       436:
                    437:        return 0;
1.1       deraadt   438: }
                    439:
1.13      markus    440: /*
                    441:  * Checks if the client window has changed, and sends a packet about it to
                    442:  * the server if so.  The actual change is detected elsewhere (by a software
                    443:  * interrupt on Unix); this just checks the flag and sends a message if
                    444:  * appropriate.
                    445:  */
1.1       deraadt   446:
1.77      itojun    447: static void
1.303     djm       448: client_check_window_change(struct ssh *ssh)
1.1       deraadt   449: {
1.292     djm       450:        if (!received_window_change_signal)
1.16      markus    451:                return;
                    452:        received_window_change_signal = 0;
1.354     djm       453:        debug2_f("changed");
1.303     djm       454:        channel_send_window_changes(ssh);
1.1       deraadt   455: }
                    456:
1.264     markus    457: static int
1.297     markus    458: client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
1.117     markus    459: {
1.196     djm       460:        struct global_confirm *gc;
                    461:
                    462:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
1.264     markus    463:                return 0;
1.196     djm       464:        if (gc->cb != NULL)
1.303     djm       465:                gc->cb(ssh, type, seq, gc->ctx);
1.196     djm       466:        if (--gc->ref_count <= 0) {
                    467:                TAILQ_REMOVE(&global_confirms, gc, entry);
1.342     jsg       468:                freezero(gc, sizeof(*gc));
1.196     djm       469:        }
                    470:
1.320     djm       471:        ssh_packet_set_alive_timeouts(ssh, 0);
1.264     markus    472:        return 0;
1.117     markus    473: }
                    474:
                    475: static void
1.345     dtucker   476: schedule_server_alive_check(void)
                    477: {
                    478:        if (options.server_alive_interval > 0)
                    479:                server_alive_time = monotime() + options.server_alive_interval;
                    480: }
                    481:
                    482: static void
1.320     djm       483: server_alive_check(struct ssh *ssh)
1.117     markus    484: {
1.320     djm       485:        int r;
                    486:
                    487:        if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
1.228     djm       488:                logit("Timeout, server %s not responding.", host);
1.176     markus    489:                cleanup_exit(255);
                    490:        }
1.320     djm       491:        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                    492:            (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
                    493:            (r = sshpkt_put_u8(ssh, 1)) != 0 ||         /* boolean: want reply */
                    494:            (r = sshpkt_send(ssh)) != 0)
1.354     djm       495:                fatal_fr(r, "send packet");
1.196     djm       496:        /* Insert an empty placeholder to maintain ordering */
                    497:        client_register_global_confirm(NULL, NULL);
1.345     dtucker   498:        schedule_server_alive_check();
1.117     markus    499: }
                    500:
1.393   ! djm       501: /* Try to send a dummy keystroke */
        !           502: static int
        !           503: send_chaff(struct ssh *ssh)
        !           504: {
        !           505:        int r;
        !           506:
        !           507:        if ((ssh->kex->flags & KEX_HAS_PING) == 0)
        !           508:                return 0;
        !           509:        /* XXX probabilistically send chaff? */
        !           510:        /*
        !           511:         * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
        !           512:         *    4 bytes channel ID + 4 bytes string length + 1 byte string data
        !           513:         * simulate that here.
        !           514:         */
        !           515:        if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
        !           516:            (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
        !           517:            (r = sshpkt_send(ssh)) != 0)
        !           518:                fatal_fr(r, "send packet");
        !           519:        return 1;
        !           520: }
        !           521:
        !           522: /*
        !           523:  * Performs keystroke timing obfuscation. Returns non-zero if the
        !           524:  * output fd should be polled.
        !           525:  */
        !           526: static int
        !           527: obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout)
        !           528: {
        !           529:        static int active;
        !           530:        static struct timespec next_interval, chaff_until;
        !           531:        struct timespec now, tmp;
        !           532:        int just_started = 0, had_keystroke = 0;
        !           533:        static unsigned long long nchaff;
        !           534:        char *stop_reason = NULL;
        !           535:        long long n;
        !           536:
        !           537:        monotime_ts(&now);
        !           538:
        !           539:        if (options.obscure_keystroke_timing_interval <= 0)
        !           540:                return 1;       /* disabled in config */
        !           541:
        !           542:        if (!channel_still_open(ssh) || quit_pending) {
        !           543:                /* Stop if no channels left of we're waiting for one to close */
        !           544:                stop_reason = "no active channels";
        !           545:        } else if (ssh_packet_is_rekeying(ssh)) {
        !           546:                /* Stop if we're rekeying */
        !           547:                stop_reason = "rekeying started";
        !           548:        } else if (!ssh_packet_interactive_data_to_write(ssh) &&
        !           549:            ssh_packet_have_data_to_write(ssh)) {
        !           550:                /* Stop if the output buffer has more than a few keystrokes */
        !           551:                stop_reason = "output buffer filling";
        !           552:        } else if (active && ssh_packet_have_data_to_write(ssh)) {
        !           553:                /* Still in active mode and have a keystroke queued. */
        !           554:                had_keystroke = 1;
        !           555:        } else if (active) {
        !           556:                if (timespeccmp(&now, &chaff_until, >=)) {
        !           557:                        /* Stop if there have been no keystrokes for a while */
        !           558:                        stop_reason = "chaff time expired";
        !           559:                } else if (timespeccmp(&now, &next_interval, >=)) {
        !           560:                        /* Otherwise if we were due to send, then send chaff */
        !           561:                        if (send_chaff(ssh))
        !           562:                                nchaff++;
        !           563:                }
        !           564:        }
        !           565:
        !           566:        if (stop_reason != NULL) {
        !           567:                active = 0;
        !           568:                debug3_f("stopping: %s (%llu chaff packets sent)",
        !           569:                    stop_reason, nchaff);
        !           570:                return 1;
        !           571:        }
        !           572:
        !           573:        /*
        !           574:         * If we're in interactive mode, and only have a small amount
        !           575:         * of outbound data, then we assume that the user is typing
        !           576:         * interactively. In this case, start quantising outbound packets to
        !           577:         * fixed time intervals to hide inter-keystroke timing.
        !           578:         */
        !           579:        if (!active && ssh_packet_interactive_data_to_write(ssh)) {
        !           580:                debug3_f("starting: interval %d",
        !           581:                    options.obscure_keystroke_timing_interval);
        !           582:                just_started = had_keystroke = active = 1;
        !           583:                nchaff = 0;
        !           584:                ms_to_timespec(&tmp, options.obscure_keystroke_timing_interval);
        !           585:                timespecadd(&now, &tmp, &next_interval);
        !           586:        }
        !           587:
        !           588:        /* Don't hold off if obfuscation inactive */
        !           589:        if (!active)
        !           590:                return 1;
        !           591:
        !           592:        if (had_keystroke) {
        !           593:                /*
        !           594:                 * Arrange to send chaff packets for a random interval after
        !           595:                 * the last keystroke was sent.
        !           596:                 */
        !           597:                ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
        !           598:                    arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
        !           599:                timespecadd(&now, &tmp, &chaff_until);
        !           600:        }
        !           601:
        !           602:        ptimeout_deadline_monotime_tsp(timeout, &next_interval);
        !           603:
        !           604:        if (just_started)
        !           605:                return 1;
        !           606:
        !           607:        /* Don't arm output fd for poll until the timing interval has elapsed */
        !           608:        if (timespeccmp(&now, &next_interval, <))
        !           609:                return 0;
        !           610:
        !           611:        /* Calculate number of intervals missed since the last check */
        !           612:        n = (now.tv_sec - next_interval.tv_sec) * 1000 * 1000 * 1000;
        !           613:        n += now.tv_nsec - next_interval.tv_nsec;
        !           614:        n /= options.obscure_keystroke_timing_interval * 1000 * 1000;
        !           615:        n = (n < 0) ? 1 : n + 1;
        !           616:
        !           617:        /* Advance to the next interval */
        !           618:        ms_to_timespec(&tmp, options.obscure_keystroke_timing_interval * n);
        !           619:        timespecadd(&now, &tmp, &next_interval);
        !           620:        return 1;
        !           621: }
        !           622:
1.13      markus    623: /*
                    624:  * Waits until the client can do something (some data becomes available on
                    625:  * one of the file descriptors).
                    626:  */
1.77      itojun    627: static void
1.374     djm       628: client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
                    629:     u_int *npfd_allocp, u_int *npfd_activep, int rekeying,
                    630:     int *conn_in_readyp, int *conn_out_readyp)
1.11      markus    631: {
1.386     djm       632:        struct timespec timeout;
1.393   ! djm       633:        int ret, oready;
1.374     djm       634:        u_int p;
1.117     markus    635:
1.374     djm       636:        *conn_in_readyp = *conn_out_readyp = 0;
1.11      markus    637:
1.374     djm       638:        /* Prepare channel poll. First two pollfd entries are reserved */
1.386     djm       639:        ptimeout_init(&timeout);
                    640:        channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
1.374     djm       641:        if (*npfd_activep < 2)
                    642:                fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
                    643:
                    644:        /* channel_prepare_poll could have closed the last channel */
1.303     djm       645:        if (session_closed && !channel_still_open(ssh) &&
1.320     djm       646:            !ssh_packet_have_data_to_write(ssh)) {
1.374     djm       647:                /* clear events since we did not call poll() */
                    648:                for (p = 0; p < *npfd_activep; p++)
                    649:                        (*pfdp)[p].revents = 0;
1.292     djm       650:                return;
1.16      markus    651:        }
1.11      markus    652:
1.393   ! djm       653:        oready = obfuscate_keystroke_timing(ssh, &timeout);
        !           654:
1.374     djm       655:        /* Monitor server connection on reserved pollfd entries */
                    656:        (*pfdp)[0].fd = connection_in;
                    657:        (*pfdp)[0].events = POLLIN;
                    658:        (*pfdp)[1].fd = connection_out;
1.393   ! djm       659:        (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
        !           660:            POLLOUT : 0;
1.11      markus    661:
1.13      markus    662:        /*
                    663:         * Wait for something to happen.  This will suspend the process until
1.374     djm       664:         * some polled descriptor can be read, written, or has some other
1.222     djm       665:         * event pending, or a timeout expires.
1.13      markus    666:         */
1.386     djm       667:        set_control_persist_exit_time(ssh);
                    668:        if (control_persist_exit_time > 0)
                    669:                ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
1.345     dtucker   670:        if (options.server_alive_interval > 0)
1.386     djm       671:                ptimeout_deadline_monotime(&timeout, server_alive_time);
                    672:        if (options.rekey_interval > 0 && !rekeying) {
                    673:                ptimeout_deadline_sec(&timeout,
1.320     djm       674:                    ssh_packet_get_rekey_timeout(ssh));
1.386     djm       675:        }
1.374     djm       676:
1.393   ! djm       677:        ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), NULL);
1.222     djm       678:
1.326     deraadt   679:        if (ret == -1) {
1.51      markus    680:                /*
1.374     djm       681:                 * We have to clear the events because we return.
1.51      markus    682:                 * We have to return, because the mainloop checks for the flags
                    683:                 * set by the signal handlers.
                    684:                 */
1.374     djm       685:                for (p = 0; p < *npfd_activep; p++)
                    686:                        (*pfdp)[p].revents = 0;
1.11      markus    687:                if (errno == EINTR)
                    688:                        return;
                    689:                /* Note: we might still have data in the buffers. */
1.377     djm       690:                quit_message("poll: %s", strerror(errno));
1.374     djm       691:                return;
                    692:        }
                    693:
                    694:        *conn_in_readyp = (*pfdp)[0].revents != 0;
                    695:        *conn_out_readyp = (*pfdp)[1].revents != 0;
                    696:
                    697:        if (options.server_alive_interval > 0 && !*conn_in_readyp &&
                    698:            monotime() >= server_alive_time) {
1.249     dtucker   699:                /*
1.374     djm       700:                 * ServerAlive check is needed. We can't rely on the poll
1.345     dtucker   701:                 * timing out since traffic on the client side such as port
                    702:                 * forwards can keep waking it up.
1.249     dtucker   703:                 */
1.345     dtucker   704:                server_alive_check(ssh);
1.374     djm       705:        }
1.11      markus    706: }
                    707:
1.77      itojun    708: static void
1.315     markus    709: client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
1.1       deraadt   710: {
1.11      markus    711:        /* Flush stdout and stderr buffers. */
1.315     markus    712:        if (sshbuf_len(bout) > 0)
                    713:                atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
                    714:                    sshbuf_len(bout));
                    715:        if (sshbuf_len(berr) > 0)
                    716:                atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
                    717:                    sshbuf_len(berr));
1.11      markus    718:
1.233     djm       719:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    720:
1.305     djm       721:        sshbuf_reset(bin);
                    722:        sshbuf_reset(bout);
                    723:        sshbuf_reset(berr);
1.11      markus    724:
                    725:        /* Send the suspend signal to the program itself. */
                    726:        kill(getpid(), SIGTSTP);
                    727:
1.132     djm       728:        /* Reset window sizes in case they have changed */
                    729:        received_window_change_signal = 1;
1.11      markus    730:
1.233     djm       731:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    732: }
                    733:
1.77      itojun    734: static void
1.374     djm       735: client_process_net_input(struct ssh *ssh)
1.11      markus    736: {
1.378     djm       737:        int r;
1.11      markus    738:
1.13      markus    739:        /*
                    740:         * Read input from the server, and add any such data to the buffer of
                    741:         * the packet subsystem.
                    742:         */
1.374     djm       743:        schedule_server_alive_check();
1.378     djm       744:        if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
                    745:                return; /* success */
                    746:        if (r == SSH_ERR_SYSTEM_ERROR) {
                    747:                if (errno == EAGAIN || errno == EINTR)
                    748:                        return;
                    749:                if (errno == EPIPE) {
                    750:                        quit_message("Connection to %s closed by remote host.",
                    751:                            host);
                    752:                        return;
                    753:                }
1.11      markus    754:        }
1.378     djm       755:        quit_message("Read from remote host %s: %s", host, ssh_err(r));
1.17      markus    756: }
1.16      markus    757:
1.97      jakob     758: static void
1.303     djm       759: client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
1.123     djm       760: {
1.190     djm       761:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    762:        char errmsg[256];
1.315     markus    763:        int r, tochan;
1.190     djm       764:
1.234     djm       765:        /*
                    766:         * If a TTY was explicitly requested, then a failure to allocate
                    767:         * one is fatal.
                    768:         */
                    769:        if (cr->action == CONFIRM_TTY &&
                    770:            (options.request_tty == REQUEST_TTY_FORCE ||
                    771:            options.request_tty == REQUEST_TTY_YES))
                    772:                cr->action = CONFIRM_CLOSE;
                    773:
1.312     djm       774:        /* XXX suppress on mux _client_ quietmode */
1.190     djm       775:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       776:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       777:
                    778:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    779:                debug2("%s request accepted on channel %d",
                    780:                    cr->request_type, c->self);
                    781:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    782:                if (tochan) {
                    783:                        snprintf(errmsg, sizeof(errmsg),
                    784:                            "%s request failed\r\n", cr->request_type);
                    785:                } else {
                    786:                        snprintf(errmsg, sizeof(errmsg),
                    787:                            "%s request failed on channel %d",
                    788:                            cr->request_type, c->self);
                    789:                }
                    790:                /* If error occurred on primary session channel, then exit */
1.234     djm       791:                if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190     djm       792:                        fatal("%s", errmsg);
1.234     djm       793:                /*
                    794:                 * If error occurred on mux client, append to
                    795:                 * their stderr.
                    796:                 */
                    797:                if (tochan) {
1.360     djm       798:                        debug3_f("channel %d: mux request: %s", c->self,
                    799:                            cr->request_type);
1.315     markus    800:                        if ((r = sshbuf_put(c->extended, errmsg,
                    801:                            strlen(errmsg))) != 0)
1.354     djm       802:                                fatal_fr(r, "sshbuf_put");
1.234     djm       803:                } else
1.190     djm       804:                        error("%s", errmsg);
1.234     djm       805:                if (cr->action == CONFIRM_TTY) {
                    806:                        /*
                    807:                         * If a TTY allocation error occurred, then arrange
                    808:                         * for the correct TTY to leave raw mode.
                    809:                         */
                    810:                        if (c->self == session_ident)
                    811:                                leave_raw_mode(0);
                    812:                        else
1.303     djm       813:                                mux_tty_alloc_failed(ssh, c);
1.234     djm       814:                } else if (cr->action == CONFIRM_CLOSE) {
1.303     djm       815:                        chan_read_failed(ssh, c);
                    816:                        chan_write_failed(ssh, c);
1.190     djm       817:                }
                    818:        }
1.250     djm       819:        free(cr);
1.190     djm       820: }
                    821:
                    822: static void
1.303     djm       823: client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
1.190     djm       824: {
1.250     djm       825:        free(ctx);
1.190     djm       826: }
1.129     deraadt   827:
1.236     djm       828: void
1.303     djm       829: client_expect_confirm(struct ssh *ssh, int id, const char *request,
1.234     djm       830:     enum confirm_action action)
1.190     djm       831: {
1.255     djm       832:        struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123     djm       833:
1.190     djm       834:        cr->request_type = request;
1.234     djm       835:        cr->action = action;
1.123     djm       836:
1.303     djm       837:        channel_register_status_confirm(ssh, id, client_status_confirm,
1.190     djm       838:            client_abandon_status_confirm, cr);
1.196     djm       839: }
                    840:
                    841: void
                    842: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    843: {
1.201     djm       844:        struct global_confirm *gc, *last_gc;
1.196     djm       845:
                    846:        /* Coalesce identical callbacks */
1.201     djm       847:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    848:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    849:                if (++last_gc->ref_count >= INT_MAX)
1.354     djm       850:                        fatal_f("last_gc->ref_count = %d",
                    851:                            last_gc->ref_count);
1.196     djm       852:                return;
                    853:        }
                    854:
1.255     djm       855:        gc = xcalloc(1, sizeof(*gc));
1.196     djm       856:        gc->cb = cb;
                    857:        gc->ctx = ctx;
                    858:        gc->ref_count = 1;
                    859:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       860: }
                    861:
1.384     djm       862: /*
                    863:  * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
                    864:  * hostkey update request.
                    865:  */
                    866: static int
                    867: can_update_hostkeys(void)
                    868: {
                    869:        if (hostkeys_update_complete)
                    870:                return 0;
                    871:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
                    872:            options.batch_mode)
                    873:                return 0; /* won't ask in batchmode, so don't even try */
                    874:        if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
                    875:                return 0;
                    876:        return 1;
                    877: }
                    878:
1.385     dtucker   879: static void
                    880: client_repledge(void)
1.384     djm       881: {
                    882:        debug3_f("enter");
                    883:
                    884:        /* Might be able to tighten pledge now that session is established */
                    885:        if (options.control_master || options.control_path != NULL ||
                    886:            options.forward_x11 || options.fork_after_authentication ||
                    887:            can_update_hostkeys() ||
                    888:            (session_ident != -1 && !session_setup_complete)) {
                    889:                /* Can't tighten */
                    890:                return;
                    891:        }
                    892:        /*
                    893:         * LocalCommand and UpdateHostkeys have finished, so can get rid of
                    894:         * filesystem.
                    895:         *
                    896:         * XXX protocol allows a server can to change hostkeys during the
                    897:         *     connection at rekey time that could trigger a hostkeys update
                    898:         *     but AFAIK no implementations support this. Could improve by
                    899:         *     forcing known_hosts to be read-only or via unveil(2).
                    900:         */
                    901:        if (options.num_local_forwards != 0 ||
                    902:            options.num_remote_forwards != 0 ||
                    903:            options.num_permitted_remote_opens != 0 ||
                    904:            options.enable_escape_commandline != 0) {
                    905:                /* rfwd needs inet */
                    906:                debug("pledge: network");
                    907:                if (pledge("stdio unix inet dns proc tty", NULL) == -1)
                    908:                        fatal_f("pledge(): %s", strerror(errno));
                    909:        } else if (options.forward_agent != 0) {
                    910:                /* agent forwarding needs to open $SSH_AUTH_SOCK at will */
                    911:                debug("pledge: agent");
                    912:                if (pledge("stdio unix proc tty", NULL) == -1)
                    913:                        fatal_f("pledge(): %s", strerror(errno));
                    914:        } else {
                    915:                debug("pledge: fork");
                    916:                if (pledge("stdio proc tty", NULL) == -1)
                    917:                        fatal_f("pledge(): %s", strerror(errno));
                    918:        }
                    919:        /* XXX further things to do:
                    920:         *
                    921:         * - might be able to get rid of proc if we kill ~^Z
                    922:         * - ssh -N (no session)
                    923:         * - stdio forwarding
                    924:         * - sessions without tty
                    925:         */
                    926: }
                    927:
1.123     djm       928: static void
1.303     djm       929: process_cmdline(struct ssh *ssh)
1.97      jakob     930: {
                    931:        void (*handler)(int);
1.261     millert   932:        char *s, *cmd;
                    933:        int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
                    934:        struct Forward fwd;
1.97      jakob     935:
1.257     tedu      936:        memset(&fwd, 0, sizeof(fwd));
1.183     djm       937:
1.233     djm       938:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.332     dtucker   939:        handler = ssh_signal(SIGINT, SIG_IGN);
1.99      markus    940:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     941:        if (s == NULL)
                    942:                goto out;
1.256     deraadt   943:        while (isspace((u_char)*s))
1.97      jakob     944:                s++;
1.121     djm       945:        if (*s == '-')
                    946:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   947:        if (*s == '\0')
1.97      jakob     948:                goto out;
1.121     djm       949:
1.122     djm       950:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       951:                logit("Commands:");
1.164     djm       952:                logit("      -L[bind_address:]port:host:hostport    "
                    953:                    "Request local forward");
                    954:                logit("      -R[bind_address:]port:host:hostport    "
                    955:                    "Request remote forward");
1.204     stevesk   956:                logit("      -D[bind_address:]port                  "
                    957:                    "Request dynamic forward");
1.237     markus    958:                logit("      -KL[bind_address:]port                 "
                    959:                    "Cancel local forward");
1.165     stevesk   960:                logit("      -KR[bind_address:]port                 "
1.164     djm       961:                    "Cancel remote forward");
1.237     markus    962:                logit("      -KD[bind_address:]port                 "
                    963:                    "Cancel dynamic forward");
1.146     reyk      964:                if (!options.permit_local_command)
                    965:                        goto out;
1.164     djm       966:                logit("      !args                                  "
                    967:                    "Execute local command");
1.146     reyk      968:                goto out;
                    969:        }
                    970:
                    971:        if (*s == '!' && options.permit_local_command) {
                    972:                s++;
                    973:                ssh_local_cmd(s);
1.121     djm       974:                goto out;
                    975:        }
                    976:
                    977:        if (*s == 'K') {
                    978:                delete = 1;
                    979:                s++;
                    980:        }
1.204     stevesk   981:        if (*s == 'L')
                    982:                local = 1;
                    983:        else if (*s == 'R')
                    984:                remote = 1;
                    985:        else if (*s == 'D')
                    986:                dynamic = 1;
                    987:        else {
1.109     itojun    988:                logit("Invalid command.");
1.97      jakob     989:                goto out;
                    990:        }
1.204     stevesk   991:
1.256     deraadt   992:        while (isspace((u_char)*++s))
1.179     tedu      993:                ;
1.97      jakob     994:
1.217     djm       995:        /* XXX update list of forwards in options */
1.121     djm       996:        if (delete) {
1.261     millert   997:                /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
                    998:                if (!parse_forward(&fwd, s, 1, 0)) {
                    999:                        logit("Bad forwarding close specification.");
1.121     djm      1000:                        goto out;
                   1001:                }
1.237     markus   1002:                if (remote)
1.303     djm      1003:                        ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1.237     markus   1004:                else if (dynamic)
1.303     djm      1005:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert  1006:                            0, &options.fwd_opts) > 0;
1.237     markus   1007:                else
1.303     djm      1008:                        ok = channel_cancel_lport_listener(ssh, &fwd,
1.261     millert  1009:                            CHANNEL_CANCEL_PORT_STATIC,
                   1010:                            &options.fwd_opts) > 0;
1.237     markus   1011:                if (!ok) {
1.290     dtucker  1012:                        logit("Unknown port forwarding.");
1.237     markus   1013:                        goto out;
                   1014:                }
                   1015:                logit("Canceled forwarding.");
1.121     djm      1016:        } else {
1.382     dtucker  1017:                /* -R specs can be both dynamic or not, so check both. */
                   1018:                if (remote) {
                   1019:                        if (!parse_forward(&fwd, s, 0, remote) &&
                   1020:                            !parse_forward(&fwd, s, 1, remote)) {
                   1021:                                logit("Bad remote forwarding specification.");
                   1022:                                goto out;
                   1023:                        }
                   1024:                } else if (!parse_forward(&fwd, s, dynamic, remote)) {
                   1025:                        logit("Bad local forwarding specification.");
1.121     djm      1026:                        goto out;
                   1027:                }
1.204     stevesk  1028:                if (local || dynamic) {
1.303     djm      1029:                        if (!channel_setup_local_fwd_listener(ssh, &fwd,
1.261     millert  1030:                            &options.fwd_opts)) {
1.121     djm      1031:                                logit("Port forwarding failed.");
                   1032:                                goto out;
                   1033:                        }
1.135     djm      1034:                } else {
1.303     djm      1035:                        if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1.167     markus   1036:                                logit("Port forwarding failed.");
                   1037:                                goto out;
                   1038:                        }
1.135     djm      1039:                }
1.121     djm      1040:                logit("Forwarding port.");
                   1041:        }
                   1042:
1.97      jakob    1043: out:
1.332     dtucker  1044:        ssh_signal(SIGINT, handler);
1.233     djm      1045:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250     djm      1046:        free(cmd);
                   1047:        free(fwd.listen_host);
1.261     millert  1048:        free(fwd.listen_path);
1.250     djm      1049:        free(fwd.connect_host);
1.261     millert  1050:        free(fwd.connect_path);
1.97      jakob    1051: }
                   1052:
1.244     dtucker  1053: /* reasons to suppress output of an escape command in help output */
                   1054: #define SUPPRESS_NEVER         0       /* never suppress, always show */
1.292     djm      1055: #define SUPPRESS_MUXCLIENT     1       /* don't show in mux client sessions */
                   1056: #define SUPPRESS_MUXMASTER     2       /* don't show in mux master sessions */
                   1057: #define SUPPRESS_SYSLOG                4       /* don't show when logging to syslog */
1.383     djm      1058: #define SUPPRESS_NOCMDLINE     8       /* don't show when cmdline disabled*/
1.244     dtucker  1059: struct escape_help_text {
                   1060:        const char *cmd;
                   1061:        const char *text;
                   1062:        unsigned int flags;
                   1063: };
                   1064: static struct escape_help_text esc_txt[] = {
                   1065:     {".",  "terminate session", SUPPRESS_MUXMASTER},
                   1066:     {".",  "terminate connection (and any multiplexed sessions)",
                   1067:        SUPPRESS_MUXCLIENT},
1.292     djm      1068:     {"B",  "send a BREAK to the remote system", SUPPRESS_NEVER},
1.383     djm      1069:     {"C",  "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1.292     djm      1070:     {"R",  "request rekey", SUPPRESS_NEVER},
1.246     dtucker  1071:     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244     dtucker  1072:     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
                   1073:     {"#",  "list forwarded connections", SUPPRESS_NEVER},
                   1074:     {"&",  "background ssh (when waiting for connections to terminate)",
                   1075:        SUPPRESS_MUXCLIENT},
                   1076:     {"?", "this message", SUPPRESS_NEVER},
                   1077: };
                   1078:
                   1079: static void
1.315     markus   1080: print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
                   1081:     int using_stderr)
1.244     dtucker  1082: {
                   1083:        unsigned int i, suppress_flags;
1.315     markus   1084:        int r;
1.244     dtucker  1085:
1.315     markus   1086:        if ((r = sshbuf_putf(b,
                   1087:            "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
1.354     djm      1088:                fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1089:
1.292     djm      1090:        suppress_flags =
1.244     dtucker  1091:            (mux_client ? SUPPRESS_MUXCLIENT : 0) |
                   1092:            (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1.383     djm      1093:            (using_stderr ? 0 : SUPPRESS_SYSLOG) |
                   1094:            (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
1.244     dtucker  1095:
                   1096:        for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
                   1097:                if (esc_txt[i].flags & suppress_flags)
                   1098:                        continue;
1.315     markus   1099:                if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
                   1100:                    escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
1.354     djm      1101:                        fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1102:        }
                   1103:
1.315     markus   1104:        if ((r = sshbuf_putf(b,
1.246     dtucker  1105:            " %c%c   - send the escape character by typing it twice\r\n"
1.244     dtucker  1106:            "(Note that escapes are only recognized immediately after "
1.315     markus   1107:            "newline.)\r\n", escape_char, escape_char)) != 0)
1.354     djm      1108:                fatal_fr(r, "sshbuf_putf");
1.244     dtucker  1109: }
                   1110:
1.314     djm      1111: /*
1.296     naddy    1112:  * Process the characters one by one.
1.195     djm      1113:  */
1.77      itojun   1114: static int
1.303     djm      1115: process_escapes(struct ssh *ssh, Channel *c,
1.315     markus   1116:     struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1.195     djm      1117:     char *buf, int len)
1.31      markus   1118: {
                   1119:        pid_t pid;
1.315     markus   1120:        int r, bytes = 0;
1.42      markus   1121:        u_int i;
                   1122:        u_char ch;
1.31      markus   1123:        char *s;
1.392     dtucker  1124:        struct escape_filter_ctx *efc;
1.31      markus   1125:
1.392     dtucker  1126:        if (c == NULL || c->filter_ctx == NULL || len <= 0)
1.294     djm      1127:                return 0;
1.314     djm      1128:
1.392     dtucker  1129:        efc = (struct escape_filter_ctx *)c->filter_ctx;
1.139     djm      1130:
                   1131:        for (i = 0; i < (u_int)len; i++) {
1.31      markus   1132:                /* Get one character at a time. */
                   1133:                ch = buf[i];
                   1134:
1.294     djm      1135:                if (efc->escape_pending) {
1.31      markus   1136:                        /* We have previously seen an escape character. */
                   1137:                        /* Clear the flag now. */
1.294     djm      1138:                        efc->escape_pending = 0;
1.31      markus   1139:
                   1140:                        /* Process the escaped character. */
                   1141:                        switch (ch) {
                   1142:                        case '.':
                   1143:                                /* Terminate the connection. */
1.315     markus   1144:                                if ((r = sshbuf_putf(berr, "%c.\r\n",
                   1145:                                    efc->escape_char)) != 0)
1.354     djm      1146:                                        fatal_fr(r, "sshbuf_putf");
1.217     djm      1147:                                if (c && c->ctl_chan != -1) {
1.387     djm      1148:                                        channel_force_close(ssh, c, 1);
1.195     djm      1149:                                        return 0;
                   1150:                                } else
                   1151:                                        quit_pending = 1;
1.31      markus   1152:                                return -1;
                   1153:
                   1154:                        case 'Z' - 64:
1.195     djm      1155:                                /* XXX support this for mux clients */
1.217     djm      1156:                                if (c && c->ctl_chan != -1) {
1.245     dtucker  1157:                                        char b[16];
1.195     djm      1158:  noescape:
1.245     dtucker  1159:                                        if (ch == 'Z' - 64)
                   1160:                                                snprintf(b, sizeof b, "^Z");
                   1161:                                        else
                   1162:                                                snprintf(b, sizeof b, "%c", ch);
1.315     markus   1163:                                        if ((r = sshbuf_putf(berr,
1.245     dtucker  1164:                                            "%c%s escape not available to "
1.195     djm      1165:                                            "multiplexed sessions\r\n",
1.315     markus   1166:                                            efc->escape_char, b)) != 0)
1.354     djm      1167:                                                fatal_fr(r, "sshbuf_putf");
1.195     djm      1168:                                        continue;
                   1169:                                }
1.197     djm      1170:                                /* Suspend the program. Inform the user */
1.315     markus   1171:                                if ((r = sshbuf_putf(berr,
                   1172:                                    "%c^Z [suspend ssh]\r\n",
                   1173:                                    efc->escape_char)) != 0)
1.354     djm      1174:                                        fatal_fr(r, "sshbuf_putf");
1.31      markus   1175:
                   1176:                                /* Restore terminal modes and suspend. */
                   1177:                                client_suspend_self(bin, bout, berr);
                   1178:
                   1179:                                /* We have been continued. */
                   1180:                                continue;
                   1181:
1.111     markus   1182:                        case 'B':
1.315     markus   1183:                                if ((r = sshbuf_putf(berr,
                   1184:                                    "%cB\r\n", efc->escape_char)) != 0)
1.354     djm      1185:                                        fatal_fr(r, "sshbuf_putf");
1.303     djm      1186:                                channel_request_start(ssh, c->self, "break", 0);
1.315     markus   1187:                                if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
                   1188:                                    (r = sshpkt_send(ssh)) != 0)
1.354     djm      1189:                                        fatal_fr(r, "send packet");
1.111     markus   1190:                                continue;
                   1191:
1.54      markus   1192:                        case 'R':
1.357     djm      1193:                                if (ssh->compat & SSH_BUG_NOREKEY)
1.292     djm      1194:                                        logit("Server does not "
                   1195:                                            "support re-keying");
                   1196:                                else
                   1197:                                        need_rekeying = 1;
1.54      markus   1198:                                continue;
                   1199:
1.242     dtucker  1200:                        case 'V':
                   1201:                                /* FALLTHROUGH */
                   1202:                        case 'v':
                   1203:                                if (c && c->ctl_chan != -1)
                   1204:                                        goto noescape;
                   1205:                                if (!log_is_on_stderr()) {
1.315     markus   1206:                                        if ((r = sshbuf_putf(berr,
1.242     dtucker  1207:                                            "%c%c [Logging to syslog]\r\n",
1.315     markus   1208:                                            efc->escape_char, ch)) != 0)
1.354     djm      1209:                                                fatal_fr(r, "sshbuf_putf");
1.242     dtucker  1210:                                        continue;
                   1211:                                }
                   1212:                                if (ch == 'V' && options.log_level >
                   1213:                                    SYSLOG_LEVEL_QUIET)
                   1214:                                        log_change_level(--options.log_level);
                   1215:                                if (ch == 'v' && options.log_level <
                   1216:                                    SYSLOG_LEVEL_DEBUG3)
                   1217:                                        log_change_level(++options.log_level);
1.315     markus   1218:                                if ((r = sshbuf_putf(berr,
1.294     djm      1219:                                    "%c%c [LogLevel %s]\r\n",
                   1220:                                    efc->escape_char, ch,
1.315     markus   1221:                                    log_level_name(options.log_level))) != 0)
1.354     djm      1222:                                        fatal_fr(r, "sshbuf_putf");
1.242     dtucker  1223:                                continue;
                   1224:
1.31      markus   1225:                        case '&':
1.392     dtucker  1226:                                if (c->ctl_chan != -1)
1.195     djm      1227:                                        goto noescape;
1.31      markus   1228:                                /*
1.197     djm      1229:                                 * Detach the program (continue to serve
                   1230:                                 * connections, but put in background and no
                   1231:                                 * more new connections).
1.31      markus   1232:                                 */
                   1233:                                /* Restore tty modes. */
1.233     djm      1234:                                leave_raw_mode(
                   1235:                                    options.request_tty == REQUEST_TTY_FORCE);
1.31      markus   1236:
                   1237:                                /* Stop listening for new connections. */
1.303     djm      1238:                                channel_stop_listening(ssh);
1.31      markus   1239:
1.354     djm      1240:                                if ((r = sshbuf_putf(berr, "%c& "
                   1241:                                    "[backgrounded]\n", efc->escape_char)) != 0)
                   1242:                                        fatal_fr(r, "sshbuf_putf");
1.31      markus   1243:
                   1244:                                /* Fork into background. */
                   1245:                                pid = fork();
1.326     deraadt  1246:                                if (pid == -1) {
1.31      markus   1247:                                        error("fork: %.100s", strerror(errno));
                   1248:                                        continue;
                   1249:                                }
                   1250:                                if (pid != 0) { /* This is the parent. */
                   1251:                                        /* The parent just exits. */
                   1252:                                        exit(0);
                   1253:                                }
                   1254:                                /* The child continues serving connections. */
1.292     djm      1255:                                /* fake EOF on stdin */
1.315     markus   1256:                                if ((r = sshbuf_put_u8(bin, 4)) != 0)
1.354     djm      1257:                                        fatal_fr(r, "sshbuf_put_u8");
1.292     djm      1258:                                return -1;
1.31      markus   1259:                        case '?':
1.294     djm      1260:                                print_escape_help(berr, efc->escape_char,
1.244     dtucker  1261:                                    (c && c->ctl_chan != -1),
                   1262:                                    log_is_on_stderr());
1.31      markus   1263:                                continue;
                   1264:
                   1265:                        case '#':
1.315     markus   1266:                                if ((r = sshbuf_putf(berr, "%c#\r\n",
                   1267:                                    efc->escape_char)) != 0)
1.354     djm      1268:                                        fatal_fr(r, "sshbuf_putf");
1.303     djm      1269:                                s = channel_open_message(ssh);
1.315     markus   1270:                                if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1.354     djm      1271:                                        fatal_fr(r, "sshbuf_put");
1.250     djm      1272:                                free(s);
1.97      jakob    1273:                                continue;
                   1274:
                   1275:                        case 'C':
1.217     djm      1276:                                if (c && c->ctl_chan != -1)
1.206     djm      1277:                                        goto noescape;
1.383     djm      1278:                                if (options.enable_escape_commandline == 0) {
                   1279:                                        if ((r = sshbuf_putf(berr,
                   1280:                                            "commandline disabled\r\n")) != 0)
                   1281:                                                fatal_fr(r, "sshbuf_putf");
                   1282:                                        continue;
                   1283:                                }
1.303     djm      1284:                                process_cmdline(ssh);
1.31      markus   1285:                                continue;
                   1286:
                   1287:                        default:
1.294     djm      1288:                                if (ch != efc->escape_char) {
1.315     markus   1289:                                        if ((r = sshbuf_put_u8(bin,
                   1290:                                            efc->escape_char)) != 0)
1.354     djm      1291:                                                fatal_fr(r, "sshbuf_put_u8");
1.31      markus   1292:                                        bytes++;
                   1293:                                }
                   1294:                                /* Escaped characters fall through here */
                   1295:                                break;
                   1296:                        }
                   1297:                } else {
                   1298:                        /*
1.197     djm      1299:                         * The previous character was not an escape char.
                   1300:                         * Check if this is an escape.
1.31      markus   1301:                         */
1.294     djm      1302:                        if (last_was_cr && ch == efc->escape_char) {
1.197     djm      1303:                                /*
                   1304:                                 * It is. Set the flag and continue to
                   1305:                                 * next character.
                   1306:                                 */
1.294     djm      1307:                                efc->escape_pending = 1;
1.31      markus   1308:                                continue;
                   1309:                        }
                   1310:                }
                   1311:
                   1312:                /*
                   1313:                 * Normal character.  Record whether it was a newline,
                   1314:                 * and append it to the buffer.
                   1315:                 */
                   1316:                last_was_cr = (ch == '\r' || ch == '\n');
1.315     markus   1317:                if ((r = sshbuf_put_u8(bin, ch)) != 0)
1.354     djm      1318:                        fatal_fr(r, "sshbuf_put_u8");
1.31      markus   1319:                bytes++;
                   1320:        }
                   1321:        return bytes;
                   1322: }
                   1323:
1.13      markus   1324: /*
1.15      markus   1325:  * Get packets from the connection input buffer, and process them as long as
                   1326:  * there are packets available.
                   1327:  *
                   1328:  * Any unknown packets received during the actual
                   1329:  * session cause the session to terminate.  This is
                   1330:  * intended to make debugging easier since no
                   1331:  * confirmations are sent.  Any compatible protocol
                   1332:  * extensions must be negotiated during the
                   1333:  * preparatory phase.
                   1334:  */
                   1335:
1.77      itojun   1336: static void
1.321     djm      1337: client_process_buffered_input_packets(struct ssh *ssh)
1.15      markus   1338: {
1.321     djm      1339:        ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1.15      markus   1340: }
                   1341:
1.31      markus   1342: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1343:
1.195     djm      1344: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1345: void *
                   1346: client_new_escape_filter_ctx(int escape_char)
                   1347: {
                   1348:        struct escape_filter_ctx *ret;
                   1349:
1.255     djm      1350:        ret = xcalloc(1, sizeof(*ret));
1.195     djm      1351:        ret->escape_pending = 0;
                   1352:        ret->escape_char = escape_char;
                   1353:        return (void *)ret;
                   1354: }
                   1355:
1.198     djm      1356: /* Free the escape filter context on channel free */
                   1357: void
1.303     djm      1358: client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1.198     djm      1359: {
1.250     djm      1360:        free(ctx);
1.198     djm      1361: }
                   1362:
1.195     djm      1363: int
1.303     djm      1364: client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1.30      markus   1365: {
1.190     djm      1366:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1367:                return 0;
                   1368:
1.303     djm      1369:        return process_escapes(ssh, c, c->input, c->output, c->extended,
1.195     djm      1370:            buf, len);
1.30      markus   1371: }
                   1372:
1.77      itojun   1373: static void
1.387     djm      1374: client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
1.60      markus   1375: {
1.303     djm      1376:        channel_cancel_cleanup(ssh, id);
1.60      markus   1377:        session_closed = 1;
1.233     djm      1378:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60      markus   1379: }
                   1380:
1.15      markus   1381: /*
1.13      markus   1382:  * Implements the interactive session with the server.  This is called after
                   1383:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1384:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1385:  * used as an escape character for terminating or suspending the session.
1.13      markus   1386:  */
1.20      markus   1387: int
1.303     djm      1388: client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
                   1389:     int ssh2_chan_id)
1.1       deraadt  1390: {
1.374     djm      1391:        struct pollfd *pfd = NULL;
                   1392:        u_int npfd_alloc = 0, npfd_active = 0;
1.11      markus   1393:        double start_time, total_time;
1.374     djm      1394:        int r, len;
1.200     markus   1395:        u_int64_t ibytes, obytes;
1.374     djm      1396:        int conn_in_ready, conn_out_ready;
1.11      markus   1397:
                   1398:        debug("Entering interactive session.");
1.384     djm      1399:        session_ident = ssh2_chan_id;
1.277     semarie  1400:
1.278     semarie  1401:        if (options.control_master &&
1.286     djm      1402:            !option_clear_or_none(options.control_path)) {
1.278     semarie  1403:                debug("pledge: id");
1.327     mestre   1404:                if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1.278     semarie  1405:                    NULL) == -1)
1.354     djm      1406:                        fatal_f("pledge(): %s", strerror(errno));
1.278     semarie  1407:
                   1408:        } else if (options.forward_x11 || options.permit_local_command) {
1.277     semarie  1409:                debug("pledge: exec");
                   1410:                if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
                   1411:                    NULL) == -1)
1.354     djm      1412:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1413:
                   1414:        } else if (options.update_hostkeys) {
1.373     jsg      1415:                debug("pledge: filesystem");
1.277     semarie  1416:                if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
                   1417:                    NULL) == -1)
1.354     djm      1418:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1419:
1.286     djm      1420:        } else if (!option_clear_or_none(options.proxy_command) ||
1.369     djm      1421:            options.fork_after_authentication) {
1.277     semarie  1422:                debug("pledge: proc");
                   1423:                if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1.354     djm      1424:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1425:
                   1426:        } else {
                   1427:                debug("pledge: network");
1.300     mestre   1428:                if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1.354     djm      1429:                        fatal_f("pledge(): %s", strerror(errno));
1.277     semarie  1430:        }
1.11      markus   1431:
1.384     djm      1432:        /* might be able to tighten now */
                   1433:        client_repledge();
                   1434:
1.307     dtucker  1435:        start_time = monotime_double();
1.11      markus   1436:
                   1437:        /* Initialize variables. */
                   1438:        last_was_cr = 1;
                   1439:        exit_status = -1;
1.320     djm      1440:        connection_in = ssh_packet_get_connection_in(ssh);
                   1441:        connection_out = ssh_packet_get_connection_out(ssh);
1.46      markus   1442:
1.11      markus   1443:        quit_pending = 0;
                   1444:
1.315     markus   1445:        /* Initialize buffer. */
                   1446:        if ((stderr_buffer = sshbuf_new()) == NULL)
1.354     djm      1447:                fatal_f("sshbuf_new failed");
1.11      markus   1448:
1.321     djm      1449:        client_init_dispatch(ssh);
1.15      markus   1450:
1.105     markus   1451:        /*
                   1452:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1453:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1454:         */
1.332     dtucker  1455:        if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1456:                ssh_signal(SIGHUP, signal_handler);
                   1457:        if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1458:                ssh_signal(SIGINT, signal_handler);
                   1459:        if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1460:                ssh_signal(SIGQUIT, signal_handler);
                   1461:        if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1462:                ssh_signal(SIGTERM, signal_handler);
                   1463:        ssh_signal(SIGWINCH, window_change_handler);
1.11      markus   1464:
                   1465:        if (have_pty)
1.233     djm      1466:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus   1467:
1.292     djm      1468:        if (session_ident != -1) {
                   1469:                if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1.303     djm      1470:                        channel_register_filter(ssh, session_ident,
1.292     djm      1471:                            client_simple_escape_filter, NULL,
                   1472:                            client_filter_cleanup,
                   1473:                            client_new_escape_filter_ctx(
                   1474:                            escape_char_arg));
1.232     djm      1475:                }
1.303     djm      1476:                channel_register_cleanup(ssh, session_ident,
1.292     djm      1477:                    client_channel_closed, 0);
1.48      markus   1478:        }
1.345     dtucker  1479:
                   1480:        schedule_server_alive_check();
1.30      markus   1481:
1.11      markus   1482:        /* Main loop of the client for the interactive session mode. */
                   1483:        while (!quit_pending) {
                   1484:
1.13      markus   1485:                /* Process buffered packets sent by the server. */
1.321     djm      1486:                client_process_buffered_input_packets(ssh);
1.11      markus   1487:
1.303     djm      1488:                if (session_closed && !channel_still_open(ssh))
1.60      markus   1489:                        break;
                   1490:
1.303     djm      1491:                if (ssh_packet_is_rekeying(ssh)) {
1.56      markus   1492:                        debug("rekeying in progress");
1.284     djm      1493:                } else if (need_rekeying) {
                   1494:                        /* manual rekey request */
                   1495:                        debug("need rekeying");
1.303     djm      1496:                        if ((r = kex_start_rekex(ssh)) != 0)
1.354     djm      1497:                                fatal_fr(r, "kex_start_rekex");
1.284     djm      1498:                        need_rekeying = 0;
1.56      markus   1499:                } else {
                   1500:                        /*
                   1501:                         * Make packets from buffered channel data, and
                   1502:                         * enqueue them for sending to the server.
                   1503:                         */
1.320     djm      1504:                        if (ssh_packet_not_very_much_data_to_write(ssh))
1.303     djm      1505:                                channel_output_poll(ssh);
1.11      markus   1506:
1.56      markus   1507:                        /*
                   1508:                         * Check if the window size has changed, and buffer a
                   1509:                         * message about it to the server if so.
                   1510:                         */
1.303     djm      1511:                        client_check_window_change(ssh);
1.11      markus   1512:
1.56      markus   1513:                        if (quit_pending)
                   1514:                                break;
                   1515:                }
1.13      markus   1516:                /*
                   1517:                 * Wait until we have something to do (something becomes
                   1518:                 * available on one of the descriptors).
                   1519:                 */
1.374     djm      1520:                client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
                   1521:                    &npfd_active, ssh_packet_is_rekeying(ssh),
                   1522:                    &conn_in_ready, &conn_out_ready);
1.11      markus   1523:
                   1524:                if (quit_pending)
                   1525:                        break;
                   1526:
1.379     djm      1527:                /* Do channel operations. */
                   1528:                channel_after_poll(ssh, pfd, npfd_active);
1.11      markus   1529:
1.17      markus   1530:                /* Buffer input from the connection.  */
1.374     djm      1531:                if (conn_in_ready)
                   1532:                        client_process_net_input(ssh);
1.17      markus   1533:
                   1534:                if (quit_pending)
                   1535:                        break;
1.367     djm      1536:
                   1537:                /* A timeout may have triggered rekeying */
                   1538:                if ((r = ssh_packet_check_rekey(ssh)) != 0)
                   1539:                        fatal_fr(r, "cannot start rekeying");
1.11      markus   1540:
1.197     djm      1541:                /*
                   1542:                 * Send as much buffered packet data as possible to the
                   1543:                 * sender.
                   1544:                 */
1.374     djm      1545:                if (conn_out_ready) {
1.338     djm      1546:                        if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   1547:                                sshpkt_fatal(ssh, r,
                   1548:                                    "%s: ssh_packet_write_poll", __func__);
                   1549:                        }
                   1550:                }
1.222     djm      1551:
                   1552:                /*
                   1553:                 * If we are a backgrounded control master, and the
                   1554:                 * timeout has expired without any active client
                   1555:                 * connections, then quit.
                   1556:                 */
                   1557:                if (control_persist_exit_time > 0) {
1.251     dtucker  1558:                        if (monotime() >= control_persist_exit_time) {
1.222     djm      1559:                                debug("ControlPersist timeout expired");
                   1560:                                break;
                   1561:                        }
                   1562:                }
1.11      markus   1563:        }
1.374     djm      1564:        free(pfd);
1.11      markus   1565:
                   1566:        /* Terminate the session. */
                   1567:
                   1568:        /* Stop watching for window change. */
1.332     dtucker  1569:        ssh_signal(SIGWINCH, SIG_DFL);
1.211     andreas  1570:
1.320     djm      1571:        if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   1572:            (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
                   1573:            (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
                   1574:            (r = sshpkt_put_cstring(ssh, "")) != 0 ||   /* language tag */
                   1575:            (r = sshpkt_send(ssh)) != 0 ||
                   1576:            (r = ssh_packet_write_wait(ssh)) != 0)
1.354     djm      1577:                fatal_fr(r, "send disconnect");
1.11      markus   1578:
1.303     djm      1579:        channel_free_all(ssh);
1.11      markus   1580:
1.75      markus   1581:        if (have_pty)
1.233     djm      1582:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.116     dtucker  1583:
                   1584:        /*
                   1585:         * If there was no shell or command requested, there will be no remote
                   1586:         * exit status to be returned.  In that case, clear error code if the
                   1587:         * connection was deliberately terminated at this end.
                   1588:         */
1.370     djm      1589:        if (options.session_type == SESSION_TYPE_NONE &&
                   1590:            received_signal == SIGTERM) {
1.116     dtucker  1591:                received_signal = 0;
                   1592:                exit_status = 0;
                   1593:        }
1.75      markus   1594:
1.301     dtucker  1595:        if (received_signal) {
                   1596:                verbose("Killed by signal %d.", (int) received_signal);
1.359     djm      1597:                cleanup_exit(255);
1.301     dtucker  1598:        }
1.75      markus   1599:
1.13      markus   1600:        /*
                   1601:         * In interactive mode (with pseudo tty) display a message indicating
                   1602:         * that the connection has been closed.
                   1603:         */
1.377     djm      1604:        if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
                   1605:                quit_message("Connection to %s closed.", host);
1.70      markus   1606:
1.11      markus   1607:        /* Output any buffered data for stderr. */
1.315     markus   1608:        if (sshbuf_len(stderr_buffer) > 0) {
1.230     djm      1609:                len = atomicio(vwrite, fileno(stderr),
1.315     markus   1610:                    (u_char *)sshbuf_ptr(stderr_buffer),
                   1611:                    sshbuf_len(stderr_buffer));
                   1612:                if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1.11      markus   1613:                        error("Write failed flushing stderr buffer.");
1.315     markus   1614:                else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1.354     djm      1615:                        fatal_fr(r, "sshbuf_consume");
1.11      markus   1616:        }
                   1617:
                   1618:        /* Clear and free any buffers. */
1.315     markus   1619:        sshbuf_free(stderr_buffer);
1.11      markus   1620:
                   1621:        /* Report bytes transferred, and transfer rates. */
1.307     dtucker  1622:        total_time = monotime_double() - start_time;
1.320     djm      1623:        ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.200     markus   1624:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229     djm      1625:            (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11      markus   1626:        if (total_time > 0)
1.200     markus   1627:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1628:                    obytes / total_time, ibytes / total_time);
1.11      markus   1629:        /* Return the exit status of the program. */
                   1630:        debug("Exit status %d", exit_status);
                   1631:        return exit_status;
1.15      markus   1632: }
                   1633:
                   1634: /*********/
                   1635:
1.77      itojun   1636: static Channel *
1.303     djm      1637: client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
                   1638:     int rchan, u_int rwindow, u_int rmaxpack)
1.40      markus   1639: {
1.103     deraadt  1640:        Channel *c = NULL;
1.289     markus   1641:        struct sshbuf *b = NULL;
1.40      markus   1642:        char *listen_address, *originator_address;
1.320     djm      1643:        u_int listen_port, originator_port;
1.289     markus   1644:        int r;
1.40      markus   1645:
                   1646:        /* Get rest of the packet */
1.320     djm      1647:        if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
                   1648:            (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
                   1649:            (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
                   1650:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
                   1651:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1652:                fatal_fr(r, "parse packet");
1.40      markus   1653:
1.354     djm      1654:        debug_f("listen %s port %d, originator %s port %d",
1.261     millert  1655:            listen_address, listen_port, originator_address, originator_port);
1.191     djm      1656:
1.320     djm      1657:        if (listen_port > 0xffff)
1.354     djm      1658:                error_f("invalid listen port");
1.320     djm      1659:        else if (originator_port > 0xffff)
1.354     djm      1660:                error_f("invalid originator port");
1.320     djm      1661:        else {
                   1662:                c = channel_connect_by_listen_address(ssh,
                   1663:                    listen_address, listen_port, "forwarded-tcpip",
                   1664:                    originator_address);
                   1665:        }
1.40      markus   1666:
1.289     markus   1667:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1668:                if ((b = sshbuf_new()) == NULL) {
1.354     djm      1669:                        error_f("alloc reply");
1.289     markus   1670:                        goto out;
                   1671:                }
                   1672:                /* reconstruct and send to muxclient */
                   1673:                if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
                   1674:                    (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1675:                    (r = sshbuf_put_cstring(b, request_type)) != 0 ||
                   1676:                    (r = sshbuf_put_u32(b, rchan)) != 0 ||
                   1677:                    (r = sshbuf_put_u32(b, rwindow)) != 0 ||
                   1678:                    (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
                   1679:                    (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
                   1680:                    (r = sshbuf_put_u32(b, listen_port)) != 0 ||
                   1681:                    (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
                   1682:                    (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1.303     djm      1683:                    (r = sshbuf_put_stringb(c->output, b)) != 0) {
1.354     djm      1684:                        error_fr(r, "compose for muxclient");
1.289     markus   1685:                        goto out;
                   1686:                }
                   1687:        }
                   1688:
                   1689:  out:
                   1690:        sshbuf_free(b);
1.250     djm      1691:        free(originator_address);
                   1692:        free(listen_address);
1.40      markus   1693:        return c;
                   1694: }
                   1695:
1.103     deraadt  1696: static Channel *
1.303     djm      1697: client_request_forwarded_streamlocal(struct ssh *ssh,
                   1698:     const char *request_type, int rchan)
1.261     millert  1699: {
                   1700:        Channel *c = NULL;
                   1701:        char *listen_path;
1.320     djm      1702:        int r;
1.261     millert  1703:
                   1704:        /* Get the remote path. */
1.320     djm      1705:        if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
                   1706:            (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 ||    /* reserved */
                   1707:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1708:                fatal_fr(r, "parse packet");
1.261     millert  1709:
1.354     djm      1710:        debug_f("request: %s", listen_path);
1.261     millert  1711:
1.303     djm      1712:        c = channel_connect_by_listen_path(ssh, listen_path,
1.261     millert  1713:            "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
                   1714:        free(listen_path);
                   1715:        return c;
                   1716: }
                   1717:
                   1718: static Channel *
1.303     djm      1719: client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1720: {
                   1721:        Channel *c = NULL;
                   1722:        char *originator;
1.321     djm      1723:        u_int originator_port;
1.320     djm      1724:        int r, sock;
1.40      markus   1725:
                   1726:        if (!options.forward_x11) {
                   1727:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1728:                error("Warning: this is probably a break-in attempt by a "
                   1729:                    "malicious server.");
1.221     djm      1730:                return NULL;
                   1731:        }
1.388     dtucker  1732:        if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1.221     djm      1733:                verbose("Rejected X11 connection after ForwardX11Timeout "
                   1734:                    "expired");
1.40      markus   1735:                return NULL;
                   1736:        }
1.320     djm      1737:        if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1.321     djm      1738:            (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1.320     djm      1739:            (r = sshpkt_get_end(ssh)) != 0)
1.354     djm      1740:                fatal_fr(r, "parse packet");
1.40      markus   1741:        /* XXX check permission */
1.321     djm      1742:        /* XXX range check originator port? */
                   1743:        debug("client_request_x11: request from %s %u", originator,
1.47      markus   1744:            originator_port);
1.250     djm      1745:        free(originator);
1.303     djm      1746:        sock = x11_connect_display(ssh);
1.67      markus   1747:        if (sock < 0)
                   1748:                return NULL;
1.303     djm      1749:        c = channel_new(ssh, "x11",
1.67      markus   1750:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1751:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1752:        c->force_drain = 1;
1.40      markus   1753:        return c;
                   1754: }
                   1755:
1.103     deraadt  1756: static Channel *
1.303     djm      1757: client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1.40      markus   1758: {
                   1759:        Channel *c = NULL;
1.262     djm      1760:        int r, sock;
1.40      markus   1761:
                   1762:        if (!options.forward_agent) {
                   1763:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1764:                error("Warning: this is probably a break-in attempt by a "
                   1765:                    "malicious server.");
1.40      markus   1766:                return NULL;
                   1767:        }
1.330     djm      1768:        if (forward_agent_sock_path == NULL) {
                   1769:                r = ssh_get_authentication_socket(&sock);
                   1770:        } else {
                   1771:                r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
                   1772:        }
                   1773:        if (r != 0) {
1.262     djm      1774:                if (r != SSH_ERR_AGENT_NOT_PRESENT)
1.354     djm      1775:                        debug_fr(r, "ssh_get_authentication_socket");
1.67      markus   1776:                return NULL;
1.262     djm      1777:        }
1.372     djm      1778:        if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
                   1779:            ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
                   1780:                debug_f("bound agent to hostkey");
                   1781:        else
                   1782:                debug2_fr(r, "ssh_agent_bind_hostkey");
                   1783:
1.303     djm      1784:        c = channel_new(ssh, "authentication agent connection",
1.67      markus   1785:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1786:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1787:            "authentication agent connection", 1);
1.82      markus   1788:        c->force_drain = 1;
1.40      markus   1789:        return c;
1.180     djm      1790: }
                   1791:
1.306     djm      1792: char *
1.303     djm      1793: client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1.343     djm      1794:     int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1.180     djm      1795: {
                   1796:        Channel *c;
1.320     djm      1797:        int r, fd;
1.306     djm      1798:        char *ifname = NULL;
1.180     djm      1799:
                   1800:        if (tun_mode == SSH_TUNMODE_NO)
                   1801:                return 0;
                   1802:
                   1803:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1804:
                   1805:        /* Open local tunnel device */
1.306     djm      1806:        if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1.180     djm      1807:                error("Tunnel device open failed.");
1.306     djm      1808:                return NULL;
1.180     djm      1809:        }
1.306     djm      1810:        debug("Tunnel forwarding using interface %s", ifname);
1.180     djm      1811:
1.303     djm      1812:        c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1.180     djm      1813:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1814:        c->datagram = 1;
1.343     djm      1815:
                   1816:        if (cb != NULL)
                   1817:                channel_register_open_confirm(ssh, c->self, cb, cbctx);
1.180     djm      1818:
1.320     djm      1819:        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
                   1820:            (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
                   1821:            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1822:            (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
                   1823:            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1824:            (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
                   1825:            (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
                   1826:            (r = sshpkt_send(ssh)) != 0)
1.321     djm      1827:                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.180     djm      1828:
1.306     djm      1829:        return ifname;
1.40      markus   1830: }
                   1831:
1.22      markus   1832: /* XXXX move to generic input handler */
1.264     markus   1833: static int
1.297     markus   1834: client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1.22      markus   1835: {
                   1836:        Channel *c = NULL;
1.320     djm      1837:        char *ctype = NULL;
                   1838:        int r;
                   1839:        u_int rchan;
                   1840:        size_t len;
                   1841:        u_int rmaxpack, rwindow;
                   1842:
                   1843:        if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
                   1844:            (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
                   1845:            (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
                   1846:            (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
                   1847:                goto out;
1.22      markus   1848:
1.24      markus   1849:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1850:            ctype, rchan, rwindow, rmaxpack);
                   1851:
1.40      markus   1852:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
1.303     djm      1853:                c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1.289     markus   1854:                    rmaxpack);
1.261     millert  1855:        } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1.303     djm      1856:                c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1.40      markus   1857:        } else if (strcmp(ctype, "x11") == 0) {
1.303     djm      1858:                c = client_request_x11(ssh, ctype, rchan);
1.40      markus   1859:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1.303     djm      1860:                c = client_request_agent(ssh, ctype, rchan);
1.22      markus   1861:        }
1.289     markus   1862:        if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
                   1863:                debug3("proxied to downstream: %s", ctype);
                   1864:        } else if (c != NULL) {
1.22      markus   1865:                debug("confirm %s", ctype);
                   1866:                c->remote_id = rchan;
1.304     djm      1867:                c->have_remote_id = 1;
1.22      markus   1868:                c->remote_window = rwindow;
                   1869:                c->remote_maxpacket = rmaxpack;
1.69      markus   1870:                if (c->type != SSH_CHANNEL_CONNECTING) {
1.320     djm      1871:                        if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
                   1872:                            (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1873:                            (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
                   1874:                            (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
                   1875:                            (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
                   1876:                            (r = sshpkt_send(ssh)) != 0)
                   1877:                                sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1.69      markus   1878:                }
1.22      markus   1879:        } else {
                   1880:                debug("failure %s", ctype);
1.320     djm      1881:                if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
                   1882:                    (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
                   1883:                    (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
                   1884:                    (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
                   1885:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   1886:                    (r = sshpkt_send(ssh)) != 0)
                   1887:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.22      markus   1888:        }
1.320     djm      1889:        r = 0;
                   1890:  out:
1.250     djm      1891:        free(ctype);
1.320     djm      1892:        return r;
1.22      markus   1893: }
1.267     djm      1894:
1.264     markus   1895: static int
1.297     markus   1896: client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1.48      markus   1897: {
                   1898:        Channel *c = NULL;
1.320     djm      1899:        char *rtype = NULL;
                   1900:        u_char reply;
                   1901:        u_int id, exitval;
                   1902:        int r, success = 0;
                   1903:
                   1904:        if ((r = sshpkt_get_u32(ssh, &id)) != 0)
                   1905:                return r;
                   1906:        if (id <= INT_MAX)
                   1907:                c = channel_lookup(ssh, id);
1.297     markus   1908:        if (channel_proxy_upstream(c, type, seq, ssh))
1.289     markus   1909:                return 0;
1.320     djm      1910:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   1911:            (r = sshpkt_get_u8(ssh, &reply)) != 0)
                   1912:                goto out;
1.48      markus   1913:
1.320     djm      1914:        debug("client_input_channel_req: channel %u rtype %s reply %d",
1.48      markus   1915:            id, rtype, reply);
                   1916:
1.320     djm      1917:        if (c == NULL) {
1.197     djm      1918:                error("client_input_channel_req: channel %d: "
                   1919:                    "unknown channel", id);
1.193     markus   1920:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1.320     djm      1921:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1922:                        goto out;
1.303     djm      1923:                chan_rcvd_eow(ssh, c);
1.48      markus   1924:        } else if (strcmp(rtype, "exit-status") == 0) {
1.320     djm      1925:                if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
                   1926:                        goto out;
1.217     djm      1927:                if (c->ctl_chan != -1) {
1.303     djm      1928:                        mux_exit_message(ssh, c, exitval);
1.215     djm      1929:                        success = 1;
1.320     djm      1930:                } else if ((int)id == session_ident) {
1.215     djm      1931:                        /* Record exit value of local session */
1.123     djm      1932:                        success = 1;
                   1933:                        exit_status = exitval;
1.215     djm      1934:                } else {
1.218     djm      1935:                        /* Probably for a mux channel that has already closed */
1.354     djm      1936:                        debug_f("no sink for exit-status on channel %d",
                   1937:                            id);
1.123     djm      1938:                }
1.320     djm      1939:                if ((r = sshpkt_get_end(ssh)) != 0)
                   1940:                        goto out;
1.48      markus   1941:        }
1.259     djm      1942:        if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.304     djm      1943:                if (!c->have_remote_id)
1.354     djm      1944:                        fatal_f("channel %d: no remote_id", c->self);
1.320     djm      1945:                if ((r = sshpkt_start(ssh, success ?
                   1946:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
                   1947:                    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
                   1948:                    (r = sshpkt_send(ssh)) != 0)
                   1949:                        sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1.48      markus   1950:        }
1.320     djm      1951:        r = 0;
                   1952:  out:
1.250     djm      1953:        free(rtype);
1.320     djm      1954:        return r;
1.48      markus   1955: }
1.267     djm      1956:
1.269     djm      1957: struct hostkeys_update_ctx {
                   1958:        /* The hostname and (optionally) IP address string for the server */
                   1959:        char *host_str, *ip_str;
                   1960:
                   1961:        /*
                   1962:         * Keys received from the server and a flag for each indicating
                   1963:         * whether they already exist in known_hosts.
1.351     djm      1964:         * keys_match is filled in by hostkeys_find() and later (for new
1.381     djm      1965:         * keys) by client_global_hostkeys_prove_confirm().
1.269     djm      1966:         */
                   1967:        struct sshkey **keys;
1.351     djm      1968:        u_int *keys_match;      /* mask of HKF_MATCH_* from hostfile.h */
                   1969:        int *keys_verified;     /* flag for new keys verified by server */
                   1970:        size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
1.269     djm      1971:
                   1972:        /*
                   1973:         * Keys that are in known_hosts, but were not present in the update
                   1974:         * from the server (i.e. scheduled to be deleted).
                   1975:         * Filled in by hostkeys_find().
                   1976:         */
                   1977:        struct sshkey **old_keys;
                   1978:        size_t nold;
1.347     djm      1979:
                   1980:        /* Various special cases. */
1.350     djm      1981:        int complex_hostspec;   /* wildcard or manual pattern-list host name */
1.347     djm      1982:        int ca_available;       /* saw CA key for this host */
1.352     djm      1983:        int old_key_seen;       /* saw old key with other name/addr */
1.353     djm      1984:        int other_name_seen;    /* saw key with other name/addr */
1.269     djm      1985: };
                   1986:
                   1987: static void
                   1988: hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
                   1989: {
                   1990:        size_t i;
                   1991:
                   1992:        if (ctx == NULL)
                   1993:                return;
                   1994:        for (i = 0; i < ctx->nkeys; i++)
                   1995:                sshkey_free(ctx->keys[i]);
                   1996:        free(ctx->keys);
1.351     djm      1997:        free(ctx->keys_match);
                   1998:        free(ctx->keys_verified);
1.269     djm      1999:        for (i = 0; i < ctx->nold; i++)
                   2000:                sshkey_free(ctx->old_keys[i]);
                   2001:        free(ctx->old_keys);
                   2002:        free(ctx->host_str);
                   2003:        free(ctx->ip_str);
                   2004:        free(ctx);
                   2005: }
                   2006:
1.350     djm      2007: /*
                   2008:  * Returns non-zero if a known_hosts hostname list is not of a form that
                   2009:  * can be handled by UpdateHostkeys. These include wildcard hostnames and
                   2010:  * hostnames lists that do not follow the form host[,ip].
                   2011:  */
                   2012: static int
                   2013: hostspec_is_complex(const char *hosts)
                   2014: {
                   2015:        char *cp;
                   2016:
                   2017:        /* wildcard */
                   2018:        if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
                   2019:                return 1;
                   2020:        /* single host/ip = ok */
                   2021:        if ((cp = strchr(hosts, ',')) == NULL)
                   2022:                return 0;
                   2023:        /* more than two entries on the line */
                   2024:        if (strchr(cp + 1, ',') != NULL)
                   2025:                return 1;
                   2026:        /* XXX maybe parse cp+1 and ensure it is an IP? */
                   2027:        return 0;
                   2028: }
                   2029:
1.352     djm      2030: /* callback to search for ctx->keys in known_hosts */
1.269     djm      2031: static int
                   2032: hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
                   2033: {
                   2034:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2035:        size_t i;
                   2036:        struct sshkey **tmp;
                   2037:
1.353     djm      2038:        if (l->key == NULL)
1.269     djm      2039:                return 0;
1.353     djm      2040:        if (l->status != HKF_STATUS_MATCHED) {
                   2041:                /* Record if one of the keys appears on a non-matching line */
                   2042:                for (i = 0; i < ctx->nkeys; i++) {
                   2043:                        if (sshkey_equal(l->key, ctx->keys[i])) {
                   2044:                                ctx->other_name_seen = 1;
1.354     djm      2045:                                debug3_f("found %s key under different "
                   2046:                                    "name/addr at %s:%ld",
1.353     djm      2047:                                    sshkey_ssh_name(ctx->keys[i]),
                   2048:                                    l->path, l->linenum);
                   2049:                                return 0;
                   2050:                        }
                   2051:                }
                   2052:                return 0;
                   2053:        }
                   2054:        /* Don't proceed if revocation or CA markers are present */
                   2055:        /* XXX relax this */
                   2056:        if (l->marker != MRK_NONE) {
1.354     djm      2057:                debug3_f("hostkeys file %s:%ld has CA/revocation marker",
                   2058:                    l->path, l->linenum);
1.353     djm      2059:                ctx->complex_hostspec = 1;
                   2060:                return 0;
                   2061:        }
                   2062:
1.355     djm      2063:        /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
                   2064:        if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
                   2065:                if ((l->match & HKF_MATCH_HOST) == 0) {
                   2066:                        /* Record if address matched a different hostname. */
                   2067:                        ctx->other_name_seen = 1;
                   2068:                        debug3_f("found address %s against different hostname "
                   2069:                            "at %s:%ld", ctx->ip_str, l->path, l->linenum);
                   2070:                        return 0;
                   2071:                } else if ((l->match & HKF_MATCH_IP) == 0) {
                   2072:                        /* Record if hostname matched a different address. */
                   2073:                        ctx->other_name_seen = 1;
                   2074:                        debug3_f("found hostname %s against different address "
                   2075:                            "at %s:%ld", ctx->host_str, l->path, l->linenum);
                   2076:                }
1.353     djm      2077:        }
1.269     djm      2078:
1.350     djm      2079:        /*
                   2080:         * UpdateHostkeys is skipped for wildcard host names and hostnames
                   2081:         * that contain more than two entries (ssh never writes these).
                   2082:         */
                   2083:        if (hostspec_is_complex(l->hosts)) {
1.354     djm      2084:                debug3_f("hostkeys file %s:%ld complex host specification",
                   2085:                    l->path, l->linenum);
1.350     djm      2086:                ctx->complex_hostspec = 1;
1.347     djm      2087:                return 0;
                   2088:        }
                   2089:
1.269     djm      2090:        /* Mark off keys we've already seen for this host */
                   2091:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2092:                if (!sshkey_equal(l->key, ctx->keys[i]))
                   2093:                        continue;
1.354     djm      2094:                debug3_f("found %s key at %s:%ld",
1.351     djm      2095:                    sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
                   2096:                ctx->keys_match[i] |= l->match;
                   2097:                return 0;
1.269     djm      2098:        }
                   2099:        /* This line contained a key that not offered by the server */
1.354     djm      2100:        debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
                   2101:            l->path, l->linenum);
1.299     deraadt  2102:        if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1.269     djm      2103:            sizeof(*ctx->old_keys))) == NULL)
1.354     djm      2104:                fatal_f("recallocarray failed nold = %zu", ctx->nold);
1.269     djm      2105:        ctx->old_keys = tmp;
                   2106:        ctx->old_keys[ctx->nold++] = l->key;
                   2107:        l->key = NULL;
                   2108:
                   2109:        return 0;
                   2110: }
                   2111:
1.352     djm      2112: /* callback to search for ctx->old_keys in known_hosts under other names */
                   2113: static int
                   2114: hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
                   2115: {
                   2116:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2117:        size_t i;
                   2118:        int hashed;
                   2119:
                   2120:        /* only care about lines that *don't* match the active host spec */
                   2121:        if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
                   2122:                return 0;
                   2123:
                   2124:        hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
                   2125:        for (i = 0; i < ctx->nold; i++) {
                   2126:                if (!sshkey_equal(l->key, ctx->old_keys[i]))
                   2127:                        continue;
1.354     djm      2128:                debug3_f("found deprecated %s key at %s:%ld as %s",
1.364     djm      2129:                    sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
1.352     djm      2130:                    hashed ? "[HASHED]" : l->hosts);
                   2131:                ctx->old_key_seen = 1;
                   2132:                break;
                   2133:        }
                   2134:        return 0;
                   2135: }
                   2136:
                   2137: /*
                   2138:  * Check known_hosts files for deprecated keys under other names. Returns 0
                   2139:  * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
                   2140:  * exist under names other than the active hostname/IP.
                   2141:  */
                   2142: static int
                   2143: check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
                   2144: {
                   2145:        size_t i;
                   2146:        int r;
                   2147:
1.354     djm      2148:        debug2_f("checking for %zu deprecated keys", ctx->nold);
1.352     djm      2149:        for (i = 0; i < options.num_user_hostfiles; i++) {
1.354     djm      2150:                debug3_f("searching %s for %s / %s",
1.352     djm      2151:                    options.user_hostfiles[i], ctx->host_str,
                   2152:                    ctx->ip_str ? ctx->ip_str : "(none)");
                   2153:                if ((r = hostkeys_foreach(options.user_hostfiles[i],
                   2154:                    hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
1.356     djm      2155:                    HKF_WANT_PARSE_KEY, 0)) != 0) {
1.352     djm      2156:                        if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354     djm      2157:                                debug_f("hostkeys file %s does not exist",
                   2158:                                    options.user_hostfiles[i]);
1.352     djm      2159:                                continue;
                   2160:                        }
1.354     djm      2161:                        error_fr(r, "hostkeys_foreach failed for %s",
                   2162:                            options.user_hostfiles[i]);
1.352     djm      2163:                        return -1;
                   2164:                }
                   2165:        }
                   2166:        return 0;
                   2167: }
                   2168:
1.269     djm      2169: static void
1.337     djm      2170: hostkey_change_preamble(LogLevel loglevel)
1.269     djm      2171: {
1.336     djm      2172:        do_log2(loglevel, "The server has updated its host keys.");
                   2173:        do_log2(loglevel, "These changes were verified by the server's "
                   2174:            "existing trusted key.");
                   2175: }
                   2176:
                   2177: static void
                   2178: update_known_hosts(struct hostkeys_update_ctx *ctx)
                   2179: {
                   2180:        int r, was_raw = 0, first = 1;
                   2181:        int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
                   2182:        LogLevel loglevel = asking ?  SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1.269     djm      2183:        char *fp, *response;
                   2184:        size_t i;
1.333     djm      2185:        struct stat sb;
1.269     djm      2186:
                   2187:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2188:                if (!ctx->keys_verified[i])
1.269     djm      2189:                        continue;
                   2190:                if ((fp = sshkey_fingerprint(ctx->keys[i],
                   2191:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354     djm      2192:                        fatal_f("sshkey_fingerprint failed");
1.336     djm      2193:                if (first && asking)
1.337     djm      2194:                        hostkey_change_preamble(loglevel);
1.269     djm      2195:                do_log2(loglevel, "Learned new hostkey: %s %s",
                   2196:                    sshkey_type(ctx->keys[i]), fp);
1.336     djm      2197:                first = 0;
1.269     djm      2198:                free(fp);
                   2199:        }
                   2200:        for (i = 0; i < ctx->nold; i++) {
                   2201:                if ((fp = sshkey_fingerprint(ctx->old_keys[i],
                   2202:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.354     djm      2203:                        fatal_f("sshkey_fingerprint failed");
1.336     djm      2204:                if (first && asking)
1.337     djm      2205:                        hostkey_change_preamble(loglevel);
1.269     djm      2206:                do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
                   2207:                    sshkey_type(ctx->old_keys[i]), fp);
1.336     djm      2208:                first = 0;
1.269     djm      2209:                free(fp);
                   2210:        }
                   2211:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1.271     djm      2212:                if (get_saved_tio() != NULL) {
                   2213:                        leave_raw_mode(1);
                   2214:                        was_raw = 1;
                   2215:                }
1.269     djm      2216:                response = NULL;
                   2217:                for (i = 0; !quit_pending && i < 3; i++) {
                   2218:                        free(response);
                   2219:                        response = read_passphrase("Accept updated hostkeys? "
                   2220:                            "(yes/no): ", RP_ECHO);
1.389     dtucker  2221:                        if (response != NULL && strcasecmp(response, "yes") == 0)
1.269     djm      2222:                                break;
                   2223:                        else if (quit_pending || response == NULL ||
                   2224:                            strcasecmp(response, "no") == 0) {
                   2225:                                options.update_hostkeys = 0;
                   2226:                                break;
                   2227:                        } else {
                   2228:                                do_log2(loglevel, "Please enter "
                   2229:                                    "\"yes\" or \"no\"");
                   2230:                        }
                   2231:                }
                   2232:                if (quit_pending || i >= 3 || response == NULL)
                   2233:                        options.update_hostkeys = 0;
                   2234:                free(response);
1.271     djm      2235:                if (was_raw)
                   2236:                        enter_raw_mode(1);
1.269     djm      2237:        }
1.333     djm      2238:        if (options.update_hostkeys == 0)
                   2239:                return;
1.269     djm      2240:        /*
                   2241:         * Now that all the keys are verified, we can go ahead and replace
                   2242:         * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
                   2243:         * cancel the operation).
                   2244:         */
1.333     djm      2245:        for (i = 0; i < options.num_user_hostfiles; i++) {
                   2246:                /*
                   2247:                 * NB. keys are only added to hostfiles[0], for the rest we
                   2248:                 * just delete the hostname entries.
                   2249:                 */
                   2250:                if (stat(options.user_hostfiles[i], &sb) != 0) {
                   2251:                        if (errno == ENOENT) {
1.354     djm      2252:                                debug_f("known hosts file %s does not "
                   2253:                                    "exist", options.user_hostfiles[i]);
1.333     djm      2254:                        } else {
1.354     djm      2255:                                error_f("known hosts file %s "
                   2256:                                    "inaccessible: %s",
                   2257:                                    options.user_hostfiles[i], strerror(errno));
1.333     djm      2258:                        }
                   2259:                        continue;
                   2260:                }
                   2261:                if ((r = hostfile_replace_entries(options.user_hostfiles[i],
                   2262:                    ctx->host_str, ctx->ip_str,
                   2263:                    i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
                   2264:                    options.hash_known_hosts, 0,
                   2265:                    options.fingerprint_hash)) != 0) {
1.354     djm      2266:                        error_fr(r, "hostfile_replace_entries failed for %s",
                   2267:                            options.user_hostfiles[i]);
1.333     djm      2268:                }
                   2269:        }
1.269     djm      2270: }
                   2271:
                   2272: static void
1.381     djm      2273: client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
1.303     djm      2274:     u_int32_t seq, void *_ctx)
1.269     djm      2275: {
                   2276:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2277:        size_t i, ndone;
                   2278:        struct sshbuf *signdata;
1.375     djm      2279:        int r, plaintype;
1.269     djm      2280:        const u_char *sig;
1.375     djm      2281:        const char *rsa_kexalg = NULL;
                   2282:        char *alg = NULL;
1.269     djm      2283:        size_t siglen;
                   2284:
                   2285:        if (ctx->nnew == 0)
1.354     djm      2286:                fatal_f("ctx->nnew == 0"); /* sanity */
1.269     djm      2287:        if (type != SSH2_MSG_REQUEST_SUCCESS) {
                   2288:                error("Server failed to confirm ownership of "
                   2289:                    "private host keys");
                   2290:                hostkeys_update_ctx_free(ctx);
                   2291:                return;
                   2292:        }
1.375     djm      2293:        if (sshkey_type_plain(sshkey_type_from_name(
                   2294:            ssh->kex->hostkey_alg)) == KEY_RSA)
                   2295:                rsa_kexalg = ssh->kex->hostkey_alg;
1.269     djm      2296:        if ((signdata = sshbuf_new()) == NULL)
1.354     djm      2297:                fatal_f("sshbuf_new failed");
1.269     djm      2298:        /*
                   2299:         * Expect a signature for each of the ctx->nnew private keys we
                   2300:         * haven't seen before. They will be in the same order as the
1.351     djm      2301:         * ctx->keys where the corresponding ctx->keys_match[i] == 0.
1.269     djm      2302:         */
                   2303:        for (ndone = i = 0; i < ctx->nkeys; i++) {
1.351     djm      2304:                if (ctx->keys_match[i])
1.269     djm      2305:                        continue;
1.375     djm      2306:                plaintype = sshkey_type_plain(ctx->keys[i]->type);
1.269     djm      2307:                /* Prepare data to be signed: session ID, unique string, key */
                   2308:                sshbuf_reset(signdata);
1.270     djm      2309:                if ( (r = sshbuf_put_cstring(signdata,
                   2310:                    "hostkeys-prove-00@openssh.com")) != 0 ||
1.358     djm      2311:                    (r = sshbuf_put_stringb(signdata,
                   2312:                    ssh->kex->session_id)) != 0 ||
1.269     djm      2313:                    (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1.354     djm      2314:                        fatal_fr(r, "compose signdata");
1.269     djm      2315:                /* Extract and verify signature */
                   2316:                if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1.354     djm      2317:                        error_fr(r, "parse sig");
1.269     djm      2318:                        goto out;
                   2319:                }
1.375     djm      2320:                if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
                   2321:                        error_fr(r, "server gave unintelligible signature "
                   2322:                            "for %s key %zu", sshkey_type(ctx->keys[i]), i);
                   2323:                        goto out;
                   2324:                }
1.309     djm      2325:                /*
1.375     djm      2326:                 * Special case for RSA keys: if a RSA hostkey was negotiated,
                   2327:                 * then use its signature type for verification of RSA hostkey
                   2328:                 * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
1.309     djm      2329:                 */
1.375     djm      2330:                if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
                   2331:                    match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
                   2332:                        debug_f("server used untrusted RSA signature algorithm "
                   2333:                            "%s for key %zu, disregarding", alg, i);
                   2334:                        free(alg);
                   2335:                        /* zap the key from the list */
                   2336:                        sshkey_free(ctx->keys[i]);
                   2337:                        ctx->keys[i] = NULL;
                   2338:                        ndone++;
                   2339:                        continue;
                   2340:                }
                   2341:                debug3_f("verify %s key %zu using sigalg %s",
                   2342:                    sshkey_type(ctx->keys[i]), i, alg);
                   2343:                free(alg);
1.269     djm      2344:                if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1.308     djm      2345:                    sshbuf_ptr(signdata), sshbuf_len(signdata),
1.375     djm      2346:                    plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
1.361     djm      2347:                        error_fr(r, "server gave bad signature for %s key %zu",
1.354     djm      2348:                            sshkey_type(ctx->keys[i]), i);
1.269     djm      2349:                        goto out;
                   2350:                }
                   2351:                /* Key is good. Mark it as 'seen' */
1.351     djm      2352:                ctx->keys_verified[i] = 1;
1.269     djm      2353:                ndone++;
                   2354:        }
1.354     djm      2355:        /* Shouldn't happen */
1.269     djm      2356:        if (ndone != ctx->nnew)
1.354     djm      2357:                fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
1.320     djm      2358:        if ((r = sshpkt_get_end(ssh)) != 0) {
1.354     djm      2359:                error_f("protocol error");
1.320     djm      2360:                goto out;
                   2361:        }
1.269     djm      2362:
                   2363:        /* Make the edits to known_hosts */
                   2364:        update_known_hosts(ctx);
                   2365:  out:
                   2366:        hostkeys_update_ctx_free(ctx);
1.384     djm      2367:        hostkeys_update_complete = 1;
                   2368:        client_repledge();
1.269     djm      2369: }
                   2370:
1.267     djm      2371: /*
1.291     djm      2372:  * Returns non-zero if the key is accepted by HostkeyAlgorithms.
                   2373:  * Made slightly less trivial by the multiple RSA signature algorithm names.
                   2374:  */
                   2375: static int
                   2376: key_accepted_by_hostkeyalgs(const struct sshkey *key)
                   2377: {
                   2378:        const char *ktype = sshkey_ssh_name(key);
1.331     dtucker  2379:        const char *hostkeyalgs = options.hostkeyalgorithms;
1.291     djm      2380:
1.391     djm      2381:        if (key->type == KEY_UNSPEC)
1.291     djm      2382:                return 0;
                   2383:        if (key->type == KEY_RSA &&
                   2384:            (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
                   2385:            match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
                   2386:                return 1;
                   2387:        return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
                   2388: }
                   2389:
                   2390: /*
1.270     djm      2391:  * Handle hostkeys-00@openssh.com global request to inform the client of all
1.267     djm      2392:  * the server's hostkeys. The keys are checked against the user's
                   2393:  * HostkeyAlgorithms preference before they are accepted.
                   2394:  */
                   2395: static int
1.321     djm      2396: client_input_hostkeys(struct ssh *ssh)
1.267     djm      2397: {
                   2398:        const u_char *blob = NULL;
1.269     djm      2399:        size_t i, len = 0;
1.267     djm      2400:        struct sshbuf *buf = NULL;
1.269     djm      2401:        struct sshkey *key = NULL, **tmp;
1.384     djm      2402:        int r, prove_sent = 0;
1.269     djm      2403:        char *fp;
1.267     djm      2404:        static int hostkeys_seen = 0; /* XXX use struct ssh */
1.268     djm      2405:        extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1.272     djm      2406:        struct hostkeys_update_ctx *ctx = NULL;
1.351     djm      2407:        u_int want;
1.267     djm      2408:
                   2409:        if (hostkeys_seen)
1.354     djm      2410:                fatal_f("server already sent hostkeys");
1.384     djm      2411:        if (!can_update_hostkeys())
1.267     djm      2412:                return 1;
1.384     djm      2413:        hostkeys_seen = 1;
1.272     djm      2414:
                   2415:        ctx = xcalloc(1, sizeof(*ctx));
1.269     djm      2416:        while (ssh_packet_remaining(ssh) > 0) {
1.267     djm      2417:                sshkey_free(key);
                   2418:                key = NULL;
1.269     djm      2419:                if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
1.354     djm      2420:                        error_fr(r, "parse key");
1.269     djm      2421:                        goto out;
                   2422:                }
1.270     djm      2423:                if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
1.354     djm      2424:                        do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
1.335     djm      2425:                            SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
1.354     djm      2426:                            "convert key");
1.335     djm      2427:                        continue;
1.270     djm      2428:                }
1.267     djm      2429:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                   2430:                    SSH_FP_DEFAULT);
1.354     djm      2431:                debug3_f("received %s key %s", sshkey_type(key), fp);
1.267     djm      2432:                free(fp);
1.275     markus   2433:
1.291     djm      2434:                if (!key_accepted_by_hostkeyalgs(key)) {
1.354     djm      2435:                        debug3_f("%s key not permitted by "
                   2436:                            "HostkeyAlgorithms", sshkey_ssh_name(key));
1.267     djm      2437:                        continue;
                   2438:                }
1.269     djm      2439:                /* Skip certs */
                   2440:                if (sshkey_is_cert(key)) {
1.354     djm      2441:                        debug3_f("%s key is a certificate; skipping",
                   2442:                            sshkey_ssh_name(key));
1.269     djm      2443:                        continue;
                   2444:                }
                   2445:                /* Ensure keys are unique */
                   2446:                for (i = 0; i < ctx->nkeys; i++) {
                   2447:                        if (sshkey_equal(key, ctx->keys[i])) {
1.354     djm      2448:                                error_f("received duplicated %s host key",
                   2449:                                    sshkey_ssh_name(key));
1.269     djm      2450:                                goto out;
                   2451:                        }
                   2452:                }
                   2453:                /* Key is good, record it */
1.299     deraadt  2454:                if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
1.269     djm      2455:                    sizeof(*ctx->keys))) == NULL)
1.354     djm      2456:                        fatal_f("recallocarray failed nkeys = %zu",
                   2457:                            ctx->nkeys);
1.269     djm      2458:                ctx->keys = tmp;
                   2459:                ctx->keys[ctx->nkeys++] = key;
1.267     djm      2460:                key = NULL;
                   2461:        }
                   2462:
1.269     djm      2463:        if (ctx->nkeys == 0) {
1.354     djm      2464:                debug_f("server sent no hostkeys");
1.267     djm      2465:                goto out;
                   2466:        }
1.270     djm      2467:
1.351     djm      2468:        if ((ctx->keys_match = calloc(ctx->nkeys,
                   2469:            sizeof(*ctx->keys_match))) == NULL ||
                   2470:            (ctx->keys_verified = calloc(ctx->nkeys,
                   2471:            sizeof(*ctx->keys_verified))) == NULL)
1.354     djm      2472:                fatal_f("calloc failed");
1.267     djm      2473:
1.268     djm      2474:        get_hostfile_hostname_ipaddr(host,
                   2475:            options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
1.269     djm      2476:            options.port, &ctx->host_str,
                   2477:            options.check_host_ip ? &ctx->ip_str : NULL);
1.268     djm      2478:
1.269     djm      2479:        /* Find which keys we already know about. */
1.333     djm      2480:        for (i = 0; i < options.num_user_hostfiles; i++) {
1.354     djm      2481:                debug_f("searching %s for %s / %s",
1.339     dtucker  2482:                    options.user_hostfiles[i], ctx->host_str,
1.340     dtucker  2483:                    ctx->ip_str ? ctx->ip_str : "(none)");
1.333     djm      2484:                if ((r = hostkeys_foreach(options.user_hostfiles[i],
                   2485:                    hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
1.356     djm      2486:                    HKF_WANT_PARSE_KEY, 0)) != 0) {
1.333     djm      2487:                        if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1.354     djm      2488:                                debug_f("hostkeys file %s does not exist",
                   2489:                                    options.user_hostfiles[i]);
1.333     djm      2490:                                continue;
                   2491:                        }
1.354     djm      2492:                        error_fr(r, "hostkeys_foreach failed for %s",
                   2493:                            options.user_hostfiles[i]);
1.333     djm      2494:                        goto out;
                   2495:                }
1.267     djm      2496:        }
                   2497:
1.269     djm      2498:        /* Figure out if we have any new keys to add */
1.351     djm      2499:        ctx->nnew = ctx->nincomplete = 0;
                   2500:        want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
1.269     djm      2501:        for (i = 0; i < ctx->nkeys; i++) {
1.351     djm      2502:                if (ctx->keys_match[i] == 0)
1.269     djm      2503:                        ctx->nnew++;
1.351     djm      2504:                if ((ctx->keys_match[i] & want) != want)
                   2505:                        ctx->nincomplete++;
1.269     djm      2506:        }
                   2507:
1.354     djm      2508:        debug3_f("%zu server keys: %zu new, %zu retained, "
                   2509:            "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
                   2510:            ctx->nkeys - ctx->nnew - ctx->nincomplete,
1.351     djm      2511:            ctx->nincomplete, ctx->nold);
1.269     djm      2512:
1.353     djm      2513:        if (ctx->nnew == 0 && ctx->nold == 0) {
1.354     djm      2514:                debug_f("no new or deprecated keys from server");
1.353     djm      2515:                goto out;
                   2516:        }
                   2517:
                   2518:        /* Various reasons why we cannot proceed with the update */
                   2519:        if (ctx->complex_hostspec) {
1.354     djm      2520:                debug_f("CA/revocation marker, manual host list or wildcard "
                   2521:                    "host pattern found, skipping UserKnownHostsFile update");
1.353     djm      2522:                goto out;
                   2523:        }
                   2524:        if (ctx->other_name_seen) {
1.354     djm      2525:                debug_f("host key found matching a different name/address, "
                   2526:                    "skipping UserKnownHostsFile update");
1.347     djm      2527:                goto out;
1.352     djm      2528:        }
                   2529:        /*
                   2530:         * If removing keys, check whether they appear under different
                   2531:         * names/addresses and refuse to proceed if they do. This avoids
                   2532:         * cases such as hosts with multiple names becoming inconsistent
                   2533:         * with regards to CheckHostIP entries.
                   2534:         * XXX UpdateHostkeys=force to override this (and other) checks?
                   2535:         */
                   2536:        if (ctx->nold != 0) {
                   2537:                if (check_old_keys_othernames(ctx) != 0)
                   2538:                        goto out; /* error already logged */
                   2539:                if (ctx->old_key_seen) {
1.354     djm      2540:                        debug_f("key(s) for %s%s%s exist under other names; "
                   2541:                            "skipping UserKnownHostsFile update",
1.352     djm      2542:                            ctx->host_str, ctx->ip_str == NULL ? "" : ",",
                   2543:                            ctx->ip_str == NULL ? "" : ctx->ip_str);
                   2544:                        goto out;
                   2545:                }
                   2546:        }
                   2547:
1.353     djm      2548:        if (ctx->nnew == 0) {
1.351     djm      2549:                /*
                   2550:                 * We have some keys to remove or fix matching for.
                   2551:                 * We can proceed to do this without requiring a fresh proof
                   2552:                 * from the server.
                   2553:                 */
1.269     djm      2554:                update_known_hosts(ctx);
1.353     djm      2555:                goto out;
                   2556:        }
                   2557:        /*
                   2558:         * We have received previously-unseen keys from the server.
                   2559:         * Ask the server to confirm ownership of the private halves.
                   2560:         */
1.354     djm      2561:        debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
1.353     djm      2562:        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   2563:            (r = sshpkt_put_cstring(ssh,
                   2564:            "hostkeys-prove-00@openssh.com")) != 0 ||
                   2565:            (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
1.354     djm      2566:                fatal_fr(r, "prepare hostkeys-prove");
1.353     djm      2567:        if ((buf = sshbuf_new()) == NULL)
1.354     djm      2568:                fatal_f("sshbuf_new");
1.353     djm      2569:        for (i = 0; i < ctx->nkeys; i++) {
                   2570:                if (ctx->keys_match[i])
                   2571:                        continue;
                   2572:                sshbuf_reset(buf);
                   2573:                if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
1.354     djm      2574:                    (r = sshpkt_put_stringb(ssh, buf)) != 0)
                   2575:                        fatal_fr(r, "assemble hostkeys-prove");
1.269     djm      2576:        }
1.353     djm      2577:        if ((r = sshpkt_send(ssh)) != 0)
1.354     djm      2578:                fatal_fr(r, "send hostkeys-prove");
1.353     djm      2579:        client_register_global_confirm(
1.381     djm      2580:            client_global_hostkeys_prove_confirm, ctx);
1.353     djm      2581:        ctx = NULL;  /* will be freed in callback */
1.384     djm      2582:        prove_sent = 1;
1.269     djm      2583:
1.267     djm      2584:        /* Success */
                   2585:  out:
1.269     djm      2586:        hostkeys_update_ctx_free(ctx);
1.267     djm      2587:        sshkey_free(key);
                   2588:        sshbuf_free(buf);
1.384     djm      2589:        if (!prove_sent) {
                   2590:                /* UpdateHostkeys handling completed */
                   2591:                hostkeys_update_complete = 1;
                   2592:                client_repledge();
                   2593:        }
1.269     djm      2594:        /*
                   2595:         * NB. Return success for all cases. The server doesn't need to know
                   2596:         * what the client does with its hosts file.
                   2597:         */
                   2598:        return 1;
1.267     djm      2599: }
                   2600:
1.264     markus   2601: static int
1.297     markus   2602: client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
1.95      markus   2603: {
                   2604:        char *rtype;
1.320     djm      2605:        u_char want_reply;
                   2606:        int r, success = 0;
1.95      markus   2607:
1.320     djm      2608:        if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
                   2609:            (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
                   2610:                goto out;
1.117     markus   2611:        debug("client_input_global_request: rtype %s want_reply %d",
                   2612:            rtype, want_reply);
1.270     djm      2613:        if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
1.321     djm      2614:                success = client_input_hostkeys(ssh);
1.95      markus   2615:        if (want_reply) {
1.320     djm      2616:                if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
                   2617:                    SSH2_MSG_REQUEST_FAILURE)) != 0 ||
                   2618:                    (r = sshpkt_send(ssh)) != 0 ||
                   2619:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   2620:                        goto out;
1.95      markus   2621:        }
1.320     djm      2622:        r = 0;
                   2623:  out:
1.250     djm      2624:        free(rtype);
1.320     djm      2625:        return r;
1.95      markus   2626: }
1.22      markus   2627:
1.354     djm      2628: static void
                   2629: client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
                   2630: {
                   2631:        int r;
                   2632:
                   2633:        debug("channel %d: setting env %s = \"%s\"", id, name, val);
                   2634:        channel_request_start(ssh, id, "env", 0);
                   2635:        if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
                   2636:            (r = sshpkt_put_cstring(ssh, val)) != 0 ||
                   2637:            (r = sshpkt_send(ssh)) != 0)
                   2638:                fatal_fr(r, "send setenv");
                   2639: }
                   2640:
1.123     djm      2641: void
1.303     djm      2642: client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
1.315     markus   2643:     const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
                   2644:     char **env)
1.123     djm      2645: {
1.380     djm      2646:        size_t i, j, len;
                   2647:        int matched, r;
1.313     djm      2648:        char *name, *val;
1.132     djm      2649:        Channel *c = NULL;
1.123     djm      2650:
1.354     djm      2651:        debug2_f("id %d", id);
1.123     djm      2652:
1.303     djm      2653:        if ((c = channel_lookup(ssh, id)) == NULL)
1.354     djm      2654:                fatal_f("channel %d: unknown channel", id);
1.224     djm      2655:
1.320     djm      2656:        ssh_packet_set_interactive(ssh, want_tty,
1.224     djm      2657:            options.ip_qos_interactive, options.ip_qos_bulk);
1.132     djm      2658:
1.123     djm      2659:        if (want_tty) {
                   2660:                struct winsize ws;
                   2661:
                   2662:                /* Store window size in the packet. */
1.326     deraadt  2663:                if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
1.123     djm      2664:                        memset(&ws, 0, sizeof(ws));
                   2665:
1.303     djm      2666:                channel_request_start(ssh, id, "pty-req", 1);
                   2667:                client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
1.320     djm      2668:                if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
                   2669:                    != 0 ||
                   2670:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
                   2671:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
                   2672:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
                   2673:                    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
1.354     djm      2674:                        fatal_fr(r, "build pty-req");
1.194     djm      2675:                if (tiop == NULL)
                   2676:                        tiop = get_saved_tio();
1.316     markus   2677:                ssh_tty_make_modes(ssh, -1, tiop);
1.320     djm      2678:                if ((r = sshpkt_send(ssh)) != 0)
1.354     djm      2679:                        fatal_fr(r, "send pty-req");
1.123     djm      2680:                /* XXX wait for reply */
1.132     djm      2681:                c->client_tty = 1;
1.123     djm      2682:        }
                   2683:
                   2684:        /* Transfer any environment variables from client to server */
1.126     djm      2685:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      2686:                debug("Sending environment.");
1.126     djm      2687:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      2688:                        /* Split */
1.126     djm      2689:                        name = xstrdup(env[i]);
1.123     djm      2690:                        if ((val = strchr(name, '=')) == NULL) {
1.250     djm      2691:                                free(name);
1.123     djm      2692:                                continue;
                   2693:                        }
                   2694:                        *val++ = '\0';
                   2695:
                   2696:                        matched = 0;
                   2697:                        for (j = 0; j < options.num_send_env; j++) {
                   2698:                                if (match_pattern(name, options.send_env[j])) {
                   2699:                                        matched = 1;
                   2700:                                        break;
                   2701:                                }
                   2702:                        }
                   2703:                        if (!matched) {
                   2704:                                debug3("Ignored env %s", name);
1.250     djm      2705:                                free(name);
1.123     djm      2706:                                continue;
                   2707:                        }
1.354     djm      2708:                        client_send_env(ssh, id, name, val);
1.250     djm      2709:                        free(name);
1.123     djm      2710:                }
1.313     djm      2711:        }
                   2712:        for (i = 0; i < options.num_setenv; i++) {
                   2713:                /* Split */
                   2714:                name = xstrdup(options.setenv[i]);
                   2715:                if ((val = strchr(name, '=')) == NULL) {
                   2716:                        free(name);
                   2717:                        continue;
                   2718:                }
                   2719:                *val++ = '\0';
1.354     djm      2720:                client_send_env(ssh, id, name, val);
1.313     djm      2721:                free(name);
1.123     djm      2722:        }
                   2723:
1.315     markus   2724:        len = sshbuf_len(cmd);
1.123     djm      2725:        if (len > 0) {
                   2726:                if (len > 900)
                   2727:                        len = 900;
                   2728:                if (want_subsystem) {
1.190     djm      2729:                        debug("Sending subsystem: %.*s",
1.380     djm      2730:                            (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2731:                        channel_request_start(ssh, id, "subsystem", 1);
                   2732:                        client_expect_confirm(ssh, id, "subsystem",
                   2733:                            CONFIRM_CLOSE);
1.123     djm      2734:                } else {
1.190     djm      2735:                        debug("Sending command: %.*s",
1.380     djm      2736:                            (int)len, (const u_char*)sshbuf_ptr(cmd));
1.303     djm      2737:                        channel_request_start(ssh, id, "exec", 1);
                   2738:                        client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
1.123     djm      2739:                }
1.320     djm      2740:                if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
                   2741:                    (r = sshpkt_send(ssh)) != 0)
1.354     djm      2742:                        fatal_fr(r, "send command");
1.123     djm      2743:        } else {
1.303     djm      2744:                channel_request_start(ssh, id, "shell", 1);
                   2745:                client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
1.354     djm      2746:                if ((r = sshpkt_send(ssh)) != 0)
                   2747:                        fatal_fr(r, "send shell");
1.123     djm      2748:        }
1.384     djm      2749:
                   2750:        session_setup_complete = 1;
                   2751:        client_repledge();
1.123     djm      2752: }
                   2753:
1.77      itojun   2754: static void
1.321     djm      2755: client_init_dispatch(struct ssh *ssh)
1.16      markus   2756: {
1.321     djm      2757:        ssh_dispatch_init(ssh, &dispatch_protocol_error);
1.100     markus   2758:
1.321     djm      2759:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   2760:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   2761:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   2762:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
                   2763:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
                   2764:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2765:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2766:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
                   2767:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
                   2768:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2769:        ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
                   2770:        ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2771:
                   2772:        /* rekeying */
1.321     djm      2773:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2774:
                   2775:        /* global request reply messages */
1.321     djm      2776:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2777:        ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.232     djm      2778: }
                   2779:
                   2780: void
                   2781: client_stop_mux(void)
                   2782: {
                   2783:        if (options.control_path != NULL && muxserver_sock != -1)
                   2784:                unlink(options.control_path);
                   2785:        /*
1.247     dtucker  2786:         * If we are in persist mode, or don't have a shell, signal that we
                   2787:         * should close when all active channels are closed.
1.232     djm      2788:         */
1.366     djm      2789:        if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
1.232     djm      2790:                session_closed = 1;
1.235     djm      2791:                setproctitle("[stopped mux]");
                   2792:        }
1.113     markus   2793: }
                   2794:
                   2795: /* client specific fatal cleanup */
                   2796: void
1.114     markus   2797: cleanup_exit(int i)
1.113     markus   2798: {
1.233     djm      2799:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.192     djm      2800:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2801:                unlink(options.control_path);
1.223     djm      2802:        ssh_kill_proxy_command();
1.114     markus   2803:        _exit(i);
1.1       deraadt  2804: }