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

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