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

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