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

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