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

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