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

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