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

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