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

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