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

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