[BACK]Return to mux.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/mux.c, Revision 1.35

1.35    ! djm         1: /* $OpenBSD: mux.c,v 1.34 2012/01/07 21:11:36 djm Exp $ */
1.1       djm         2: /*
                      3:  * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
                      4:  *
                      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
                      8:  *
                      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     16:  */
                     17:
                     18: /* ssh session multiplexing support */
                     19:
1.2       djm        20: /*
                     21:  * TODO:
1.10      djm        22:  *   - Better signalling from master to slave, especially passing of
1.2       djm        23:  *      error messages
1.10      djm        24:  *   - Better fall-back from mux slave error to new connection.
                     25:  *   - ExitOnForwardingFailure
                     26:  *   - Maybe extension mechanisms for multi-X11/multi-agent forwarding
                     27:  *   - Support ~^Z in mux slaves.
                     28:  *   - Inspect or control sessions in master.
                     29:  *   - If we ever support the "signal" channel request, send signals on
                     30:  *     sessions in master.
1.2       djm        31:  */
                     32:
1.1       djm        33: #include <sys/types.h>
                     34: #include <sys/param.h>
                     35: #include <sys/queue.h>
                     36: #include <sys/stat.h>
                     37: #include <sys/socket.h>
                     38: #include <sys/un.h>
                     39:
                     40: #include <errno.h>
                     41: #include <fcntl.h>
1.10      djm        42: #include <poll.h>
1.1       djm        43: #include <signal.h>
                     44: #include <stdarg.h>
                     45: #include <stddef.h>
                     46: #include <stdlib.h>
                     47: #include <stdio.h>
                     48: #include <string.h>
                     49: #include <unistd.h>
                     50: #include <util.h>
                     51: #include <paths.h>
                     52:
1.10      djm        53: #include "atomicio.h"
1.1       djm        54: #include "xmalloc.h"
                     55: #include "log.h"
                     56: #include "ssh.h"
1.18      markus     57: #include "ssh2.h"
1.1       djm        58: #include "pathnames.h"
                     59: #include "misc.h"
                     60: #include "match.h"
                     61: #include "buffer.h"
                     62: #include "channels.h"
                     63: #include "msg.h"
                     64: #include "packet.h"
                     65: #include "monitor_fdpass.h"
                     66: #include "sshpty.h"
                     67: #include "key.h"
                     68: #include "readconf.h"
                     69: #include "clientloop.h"
                     70:
                     71: /* from ssh.c */
                     72: extern int tty_flag;
                     73: extern Options options;
                     74: extern int stdin_null_flag;
                     75: extern char *host;
1.8       dtucker    76: extern int subsystem_flag;
1.1       djm        77: extern Buffer command;
1.10      djm        78: extern volatile sig_atomic_t quit_pending;
                     79: extern char *stdio_forward_host;
                     80: extern int stdio_forward_port;
1.1       djm        81:
1.2       djm        82: /* Context for session open confirmation callback */
                     83: struct mux_session_confirm_ctx {
1.10      djm        84:        u_int want_tty;
                     85:        u_int want_subsys;
                     86:        u_int want_x_fwd;
                     87:        u_int want_agent_fwd;
1.2       djm        88:        Buffer cmd;
                     89:        char *term;
                     90:        struct termios tio;
                     91:        char **env;
1.17      djm        92:        u_int rid;
1.2       djm        93: };
                     94:
1.18      markus     95: /* Context for global channel callback */
                     96: struct mux_channel_confirm_ctx {
                     97:        u_int cid;      /* channel id */
                     98:        u_int rid;      /* request id */
                     99:        int fid;        /* forward id */
                    100: };
                    101:
1.1       djm       102: /* fd to control socket */
                    103: int muxserver_sock = -1;
                    104:
1.10      djm       105: /* client request id */
                    106: u_int muxclient_request_id = 0;
                    107:
1.1       djm       108: /* Multiplexing control command */
                    109: u_int muxclient_command = 0;
                    110:
                    111: /* Set when signalled. */
                    112: static volatile sig_atomic_t muxclient_terminate = 0;
                    113:
                    114: /* PID of multiplex server */
                    115: static u_int muxserver_pid = 0;
                    116:
1.10      djm       117: static Channel *mux_listener_channel = NULL;
                    118:
                    119: struct mux_master_state {
                    120:        int hello_rcvd;
                    121: };
1.1       djm       122:
1.10      djm       123: /* mux protocol messages */
                    124: #define MUX_MSG_HELLO          0x00000001
                    125: #define MUX_C_NEW_SESSION      0x10000002
                    126: #define MUX_C_ALIVE_CHECK      0x10000004
                    127: #define MUX_C_TERMINATE                0x10000005
                    128: #define MUX_C_OPEN_FWD         0x10000006
                    129: #define MUX_C_CLOSE_FWD                0x10000007
                    130: #define MUX_C_NEW_STDIO_FWD    0x10000008
1.25      djm       131: #define MUX_C_STOP_LISTENING   0x10000009
1.10      djm       132: #define MUX_S_OK               0x80000001
                    133: #define MUX_S_PERMISSION_DENIED        0x80000002
                    134: #define MUX_S_FAILURE          0x80000003
                    135: #define MUX_S_EXIT_MESSAGE     0x80000004
                    136: #define MUX_S_ALIVE            0x80000005
                    137: #define MUX_S_SESSION_OPENED   0x80000006
1.18      markus    138: #define MUX_S_REMOTE_PORT      0x80000007
1.28      djm       139: #define MUX_S_TTY_ALLOC_FAIL   0x80000008
1.10      djm       140:
                    141: /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
                    142: #define MUX_FWD_LOCAL   1
                    143: #define MUX_FWD_REMOTE  2
                    144: #define MUX_FWD_DYNAMIC 3
                    145:
1.17      djm       146: static void mux_session_confirm(int, int, void *);
1.10      djm       147:
                    148: static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
                    149: static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
                    150: static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
                    151: static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
                    152: static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
                    153: static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
                    154: static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
1.25      djm       155: static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
1.10      djm       156:
                    157: static const struct {
                    158:        u_int type;
                    159:        int (*handler)(u_int, Channel *, Buffer *, Buffer *);
                    160: } mux_master_handlers[] = {
                    161:        { MUX_MSG_HELLO, process_mux_master_hello },
                    162:        { MUX_C_NEW_SESSION, process_mux_new_session },
                    163:        { MUX_C_ALIVE_CHECK, process_mux_alive_check },
                    164:        { MUX_C_TERMINATE, process_mux_terminate },
                    165:        { MUX_C_OPEN_FWD, process_mux_open_fwd },
                    166:        { MUX_C_CLOSE_FWD, process_mux_close_fwd },
                    167:        { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
1.25      djm       168:        { MUX_C_STOP_LISTENING, process_mux_stop_listening },
1.10      djm       169:        { 0, NULL }
                    170: };
1.1       djm       171:
1.10      djm       172: /* Cleanup callback fired on closure of mux slave _session_ channel */
                    173: /* ARGSUSED */
                    174: static void
                    175: mux_master_session_cleanup_cb(int cid, void *unused)
1.1       djm       176: {
1.10      djm       177:        Channel *cc, *c = channel_by_id(cid);
1.1       djm       178:
1.10      djm       179:        debug3("%s: entering for channel %d", __func__, cid);
                    180:        if (c == NULL)
                    181:                fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
                    182:        if (c->ctl_chan != -1) {
                    183:                if ((cc = channel_by_id(c->ctl_chan)) == NULL)
                    184:                        fatal("%s: channel %d missing control channel %d",
                    185:                            __func__, c->self, c->ctl_chan);
                    186:                c->ctl_chan = -1;
                    187:                cc->remote_id = -1;
                    188:                chan_rcvd_oclose(cc);
1.1       djm       189:        }
1.10      djm       190:        channel_cancel_cleanup(c->self);
1.1       djm       191: }
                    192:
1.10      djm       193: /* Cleanup callback fired on closure of mux slave _control_ channel */
                    194: /* ARGSUSED */
1.1       djm       195: static void
1.10      djm       196: mux_master_control_cleanup_cb(int cid, void *unused)
1.1       djm       197: {
1.10      djm       198:        Channel *sc, *c = channel_by_id(cid);
1.1       djm       199:
1.10      djm       200:        debug3("%s: entering for channel %d", __func__, cid);
                    201:        if (c == NULL)
                    202:                fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
                    203:        if (c->remote_id != -1) {
                    204:                if ((sc = channel_by_id(c->remote_id)) == NULL)
1.15      djm       205:                        fatal("%s: channel %d missing session channel %d",
1.10      djm       206:                            __func__, c->self, c->remote_id);
                    207:                c->remote_id = -1;
                    208:                sc->ctl_chan = -1;
1.12      djm       209:                if (sc->type != SSH_CHANNEL_OPEN) {
                    210:                        debug2("%s: channel %d: not open", __func__, sc->self);
1.13      djm       211:                        chan_mark_dead(sc);
1.12      djm       212:                } else {
1.14      djm       213:                        if (sc->istate == CHAN_INPUT_OPEN)
                    214:                                chan_read_failed(sc);
                    215:                        if (sc->ostate == CHAN_OUTPUT_OPEN)
                    216:                                chan_write_failed(sc);
1.12      djm       217:                }
1.1       djm       218:        }
1.10      djm       219:        channel_cancel_cleanup(c->self);
1.1       djm       220: }
                    221:
1.10      djm       222: /* Check mux client environment variables before passing them to mux master. */
                    223: static int
                    224: env_permitted(char *env)
1.1       djm       225: {
1.10      djm       226:        int i, ret;
                    227:        char name[1024], *cp;
1.1       djm       228:
1.10      djm       229:        if ((cp = strchr(env, '=')) == NULL || cp == env)
1.1       djm       230:                return 0;
1.10      djm       231:        ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
                    232:        if (ret <= 0 || (size_t)ret >= sizeof(name)) {
                    233:                error("env_permitted: name '%.100s...' too long", env);
1.1       djm       234:                return 0;
                    235:        }
                    236:
1.10      djm       237:        for (i = 0; i < options.num_send_env; i++)
                    238:                if (match_pattern(name, options.send_env[i]))
                    239:                        return 1;
1.1       djm       240:
1.10      djm       241:        return 0;
                    242: }
1.1       djm       243:
1.10      djm       244: /* Mux master protocol message handlers */
1.1       djm       245:
1.10      djm       246: static int
                    247: process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    248: {
                    249:        u_int ver;
                    250:        struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1.1       djm       251:
1.10      djm       252:        if (state == NULL)
                    253:                fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
                    254:        if (state->hello_rcvd) {
                    255:                error("%s: HELLO received twice", __func__);
                    256:                return -1;
                    257:        }
                    258:        if (buffer_get_int_ret(&ver, m) != 0) {
                    259:  malf:
                    260:                error("%s: malformed message", __func__);
                    261:                return -1;
                    262:        }
                    263:        if (ver != SSHMUX_VER) {
                    264:                error("Unsupported multiplexing protocol version %d "
                    265:                    "(expected %d)", ver, SSHMUX_VER);
                    266:                return -1;
                    267:        }
                    268:        debug2("%s: channel %d slave version %u", __func__, c->self, ver);
                    269:
                    270:        /* No extensions are presently defined */
                    271:        while (buffer_len(m) > 0) {
                    272:                char *name = buffer_get_string_ret(m, NULL);
                    273:                char *value = buffer_get_string_ret(m, NULL);
                    274:
                    275:                if (name == NULL || value == NULL) {
                    276:                        if (name != NULL)
                    277:                                xfree(name);
                    278:                        goto malf;
1.1       djm       279:                }
1.10      djm       280:                debug2("Unrecognised slave extension \"%s\"", name);
                    281:                xfree(name);
                    282:                xfree(value);
1.1       djm       283:        }
1.10      djm       284:        state->hello_rcvd = 1;
                    285:        return 0;
                    286: }
                    287:
                    288: static int
                    289: process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    290: {
                    291:        Channel *nc;
                    292:        struct mux_session_confirm_ctx *cctx;
                    293:        char *reserved, *cmd, *cp;
                    294:        u_int i, j, len, env_len, escape_char, window, packetmax;
                    295:        int new_fd[3];
1.1       djm       296:
                    297:        /* Reply for SSHMUX_COMMAND_OPEN */
1.10      djm       298:        cctx = xcalloc(1, sizeof(*cctx));
                    299:        cctx->term = NULL;
1.17      djm       300:        cctx->rid = rid;
1.11      djm       301:        cmd = reserved = NULL;
1.10      djm       302:        if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
                    303:            buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
                    304:            buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
                    305:            buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
                    306:            buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
                    307:            buffer_get_int_ret(&escape_char, m) != 0 ||
                    308:            (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
                    309:            (cmd = buffer_get_string_ret(m, &len)) == NULL) {
                    310:  malf:
1.11      djm       311:                if (cmd != NULL)
                    312:                        xfree(cmd);
                    313:                if (reserved != NULL)
                    314:                        xfree(reserved);
1.10      djm       315:                if (cctx->term != NULL)
                    316:                        xfree(cctx->term);
                    317:                error("%s: malformed message", __func__);
                    318:                return -1;
1.1       djm       319:        }
1.10      djm       320:        xfree(reserved);
1.11      djm       321:        reserved = NULL;
1.1       djm       322:
1.10      djm       323:        cctx->env = NULL;
                    324:        env_len = 0;
                    325:        while (buffer_len(m) > 0) {
                    326: #define MUX_MAX_ENV_VARS       4096
1.34      djm       327:                if ((cp = buffer_get_string_ret(m, &len)) == NULL)
1.10      djm       328:                        goto malf;
                    329:                if (!env_permitted(cp)) {
                    330:                        xfree(cp);
                    331:                        continue;
                    332:                }
                    333:                cctx->env = xrealloc(cctx->env, env_len + 2,
                    334:                    sizeof(*cctx->env));
                    335:                cctx->env[env_len++] = cp;
                    336:                cctx->env[env_len] = NULL;
                    337:                if (env_len > MUX_MAX_ENV_VARS) {
                    338:                        error(">%d environment variables received, ignoring "
                    339:                            "additional", MUX_MAX_ENV_VARS);
                    340:                        break;
                    341:                }
1.1       djm       342:        }
                    343:
1.10      djm       344:        debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
                    345:            "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
                    346:            cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
                    347:            cctx->want_subsys, cctx->term, cmd, env_len);
1.1       djm       348:
                    349:        buffer_init(&cctx->cmd);
                    350:        buffer_append(&cctx->cmd, cmd, strlen(cmd));
                    351:        xfree(cmd);
1.11      djm       352:        cmd = NULL;
1.1       djm       353:
                    354:        /* Gather fds from client */
                    355:        for(i = 0; i < 3; i++) {
1.10      djm       356:                if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
1.1       djm       357:                        error("%s: failed to receive fd %d from slave",
                    358:                            __func__, i);
                    359:                        for (j = 0; j < i; j++)
                    360:                                close(new_fd[j]);
                    361:                        for (j = 0; j < env_len; j++)
                    362:                                xfree(cctx->env[j]);
                    363:                        if (env_len > 0)
                    364:                                xfree(cctx->env);
                    365:                        xfree(cctx->term);
                    366:                        buffer_free(&cctx->cmd);
                    367:                        xfree(cctx);
1.10      djm       368:
                    369:                        /* prepare reply */
                    370:                        buffer_put_int(r, MUX_S_FAILURE);
                    371:                        buffer_put_int(r, rid);
                    372:                        buffer_put_cstring(r,
                    373:                            "did not receive file descriptors");
                    374:                        return -1;
1.1       djm       375:                }
                    376:        }
                    377:
1.10      djm       378:        debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
1.1       djm       379:            new_fd[0], new_fd[1], new_fd[2]);
                    380:
1.10      djm       381:        /* XXX support multiple child sessions in future */
                    382:        if (c->remote_id != -1) {
                    383:                debug2("%s: session already open", __func__);
                    384:                /* prepare reply */
                    385:                buffer_put_int(r, MUX_S_FAILURE);
                    386:                buffer_put_int(r, rid);
                    387:                buffer_put_cstring(r, "Multiple sessions not supported");
                    388:  cleanup:
1.1       djm       389:                close(new_fd[0]);
                    390:                close(new_fd[1]);
                    391:                close(new_fd[2]);
                    392:                xfree(cctx->term);
                    393:                if (env_len != 0) {
                    394:                        for (i = 0; i < env_len; i++)
                    395:                                xfree(cctx->env[i]);
                    396:                        xfree(cctx->env);
                    397:                }
1.10      djm       398:                buffer_free(&cctx->cmd);
1.1       djm       399:                return 0;
                    400:        }
1.10      djm       401:
                    402:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    403:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
                    404:                if (!ask_permission("Allow shared connection to %s? ", host)) {
                    405:                        debug2("%s: session refused by user", __func__);
                    406:                        /* prepare reply */
                    407:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    408:                        buffer_put_int(r, rid);
                    409:                        buffer_put_cstring(r, "Permission denied");
                    410:                        goto cleanup;
                    411:                }
                    412:        }
                    413:
                    414:        /* Try to pick up ttymodes from client before it goes raw */
                    415:        if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
                    416:                error("%s: tcgetattr: %s", __func__, strerror(errno));
1.1       djm       417:
                    418:        /* enable nonblocking unless tty */
                    419:        if (!isatty(new_fd[0]))
                    420:                set_nonblock(new_fd[0]);
                    421:        if (!isatty(new_fd[1]))
                    422:                set_nonblock(new_fd[1]);
                    423:        if (!isatty(new_fd[2]))
                    424:                set_nonblock(new_fd[2]);
                    425:
                    426:        window = CHAN_SES_WINDOW_DEFAULT;
                    427:        packetmax = CHAN_SES_PACKET_DEFAULT;
                    428:        if (cctx->want_tty) {
                    429:                window >>= 1;
                    430:                packetmax >>= 1;
                    431:        }
1.10      djm       432:
                    433:        nc = channel_new("session", SSH_CHANNEL_OPENING,
1.1       djm       434:            new_fd[0], new_fd[1], new_fd[2], window, packetmax,
                    435:            CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
                    436:
1.10      djm       437:        nc->ctl_chan = c->self;         /* link session -> control channel */
                    438:        c->remote_id = nc->self;        /* link control -> session channel */
                    439:
1.2       djm       440:        if (cctx->want_tty && escape_char != 0xffffffff) {
1.10      djm       441:                channel_register_filter(nc->self,
1.2       djm       442:                    client_simple_escape_filter, NULL,
1.4       djm       443:                    client_filter_cleanup,
1.2       djm       444:                    client_new_escape_filter_ctx((int)escape_char));
                    445:        }
1.1       djm       446:
1.10      djm       447:        debug2("%s: channel_new: %d linked to control channel %d",
                    448:            __func__, nc->self, nc->ctl_chan);
                    449:
                    450:        channel_send_open(nc->self);
                    451:        channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
1.17      djm       452:        c->mux_pause = 1; /* stop handling messages until open_confirm done */
1.16      djm       453:        channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1.10      djm       454:
1.17      djm       455:        /* reply is deferred, sent by mux_session_confirm */
1.1       djm       456:        return 0;
                    457: }
                    458:
1.10      djm       459: static int
                    460: process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
1.1       djm       461: {
1.10      djm       462:        debug2("%s: channel %d: alive check", __func__, c->self);
1.1       djm       463:
1.10      djm       464:        /* prepare reply */
                    465:        buffer_put_int(r, MUX_S_ALIVE);
                    466:        buffer_put_int(r, rid);
                    467:        buffer_put_int(r, (u_int)getpid());
1.1       djm       468:
1.10      djm       469:        return 0;
1.1       djm       470: }
                    471:
                    472: static int
1.10      djm       473: process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
1.1       djm       474: {
1.10      djm       475:        debug2("%s: channel %d: terminate request", __func__, c->self);
1.1       djm       476:
1.10      djm       477:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    478:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
                    479:                if (!ask_permission("Terminate shared connection to %s? ",
                    480:                    host)) {
                    481:                        debug2("%s: termination refused by user", __func__);
                    482:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    483:                        buffer_put_int(r, rid);
                    484:                        buffer_put_cstring(r, "Permission denied");
                    485:                        return 0;
                    486:                }
                    487:        }
1.1       djm       488:
1.10      djm       489:        quit_pending = 1;
                    490:        buffer_put_int(r, MUX_S_OK);
                    491:        buffer_put_int(r, rid);
                    492:        /* XXX exit happens too soon - message never makes it to client */
                    493:        return 0;
1.1       djm       494: }
                    495:
1.10      djm       496: static char *
                    497: format_forward(u_int ftype, Forward *fwd)
1.1       djm       498: {
1.10      djm       499:        char *ret;
1.1       djm       500:
1.10      djm       501:        switch (ftype) {
                    502:        case MUX_FWD_LOCAL:
                    503:                xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
                    504:                    (fwd->listen_host == NULL) ?
                    505:                    (options.gateway_ports ? "*" : "LOCALHOST") :
                    506:                    fwd->listen_host, fwd->listen_port,
                    507:                    fwd->connect_host, fwd->connect_port);
                    508:                break;
                    509:        case MUX_FWD_DYNAMIC:
                    510:                xasprintf(&ret, "dynamic forward %.200s:%d -> *",
                    511:                    (fwd->listen_host == NULL) ?
                    512:                    (options.gateway_ports ? "*" : "LOCALHOST") :
                    513:                     fwd->listen_host, fwd->listen_port);
                    514:                break;
                    515:        case MUX_FWD_REMOTE:
                    516:                xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
                    517:                    (fwd->listen_host == NULL) ?
                    518:                    "LOCALHOST" : fwd->listen_host,
                    519:                    fwd->listen_port,
                    520:                    fwd->connect_host, fwd->connect_port);
1.1       djm       521:                break;
                    522:        default:
1.10      djm       523:                fatal("%s: unknown forward type %u", __func__, ftype);
1.1       djm       524:        }
1.10      djm       525:        return ret;
                    526: }
1.1       djm       527:
1.10      djm       528: static int
                    529: compare_host(const char *a, const char *b)
                    530: {
                    531:        if (a == NULL && b == NULL)
                    532:                return 1;
                    533:        if (a == NULL || b == NULL)
                    534:                return 0;
                    535:        return strcmp(a, b) == 0;
                    536: }
1.1       djm       537:
1.10      djm       538: static int
                    539: compare_forward(Forward *a, Forward *b)
                    540: {
                    541:        if (!compare_host(a->listen_host, b->listen_host))
                    542:                return 0;
                    543:        if (a->listen_port != b->listen_port)
                    544:                return 0;
                    545:        if (!compare_host(a->connect_host, b->connect_host))
                    546:                return 0;
                    547:        if (a->connect_port != b->connect_port)
                    548:                return 0;
1.1       djm       549:
1.10      djm       550:        return 1;
                    551: }
1.1       djm       552:
1.18      markus    553: static void
                    554: mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                    555: {
                    556:        struct mux_channel_confirm_ctx *fctx = ctxt;
                    557:        char *failmsg = NULL;
                    558:        Forward *rfwd;
                    559:        Channel *c;
                    560:        Buffer out;
                    561:
                    562:        if ((c = channel_by_id(fctx->cid)) == NULL) {
                    563:                /* no channel for reply */
                    564:                error("%s: unknown channel", __func__);
                    565:                return;
                    566:        }
                    567:        buffer_init(&out);
                    568:        if (fctx->fid >= options.num_remote_forwards) {
                    569:                xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
                    570:                goto fail;
                    571:        }
                    572:        rfwd = &options.remote_forwards[fctx->fid];
                    573:        debug("%s: %s for: listen %d, connect %s:%d", __func__,
                    574:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                    575:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
                    576:        if (type == SSH2_MSG_REQUEST_SUCCESS) {
                    577:                if (rfwd->listen_port == 0) {
                    578:                        rfwd->allocated_port = packet_get_int();
                    579:                        logit("Allocated port %u for mux remote forward"
                    580:                            " to %s:%d", rfwd->allocated_port,
                    581:                            rfwd->connect_host, rfwd->connect_port);
                    582:                        buffer_put_int(&out, MUX_S_REMOTE_PORT);
                    583:                        buffer_put_int(&out, fctx->rid);
                    584:                        buffer_put_int(&out, rfwd->allocated_port);
1.31      markus    585:                        channel_update_permitted_opens(rfwd->handle,
                    586:                           rfwd->allocated_port);
1.18      markus    587:                } else {
                    588:                        buffer_put_int(&out, MUX_S_OK);
                    589:                        buffer_put_int(&out, fctx->rid);
                    590:                }
                    591:                goto out;
                    592:        } else {
1.31      markus    593:                if (rfwd->listen_port == 0)
                    594:                        channel_update_permitted_opens(rfwd->handle, -1);
1.18      markus    595:                xasprintf(&failmsg, "remote port forwarding failed for "
                    596:                    "listen port %d", rfwd->listen_port);
                    597:        }
                    598:  fail:
                    599:        error("%s: %s", __func__, failmsg);
                    600:        buffer_put_int(&out, MUX_S_FAILURE);
                    601:        buffer_put_int(&out, fctx->rid);
                    602:        buffer_put_cstring(&out, failmsg);
                    603:        xfree(failmsg);
                    604:  out:
                    605:        buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
                    606:        buffer_free(&out);
                    607:        if (c->mux_pause <= 0)
                    608:                fatal("%s: mux_pause %d", __func__, c->mux_pause);
                    609:        c->mux_pause = 0; /* start processing messages again */
                    610: }
                    611:
1.10      djm       612: static int
                    613: process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    614: {
                    615:        Forward fwd;
                    616:        char *fwd_desc = NULL;
                    617:        u_int ftype;
                    618:        int i, ret = 0, freefwd = 1;
                    619:
                    620:        fwd.listen_host = fwd.connect_host = NULL;
                    621:        if (buffer_get_int_ret(&ftype, m) != 0 ||
                    622:            (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    623:            buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
                    624:            (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    625:            buffer_get_int_ret(&fwd.connect_port, m) != 0) {
                    626:                error("%s: malformed message", __func__);
                    627:                ret = -1;
                    628:                goto out;
                    629:        }
                    630:
                    631:        if (*fwd.listen_host == '\0') {
                    632:                xfree(fwd.listen_host);
                    633:                fwd.listen_host = NULL;
                    634:        }
                    635:        if (*fwd.connect_host == '\0') {
                    636:                xfree(fwd.connect_host);
                    637:                fwd.connect_host = NULL;
                    638:        }
                    639:
                    640:        debug2("%s: channel %d: request %s", __func__, c->self,
                    641:            (fwd_desc = format_forward(ftype, &fwd)));
                    642:
                    643:        if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
                    644:            ftype != MUX_FWD_DYNAMIC) {
                    645:                logit("%s: invalid forwarding type %u", __func__, ftype);
                    646:  invalid:
1.18      markus    647:                if (fwd.listen_host)
                    648:                        xfree(fwd.listen_host);
                    649:                if (fwd.connect_host)
                    650:                        xfree(fwd.connect_host);
1.10      djm       651:                buffer_put_int(r, MUX_S_FAILURE);
                    652:                buffer_put_int(r, rid);
                    653:                buffer_put_cstring(r, "Invalid forwarding request");
                    654:                return 0;
                    655:        }
1.18      markus    656:        if (fwd.listen_port >= 65536) {
1.10      djm       657:                logit("%s: invalid listen port %u", __func__,
                    658:                    fwd.listen_port);
                    659:                goto invalid;
                    660:        }
                    661:        if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
                    662:            ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
                    663:                logit("%s: invalid connect port %u", __func__,
                    664:                    fwd.connect_port);
                    665:                goto invalid;
                    666:        }
                    667:        if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
                    668:                logit("%s: missing connect host", __func__);
                    669:                goto invalid;
                    670:        }
                    671:
                    672:        /* Skip forwards that have already been requested */
                    673:        switch (ftype) {
                    674:        case MUX_FWD_LOCAL:
                    675:        case MUX_FWD_DYNAMIC:
                    676:                for (i = 0; i < options.num_local_forwards; i++) {
                    677:                        if (compare_forward(&fwd,
                    678:                            options.local_forwards + i)) {
                    679:  exists:
                    680:                                debug2("%s: found existing forwarding",
                    681:                                    __func__);
                    682:                                buffer_put_int(r, MUX_S_OK);
                    683:                                buffer_put_int(r, rid);
                    684:                                goto out;
                    685:                        }
                    686:                }
                    687:                break;
                    688:        case MUX_FWD_REMOTE:
                    689:                for (i = 0; i < options.num_remote_forwards; i++) {
                    690:                        if (compare_forward(&fwd,
1.18      markus    691:                            options.remote_forwards + i)) {
                    692:                                if (fwd.listen_port != 0)
                    693:                                        goto exists;
                    694:                                debug2("%s: found allocated port",
                    695:                                    __func__);
                    696:                                buffer_put_int(r, MUX_S_REMOTE_PORT);
                    697:                                buffer_put_int(r, rid);
                    698:                                buffer_put_int(r,
                    699:                                    options.remote_forwards[i].allocated_port);
                    700:                                goto out;
                    701:                        }
1.10      djm       702:                }
                    703:                break;
                    704:        }
                    705:
                    706:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    707:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
                    708:                if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
                    709:                        debug2("%s: forwarding refused by user", __func__);
                    710:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    711:                        buffer_put_int(r, rid);
                    712:                        buffer_put_cstring(r, "Permission denied");
                    713:                        goto out;
                    714:                }
                    715:        }
                    716:
                    717:        if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
1.20      djm       718:                if (channel_setup_local_fwd_listener(fwd.listen_host,
1.10      djm       719:                    fwd.listen_port, fwd.connect_host, fwd.connect_port,
                    720:                    options.gateway_ports) < 0) {
                    721:  fail:
                    722:                        logit("slave-requested %s failed", fwd_desc);
                    723:                        buffer_put_int(r, MUX_S_FAILURE);
                    724:                        buffer_put_int(r, rid);
                    725:                        buffer_put_cstring(r, "Port forwarding failed");
                    726:                        goto out;
                    727:                }
                    728:                add_local_forward(&options, &fwd);
                    729:                freefwd = 0;
                    730:        } else {
1.18      markus    731:                struct mux_channel_confirm_ctx *fctx;
                    732:
1.31      markus    733:                fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
                    734:                    fwd.listen_port, fwd.connect_host, fwd.connect_port);
                    735:                if (fwd.handle < 0)
1.10      djm       736:                        goto fail;
                    737:                add_remote_forward(&options, &fwd);
1.18      markus    738:                fctx = xcalloc(1, sizeof(*fctx));
                    739:                fctx->cid = c->self;
                    740:                fctx->rid = rid;
1.20      djm       741:                fctx->fid = options.num_remote_forwards - 1;
1.18      markus    742:                client_register_global_confirm(mux_confirm_remote_forward,
                    743:                    fctx);
1.10      djm       744:                freefwd = 0;
1.18      markus    745:                c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
                    746:                /* delayed reply in mux_confirm_remote_forward */
                    747:                goto out;
1.10      djm       748:        }
                    749:        buffer_put_int(r, MUX_S_OK);
                    750:        buffer_put_int(r, rid);
                    751:  out:
                    752:        if (fwd_desc != NULL)
                    753:                xfree(fwd_desc);
                    754:        if (freefwd) {
                    755:                if (fwd.listen_host != NULL)
                    756:                        xfree(fwd.listen_host);
                    757:                if (fwd.connect_host != NULL)
                    758:                        xfree(fwd.connect_host);
                    759:        }
                    760:        return ret;
                    761: }
                    762:
                    763: static int
                    764: process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    765: {
1.30      djm       766:        Forward fwd, *found_fwd;
1.10      djm       767:        char *fwd_desc = NULL;
1.30      djm       768:        const char *error_reason = NULL;
1.10      djm       769:        u_int ftype;
1.31      markus    770:        int i, listen_port, ret = 0;
1.10      djm       771:
                    772:        fwd.listen_host = fwd.connect_host = NULL;
                    773:        if (buffer_get_int_ret(&ftype, m) != 0 ||
                    774:            (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    775:            buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
                    776:            (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    777:            buffer_get_int_ret(&fwd.connect_port, m) != 0) {
                    778:                error("%s: malformed message", __func__);
                    779:                ret = -1;
                    780:                goto out;
                    781:        }
                    782:
                    783:        if (*fwd.listen_host == '\0') {
                    784:                xfree(fwd.listen_host);
                    785:                fwd.listen_host = NULL;
                    786:        }
                    787:        if (*fwd.connect_host == '\0') {
                    788:                xfree(fwd.connect_host);
                    789:                fwd.connect_host = NULL;
                    790:        }
                    791:
1.30      djm       792:        debug2("%s: channel %d: request cancel %s", __func__, c->self,
1.10      djm       793:            (fwd_desc = format_forward(ftype, &fwd)));
                    794:
1.30      djm       795:        /* make sure this has been requested */
                    796:        found_fwd = NULL;
                    797:        switch (ftype) {
                    798:        case MUX_FWD_LOCAL:
                    799:        case MUX_FWD_DYNAMIC:
                    800:                for (i = 0; i < options.num_local_forwards; i++) {
                    801:                        if (compare_forward(&fwd,
                    802:                            options.local_forwards + i)) {
                    803:                                found_fwd = options.local_forwards + i;
                    804:                                break;
                    805:                        }
                    806:                }
                    807:                break;
                    808:        case MUX_FWD_REMOTE:
                    809:                for (i = 0; i < options.num_remote_forwards; i++) {
                    810:                        if (compare_forward(&fwd,
                    811:                            options.remote_forwards + i)) {
                    812:                                found_fwd = options.remote_forwards + i;
                    813:                                break;
                    814:                        }
                    815:                }
                    816:                break;
                    817:        }
                    818:
                    819:        if (found_fwd == NULL)
                    820:                error_reason = "port not forwarded";
                    821:        else if (ftype == MUX_FWD_REMOTE) {
                    822:                /*
                    823:                 * This shouldn't fail unless we confused the host/port
                    824:                 * between options.remote_forwards and permitted_opens.
1.31      markus    825:                 * However, for dynamic allocated listen ports we need
                    826:                 * to lookup the actual listen port.
1.30      djm       827:                 */
1.31      markus    828:                listen_port = (fwd.listen_port == 0) ?
                    829:                    found_fwd->allocated_port : fwd.listen_port;
1.30      djm       830:                if (channel_request_rforward_cancel(fwd.listen_host,
1.31      markus    831:                    listen_port) == -1)
1.30      djm       832:                        error_reason = "port not in permitted opens";
                    833:        } else {        /* local and dynamic forwards */
                    834:                /* Ditto */
                    835:                if (channel_cancel_lport_listener(fwd.listen_host,
                    836:                    fwd.listen_port, fwd.connect_port,
                    837:                    options.gateway_ports) == -1)
                    838:                        error_reason = "port not found";
                    839:        }
                    840:
                    841:        if (error_reason == NULL) {
                    842:                buffer_put_int(r, MUX_S_OK);
                    843:                buffer_put_int(r, rid);
1.10      djm       844:
1.30      djm       845:                if (found_fwd->listen_host != NULL)
                    846:                        xfree(found_fwd->listen_host);
                    847:                if (found_fwd->connect_host != NULL)
                    848:                        xfree(found_fwd->connect_host);
                    849:                found_fwd->listen_host = found_fwd->connect_host = NULL;
                    850:                found_fwd->listen_port = found_fwd->connect_port = 0;
                    851:        } else {
                    852:                buffer_put_int(r, MUX_S_FAILURE);
                    853:                buffer_put_int(r, rid);
                    854:                buffer_put_cstring(r, error_reason);
                    855:        }
1.10      djm       856:  out:
                    857:        if (fwd_desc != NULL)
                    858:                xfree(fwd_desc);
                    859:        if (fwd.listen_host != NULL)
                    860:                xfree(fwd.listen_host);
                    861:        if (fwd.connect_host != NULL)
                    862:                xfree(fwd.connect_host);
                    863:
                    864:        return ret;
                    865: }
                    866:
                    867: static int
                    868: process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    869: {
                    870:        Channel *nc;
                    871:        char *reserved, *chost;
                    872:        u_int cport, i, j;
                    873:        int new_fd[2];
                    874:
1.11      djm       875:        chost = reserved = NULL;
1.10      djm       876:        if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
                    877:           (chost = buffer_get_string_ret(m, NULL)) == NULL ||
                    878:            buffer_get_int_ret(&cport, m) != 0) {
1.11      djm       879:                if (reserved != NULL)
                    880:                        xfree(reserved);
1.10      djm       881:                if (chost != NULL)
                    882:                        xfree(chost);
                    883:                error("%s: malformed message", __func__);
                    884:                return -1;
                    885:        }
                    886:        xfree(reserved);
                    887:
                    888:        debug2("%s: channel %d: request stdio fwd to %s:%u",
                    889:            __func__, c->self, chost, cport);
                    890:
                    891:        /* Gather fds from client */
                    892:        for(i = 0; i < 2; i++) {
                    893:                if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
                    894:                        error("%s: failed to receive fd %d from slave",
                    895:                            __func__, i);
                    896:                        for (j = 0; j < i; j++)
                    897:                                close(new_fd[j]);
                    898:                        xfree(chost);
                    899:
                    900:                        /* prepare reply */
                    901:                        buffer_put_int(r, MUX_S_FAILURE);
                    902:                        buffer_put_int(r, rid);
                    903:                        buffer_put_cstring(r,
                    904:                            "did not receive file descriptors");
                    905:                        return -1;
                    906:                }
                    907:        }
                    908:
                    909:        debug3("%s: got fds stdin %d, stdout %d", __func__,
                    910:            new_fd[0], new_fd[1]);
                    911:
                    912:        /* XXX support multiple child sessions in future */
                    913:        if (c->remote_id != -1) {
                    914:                debug2("%s: session already open", __func__);
                    915:                /* prepare reply */
                    916:                buffer_put_int(r, MUX_S_FAILURE);
                    917:                buffer_put_int(r, rid);
                    918:                buffer_put_cstring(r, "Multiple sessions not supported");
                    919:  cleanup:
                    920:                close(new_fd[0]);
                    921:                close(new_fd[1]);
                    922:                xfree(chost);
                    923:                return 0;
                    924:        }
                    925:
                    926:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    927:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1.23      dtucker   928:                if (!ask_permission("Allow forward to %s:%u? ",
1.10      djm       929:                    chost, cport)) {
                    930:                        debug2("%s: stdio fwd refused by user", __func__);
                    931:                        /* prepare reply */
                    932:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    933:                        buffer_put_int(r, rid);
                    934:                        buffer_put_cstring(r, "Permission denied");
                    935:                        goto cleanup;
                    936:                }
                    937:        }
                    938:
                    939:        /* enable nonblocking unless tty */
                    940:        if (!isatty(new_fd[0]))
                    941:                set_nonblock(new_fd[0]);
                    942:        if (!isatty(new_fd[1]))
                    943:                set_nonblock(new_fd[1]);
                    944:
                    945:        nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
                    946:
                    947:        nc->ctl_chan = c->self;         /* link session -> control channel */
                    948:        c->remote_id = nc->self;        /* link control -> session channel */
                    949:
                    950:        debug2("%s: channel_new: %d linked to control channel %d",
                    951:            __func__, nc->self, nc->ctl_chan);
                    952:
1.16      djm       953:        channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1.10      djm       954:
                    955:        /* prepare reply */
                    956:        /* XXX defer until channel confirmed */
                    957:        buffer_put_int(r, MUX_S_SESSION_OPENED);
                    958:        buffer_put_int(r, rid);
                    959:        buffer_put_int(r, nc->self);
                    960:
                    961:        return 0;
                    962: }
                    963:
1.25      djm       964: static int
                    965: process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    966: {
                    967:        debug("%s: channel %d: stop listening", __func__, c->self);
                    968:
                    969:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    970:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
                    971:                if (!ask_permission("Disable further multiplexing on shared "
                    972:                    "connection to %s? ", host)) {
                    973:                        debug2("%s: stop listen refused by user", __func__);
                    974:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    975:                        buffer_put_int(r, rid);
                    976:                        buffer_put_cstring(r, "Permission denied");
                    977:                        return 0;
                    978:                }
                    979:        }
                    980:
                    981:        if (mux_listener_channel != NULL) {
                    982:                channel_free(mux_listener_channel);
                    983:                client_stop_mux();
                    984:                xfree(options.control_path);
                    985:                options.control_path = NULL;
                    986:                mux_listener_channel = NULL;
                    987:                muxserver_sock = -1;
                    988:        }
                    989:
                    990:        /* prepare reply */
                    991:        buffer_put_int(r, MUX_S_OK);
                    992:        buffer_put_int(r, rid);
                    993:
                    994:        return 0;
                    995: }
                    996:
1.10      djm       997: /* Channel callbacks fired on read/write from mux slave fd */
                    998: static int
                    999: mux_master_read_cb(Channel *c)
                   1000: {
                   1001:        struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
                   1002:        Buffer in, out;
                   1003:        void *ptr;
                   1004:        u_int type, rid, have, i;
                   1005:        int ret = -1;
                   1006:
                   1007:        /* Setup ctx and  */
                   1008:        if (c->mux_ctx == NULL) {
1.19      djm      1009:                state = xcalloc(1, sizeof(*state));
1.10      djm      1010:                c->mux_ctx = state;
                   1011:                channel_register_cleanup(c->self,
                   1012:                    mux_master_control_cleanup_cb, 0);
                   1013:
                   1014:                /* Send hello */
                   1015:                buffer_init(&out);
                   1016:                buffer_put_int(&out, MUX_MSG_HELLO);
                   1017:                buffer_put_int(&out, SSHMUX_VER);
                   1018:                /* no extensions */
                   1019:                buffer_put_string(&c->output, buffer_ptr(&out),
                   1020:                    buffer_len(&out));
                   1021:                buffer_free(&out);
                   1022:                debug3("%s: channel %d: hello sent", __func__, c->self);
                   1023:                return 0;
                   1024:        }
                   1025:
                   1026:        buffer_init(&in);
                   1027:        buffer_init(&out);
                   1028:
                   1029:        /* Channel code ensures that we receive whole packets */
                   1030:        if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
                   1031:  malf:
                   1032:                error("%s: malformed message", __func__);
                   1033:                goto out;
                   1034:        }
                   1035:        buffer_append(&in, ptr, have);
                   1036:
                   1037:        if (buffer_get_int_ret(&type, &in) != 0)
                   1038:                goto malf;
                   1039:        debug3("%s: channel %d packet type 0x%08x len %u",
                   1040:            __func__, c->self, type, buffer_len(&in));
                   1041:
                   1042:        if (type == MUX_MSG_HELLO)
                   1043:                rid = 0;
                   1044:        else {
                   1045:                if (!state->hello_rcvd) {
                   1046:                        error("%s: expected MUX_MSG_HELLO(0x%08x), "
                   1047:                            "received 0x%08x", __func__, MUX_MSG_HELLO, type);
                   1048:                        goto out;
1.1       djm      1049:                }
1.10      djm      1050:                if (buffer_get_int_ret(&rid, &in) != 0)
                   1051:                        goto malf;
                   1052:        }
                   1053:
                   1054:        for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
                   1055:                if (type == mux_master_handlers[i].type) {
                   1056:                        ret = mux_master_handlers[i].handler(rid, c, &in, &out);
                   1057:                        break;
1.1       djm      1058:                }
1.10      djm      1059:        }
                   1060:        if (mux_master_handlers[i].handler == NULL) {
                   1061:                error("%s: unsupported mux message 0x%08x", __func__, type);
                   1062:                buffer_put_int(&out, MUX_S_FAILURE);
                   1063:                buffer_put_int(&out, rid);
                   1064:                buffer_put_cstring(&out, "unsupported request");
                   1065:                ret = 0;
                   1066:        }
                   1067:        /* Enqueue reply packet */
                   1068:        if (buffer_len(&out) != 0) {
                   1069:                buffer_put_string(&c->output, buffer_ptr(&out),
                   1070:                    buffer_len(&out));
                   1071:        }
                   1072:  out:
                   1073:        buffer_free(&in);
                   1074:        buffer_free(&out);
                   1075:        return ret;
                   1076: }
                   1077:
                   1078: void
                   1079: mux_exit_message(Channel *c, int exitval)
                   1080: {
                   1081:        Buffer m;
                   1082:        Channel *mux_chan;
                   1083:
                   1084:        debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
                   1085:            exitval);
                   1086:
                   1087:        if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
                   1088:                fatal("%s: channel %d missing mux channel %d",
                   1089:                    __func__, c->self, c->ctl_chan);
                   1090:
                   1091:        /* Append exit message packet to control socket output queue */
                   1092:        buffer_init(&m);
                   1093:        buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
                   1094:        buffer_put_int(&m, c->self);
                   1095:        buffer_put_int(&m, exitval);
                   1096:
                   1097:        buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
                   1098:        buffer_free(&m);
                   1099: }
                   1100:
1.28      djm      1101: void
                   1102: mux_tty_alloc_failed(Channel *c)
                   1103: {
                   1104:        Buffer m;
                   1105:        Channel *mux_chan;
                   1106:
                   1107:        debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
                   1108:
                   1109:        if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
                   1110:                fatal("%s: channel %d missing mux channel %d",
                   1111:                    __func__, c->self, c->ctl_chan);
                   1112:
                   1113:        /* Append exit message packet to control socket output queue */
                   1114:        buffer_init(&m);
                   1115:        buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
                   1116:        buffer_put_int(&m, c->self);
                   1117:
                   1118:        buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
                   1119:        buffer_free(&m);
                   1120: }
                   1121:
1.10      djm      1122: /* Prepare a mux master to listen on a Unix domain socket. */
                   1123: void
                   1124: muxserver_listen(void)
                   1125: {
                   1126:        struct sockaddr_un addr;
                   1127:        mode_t old_umask;
1.22      djm      1128:        char *orig_control_path = options.control_path;
                   1129:        char rbuf[16+1];
                   1130:        u_int i, r;
1.10      djm      1131:
                   1132:        if (options.control_path == NULL ||
                   1133:            options.control_master == SSHCTL_MASTER_NO)
1.1       djm      1134:                return;
1.10      djm      1135:
                   1136:        debug("setting up multiplex master socket");
                   1137:
1.22      djm      1138:        /*
                   1139:         * Use a temporary path before listen so we can pseudo-atomically
                   1140:         * establish the listening socket in its final location to avoid
                   1141:         * other processes racing in between bind() and listen() and hitting
                   1142:         * an unready socket.
                   1143:         */
                   1144:        for (i = 0; i < sizeof(rbuf) - 1; i++) {
                   1145:                r = arc4random_uniform(26+26+10);
                   1146:                rbuf[i] = (r < 26) ? 'a' + r :
                   1147:                    (r < 26*2) ? 'A' + r - 26 :
                   1148:                    '0' + r - 26 - 26;
                   1149:        }
                   1150:        rbuf[sizeof(rbuf) - 1] = '\0';
                   1151:        options.control_path = NULL;
                   1152:        xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
                   1153:        debug3("%s: temporary control path %s", __func__, options.control_path);
                   1154:
1.10      djm      1155:        memset(&addr, '\0', sizeof(addr));
                   1156:        addr.sun_family = AF_UNIX;
                   1157:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1158:            strlen(options.control_path) + 1;
                   1159:
                   1160:        if (strlcpy(addr.sun_path, options.control_path,
1.26      djm      1161:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
                   1162:                error("ControlPath \"%s\" too long for Unix domain socket",
                   1163:                    options.control_path);
                   1164:                goto disable_mux_master;
                   1165:        }
1.10      djm      1166:
                   1167:        if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1168:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1169:
                   1170:        old_umask = umask(0177);
                   1171:        if (bind(muxserver_sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
                   1172:                if (errno == EINVAL || errno == EADDRINUSE) {
                   1173:                        error("ControlSocket %s already exists, "
                   1174:                            "disabling multiplexing", options.control_path);
1.22      djm      1175:  disable_mux_master:
1.26      djm      1176:                        if (muxserver_sock != -1) {
                   1177:                                close(muxserver_sock);
                   1178:                                muxserver_sock = -1;
                   1179:                        }
1.35    ! djm      1180:                        xfree(orig_control_path);
1.10      djm      1181:                        xfree(options.control_path);
                   1182:                        options.control_path = NULL;
                   1183:                        options.control_master = SSHCTL_MASTER_NO;
                   1184:                        return;
                   1185:                } else
                   1186:                        fatal("%s bind(): %s", __func__, strerror(errno));
                   1187:        }
                   1188:        umask(old_umask);
                   1189:
                   1190:        if (listen(muxserver_sock, 64) == -1)
                   1191:                fatal("%s listen(): %s", __func__, strerror(errno));
                   1192:
1.22      djm      1193:        /* Now atomically "move" the mux socket into position */
                   1194:        if (link(options.control_path, orig_control_path) != 0) {
                   1195:                if (errno != EEXIST) {
                   1196:                        fatal("%s: link mux listener %s => %s: %s", __func__,
                   1197:                            options.control_path, orig_control_path,
                   1198:                            strerror(errno));
                   1199:                }
                   1200:                error("ControlSocket %s already exists, disabling multiplexing",
                   1201:                    orig_control_path);
                   1202:                unlink(options.control_path);
                   1203:                goto disable_mux_master;
                   1204:        }
                   1205:        unlink(options.control_path);
                   1206:        xfree(options.control_path);
                   1207:        options.control_path = orig_control_path;
                   1208:
1.10      djm      1209:        set_nonblock(muxserver_sock);
                   1210:
                   1211:        mux_listener_channel = channel_new("mux listener",
                   1212:            SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
                   1213:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.22      djm      1214:            0, options.control_path, 1);
1.10      djm      1215:        mux_listener_channel->mux_rcb = mux_master_read_cb;
                   1216:        debug3("%s: mux listener channel %d fd %d", __func__,
                   1217:            mux_listener_channel->self, mux_listener_channel->sock);
                   1218: }
                   1219:
                   1220: /* Callback on open confirmation in mux master for a mux client session. */
                   1221: static void
1.17      djm      1222: mux_session_confirm(int id, int success, void *arg)
1.10      djm      1223: {
                   1224:        struct mux_session_confirm_ctx *cctx = arg;
                   1225:        const char *display;
1.17      djm      1226:        Channel *c, *cc;
1.10      djm      1227:        int i;
1.17      djm      1228:        Buffer reply;
1.10      djm      1229:
                   1230:        if (cctx == NULL)
                   1231:                fatal("%s: cctx == NULL", __func__);
                   1232:        if ((c = channel_by_id(id)) == NULL)
                   1233:                fatal("%s: no channel for id %d", __func__, id);
1.17      djm      1234:        if ((cc = channel_by_id(c->ctl_chan)) == NULL)
                   1235:                fatal("%s: channel %d lacks control channel %d", __func__,
                   1236:                    id, c->ctl_chan);
                   1237:
                   1238:        if (!success) {
                   1239:                debug3("%s: sending failure reply", __func__);
                   1240:                /* prepare reply */
                   1241:                buffer_init(&reply);
                   1242:                buffer_put_int(&reply, MUX_S_FAILURE);
                   1243:                buffer_put_int(&reply, cctx->rid);
                   1244:                buffer_put_cstring(&reply, "Session open refused by peer");
                   1245:                goto done;
                   1246:        }
1.10      djm      1247:
                   1248:        display = getenv("DISPLAY");
                   1249:        if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
                   1250:                char *proto, *data;
1.21      djm      1251:
1.10      djm      1252:                /* Get reasonable local authentication information. */
                   1253:                client_x11_get_proto(display, options.xauth_location,
1.21      djm      1254:                    options.forward_x11_trusted, options.forward_x11_timeout,
                   1255:                    &proto, &data);
1.10      djm      1256:                /* Request forwarding with authentication spoofing. */
1.21      djm      1257:                debug("Requesting X11 forwarding with authentication "
                   1258:                    "spoofing.");
1.29      djm      1259:                x11_request_forwarding_with_spoofing(id, display, proto,
                   1260:                    data, 1);
                   1261:                client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
                   1262:                /* XXX exit_on_forward_failure */
1.10      djm      1263:        }
                   1264:
                   1265:        if (cctx->want_agent_fwd && options.forward_agent) {
                   1266:                debug("Requesting authentication agent forwarding.");
                   1267:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1268:                packet_send();
                   1269:        }
                   1270:
                   1271:        client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
                   1272:            cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
                   1273:
1.17      djm      1274:        debug3("%s: sending success reply", __func__);
                   1275:        /* prepare reply */
                   1276:        buffer_init(&reply);
                   1277:        buffer_put_int(&reply, MUX_S_SESSION_OPENED);
                   1278:        buffer_put_int(&reply, cctx->rid);
                   1279:        buffer_put_int(&reply, c->self);
                   1280:
                   1281:  done:
                   1282:        /* Send reply */
                   1283:        buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
                   1284:        buffer_free(&reply);
                   1285:
                   1286:        if (cc->mux_pause <= 0)
                   1287:                fatal("%s: mux_pause %d", __func__, cc->mux_pause);
                   1288:        cc->mux_pause = 0; /* start processing messages again */
1.10      djm      1289:        c->open_confirm_ctx = NULL;
                   1290:        buffer_free(&cctx->cmd);
                   1291:        xfree(cctx->term);
                   1292:        if (cctx->env != NULL) {
                   1293:                for (i = 0; cctx->env[i] != NULL; i++)
                   1294:                        xfree(cctx->env[i]);
                   1295:                xfree(cctx->env);
1.1       djm      1296:        }
1.10      djm      1297:        xfree(cctx);
                   1298: }
                   1299:
                   1300: /* ** Multiplexing client support */
                   1301:
                   1302: /* Exit signal handler */
                   1303: static void
                   1304: control_client_sighandler(int signo)
                   1305: {
                   1306:        muxclient_terminate = signo;
                   1307: }
                   1308:
                   1309: /*
                   1310:  * Relay signal handler - used to pass some signals from mux client to
                   1311:  * mux master.
                   1312:  */
                   1313: static void
                   1314: control_client_sigrelay(int signo)
                   1315: {
                   1316:        int save_errno = errno;
                   1317:
                   1318:        if (muxserver_pid > 1)
                   1319:                kill(muxserver_pid, signo);
                   1320:
                   1321:        errno = save_errno;
                   1322: }
1.1       djm      1323:
1.10      djm      1324: static int
                   1325: mux_client_read(int fd, Buffer *b, u_int need)
                   1326: {
                   1327:        u_int have;
                   1328:        ssize_t len;
                   1329:        u_char *p;
                   1330:        struct pollfd pfd;
                   1331:
                   1332:        pfd.fd = fd;
                   1333:        pfd.events = POLLIN;
                   1334:        p = buffer_append_space(b, need);
                   1335:        for (have = 0; have < need; ) {
                   1336:                if (muxclient_terminate) {
                   1337:                        errno = EINTR;
                   1338:                        return -1;
                   1339:                }
                   1340:                len = read(fd, p + have, need - have);
                   1341:                if (len < 0) {
                   1342:                        switch (errno) {
                   1343:                        case EAGAIN:
                   1344:                                (void)poll(&pfd, 1, -1);
                   1345:                                /* FALLTHROUGH */
                   1346:                        case EINTR:
                   1347:                                continue;
                   1348:                        default:
                   1349:                                return -1;
                   1350:                        }
                   1351:                }
                   1352:                if (len == 0) {
                   1353:                        errno = EPIPE;
                   1354:                        return -1;
                   1355:                }
                   1356:                have += (u_int)len;
1.1       djm      1357:        }
1.10      djm      1358:        return 0;
                   1359: }
1.1       djm      1360:
1.10      djm      1361: static int
                   1362: mux_client_write_packet(int fd, Buffer *m)
                   1363: {
                   1364:        Buffer queue;
                   1365:        u_int have, need;
                   1366:        int oerrno, len;
                   1367:        u_char *ptr;
                   1368:        struct pollfd pfd;
                   1369:
                   1370:        pfd.fd = fd;
                   1371:        pfd.events = POLLOUT;
                   1372:        buffer_init(&queue);
                   1373:        buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
                   1374:
                   1375:        need = buffer_len(&queue);
                   1376:        ptr = buffer_ptr(&queue);
                   1377:
                   1378:        for (have = 0; have < need; ) {
                   1379:                if (muxclient_terminate) {
                   1380:                        buffer_free(&queue);
                   1381:                        errno = EINTR;
                   1382:                        return -1;
                   1383:                }
                   1384:                len = write(fd, ptr + have, need - have);
                   1385:                if (len < 0) {
                   1386:                        switch (errno) {
                   1387:                        case EAGAIN:
                   1388:                                (void)poll(&pfd, 1, -1);
                   1389:                                /* FALLTHROUGH */
                   1390:                        case EINTR:
                   1391:                                continue;
                   1392:                        default:
                   1393:                                oerrno = errno;
                   1394:                                buffer_free(&queue);
                   1395:                                errno = oerrno;
                   1396:                                return -1;
                   1397:                        }
                   1398:                }
                   1399:                if (len == 0) {
                   1400:                        buffer_free(&queue);
                   1401:                        errno = EPIPE;
                   1402:                        return -1;
                   1403:                }
                   1404:                have += (u_int)len;
                   1405:        }
                   1406:        buffer_free(&queue);
                   1407:        return 0;
                   1408: }
1.1       djm      1409:
1.10      djm      1410: static int
                   1411: mux_client_read_packet(int fd, Buffer *m)
                   1412: {
                   1413:        Buffer queue;
                   1414:        u_int need, have;
                   1415:        void *ptr;
                   1416:        int oerrno;
                   1417:
                   1418:        buffer_init(&queue);
                   1419:        if (mux_client_read(fd, &queue, 4) != 0) {
                   1420:                if ((oerrno = errno) == EPIPE)
                   1421:                debug3("%s: read header failed: %s", __func__, strerror(errno));
                   1422:                errno = oerrno;
                   1423:                return -1;
                   1424:        }
                   1425:        need = get_u32(buffer_ptr(&queue));
                   1426:        if (mux_client_read(fd, &queue, need) != 0) {
                   1427:                oerrno = errno;
                   1428:                debug3("%s: read body failed: %s", __func__, strerror(errno));
                   1429:                errno = oerrno;
                   1430:                return -1;
                   1431:        }
                   1432:        ptr = buffer_get_string_ptr(&queue, &have);
                   1433:        buffer_append(m, ptr, have);
                   1434:        buffer_free(&queue);
                   1435:        return 0;
                   1436: }
1.1       djm      1437:
1.10      djm      1438: static int
                   1439: mux_client_hello_exchange(int fd)
                   1440: {
                   1441:        Buffer m;
                   1442:        u_int type, ver;
1.1       djm      1443:
                   1444:        buffer_init(&m);
1.10      djm      1445:        buffer_put_int(&m, MUX_MSG_HELLO);
                   1446:        buffer_put_int(&m, SSHMUX_VER);
                   1447:        /* no extensions */
                   1448:
                   1449:        if (mux_client_write_packet(fd, &m) != 0)
                   1450:                fatal("%s: write packet: %s", __func__, strerror(errno));
1.1       djm      1451:
1.10      djm      1452:        buffer_clear(&m);
                   1453:
                   1454:        /* Read their HELLO */
                   1455:        if (mux_client_read_packet(fd, &m) != 0) {
1.5       djm      1456:                buffer_free(&m);
1.10      djm      1457:                return -1;
                   1458:        }
                   1459:
                   1460:        type = buffer_get_int(&m);
                   1461:        if (type != MUX_MSG_HELLO)
                   1462:                fatal("%s: expected HELLO (%u) received %u",
                   1463:                    __func__, MUX_MSG_HELLO, type);
                   1464:        ver = buffer_get_int(&m);
                   1465:        if (ver != SSHMUX_VER)
                   1466:                fatal("Unsupported multiplexing protocol version %d "
                   1467:                    "(expected %d)", ver, SSHMUX_VER);
                   1468:        debug2("%s: master version %u", __func__, ver);
                   1469:        /* No extensions are presently defined */
                   1470:        while (buffer_len(&m) > 0) {
                   1471:                char *name = buffer_get_string(&m, NULL);
                   1472:                char *value = buffer_get_string(&m, NULL);
                   1473:
                   1474:                debug2("Unrecognised master extension \"%s\"", name);
                   1475:                xfree(name);
                   1476:                xfree(value);
1.5       djm      1477:        }
1.10      djm      1478:        buffer_free(&m);
                   1479:        return 0;
                   1480: }
                   1481:
                   1482: static u_int
                   1483: mux_client_request_alive(int fd)
                   1484: {
                   1485:        Buffer m;
                   1486:        char *e;
                   1487:        u_int pid, type, rid;
                   1488:
                   1489:        debug3("%s: entering", __func__);
                   1490:
                   1491:        buffer_init(&m);
                   1492:        buffer_put_int(&m, MUX_C_ALIVE_CHECK);
                   1493:        buffer_put_int(&m, muxclient_request_id);
                   1494:
                   1495:        if (mux_client_write_packet(fd, &m) != 0)
                   1496:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1497:
1.1       djm      1498:        buffer_clear(&m);
                   1499:
1.10      djm      1500:        /* Read their reply */
                   1501:        if (mux_client_read_packet(fd, &m) != 0) {
                   1502:                buffer_free(&m);
                   1503:                return 0;
                   1504:        }
                   1505:
                   1506:        type = buffer_get_int(&m);
                   1507:        if (type != MUX_S_ALIVE) {
                   1508:                e = buffer_get_string(&m, NULL);
                   1509:                fatal("%s: master returned error: %s", __func__, e);
1.5       djm      1510:        }
1.10      djm      1511:
                   1512:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1513:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1514:                    __func__, muxclient_request_id, rid);
                   1515:        pid = buffer_get_int(&m);
                   1516:        buffer_free(&m);
                   1517:
                   1518:        debug3("%s: done pid = %u", __func__, pid);
                   1519:
                   1520:        muxclient_request_id++;
                   1521:
                   1522:        return pid;
                   1523: }
                   1524:
                   1525: static void
                   1526: mux_client_request_terminate(int fd)
                   1527: {
                   1528:        Buffer m;
                   1529:        char *e;
                   1530:        u_int type, rid;
                   1531:
                   1532:        debug3("%s: entering", __func__);
                   1533:
                   1534:        buffer_init(&m);
                   1535:        buffer_put_int(&m, MUX_C_TERMINATE);
                   1536:        buffer_put_int(&m, muxclient_request_id);
                   1537:
                   1538:        if (mux_client_write_packet(fd, &m) != 0)
                   1539:                fatal("%s: write packet: %s", __func__, strerror(errno));
1.1       djm      1540:
                   1541:        buffer_clear(&m);
                   1542:
1.10      djm      1543:        /* Read their reply */
                   1544:        if (mux_client_read_packet(fd, &m) != 0) {
                   1545:                /* Remote end exited already */
                   1546:                if (errno == EPIPE) {
                   1547:                        buffer_free(&m);
                   1548:                        return;
1.2       djm      1549:                }
1.10      djm      1550:                fatal("%s: read from master failed: %s",
                   1551:                    __func__, strerror(errno));
                   1552:        }
                   1553:
                   1554:        type = buffer_get_int(&m);
                   1555:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1556:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1557:                    __func__, muxclient_request_id, rid);
                   1558:        switch (type) {
                   1559:        case MUX_S_OK:
                   1560:                break;
                   1561:        case MUX_S_PERMISSION_DENIED:
                   1562:                e = buffer_get_string(&m, NULL);
                   1563:                fatal("Master refused termination request: %s", e);
                   1564:        case MUX_S_FAILURE:
                   1565:                e = buffer_get_string(&m, NULL);
                   1566:                fatal("%s: termination request failed: %s", __func__, e);
                   1567:        default:
                   1568:                fatal("%s: unexpected response from master 0x%08x",
                   1569:                    __func__, type);
                   1570:        }
                   1571:        buffer_free(&m);
                   1572:        muxclient_request_id++;
                   1573: }
                   1574:
                   1575: static int
1.30      djm      1576: mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1.10      djm      1577: {
                   1578:        Buffer m;
                   1579:        char *e, *fwd_desc;
                   1580:        u_int type, rid;
                   1581:
                   1582:        fwd_desc = format_forward(ftype, fwd);
1.30      djm      1583:        debug("Requesting %s %s",
                   1584:            cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1.10      djm      1585:        xfree(fwd_desc);
                   1586:
                   1587:        buffer_init(&m);
1.30      djm      1588:        buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1.10      djm      1589:        buffer_put_int(&m, muxclient_request_id);
                   1590:        buffer_put_int(&m, ftype);
                   1591:        buffer_put_cstring(&m,
                   1592:            fwd->listen_host == NULL ? "" : fwd->listen_host);
                   1593:        buffer_put_int(&m, fwd->listen_port);
                   1594:        buffer_put_cstring(&m,
                   1595:            fwd->connect_host == NULL ? "" : fwd->connect_host);
                   1596:        buffer_put_int(&m, fwd->connect_port);
                   1597:
                   1598:        if (mux_client_write_packet(fd, &m) != 0)
                   1599:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1600:
                   1601:        buffer_clear(&m);
                   1602:
                   1603:        /* Read their reply */
                   1604:        if (mux_client_read_packet(fd, &m) != 0) {
                   1605:                buffer_free(&m);
                   1606:                return -1;
                   1607:        }
                   1608:
                   1609:        type = buffer_get_int(&m);
                   1610:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1611:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1612:                    __func__, muxclient_request_id, rid);
                   1613:        switch (type) {
                   1614:        case MUX_S_OK:
1.1       djm      1615:                break;
1.18      markus   1616:        case MUX_S_REMOTE_PORT:
1.30      djm      1617:                if (cancel_flag)
                   1618:                        fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1.18      markus   1619:                fwd->allocated_port = buffer_get_int(&m);
                   1620:                logit("Allocated port %u for remote forward to %s:%d",
                   1621:                    fwd->allocated_port,
                   1622:                    fwd->connect_host ? fwd->connect_host : "",
                   1623:                    fwd->connect_port);
                   1624:                if (muxclient_command == SSHMUX_COMMAND_FORWARD)
                   1625:                        fprintf(stdout, "%u\n", fwd->allocated_port);
                   1626:                break;
1.10      djm      1627:        case MUX_S_PERMISSION_DENIED:
                   1628:                e = buffer_get_string(&m, NULL);
                   1629:                buffer_free(&m);
                   1630:                error("Master refused forwarding request: %s", e);
                   1631:                return -1;
                   1632:        case MUX_S_FAILURE:
                   1633:                e = buffer_get_string(&m, NULL);
                   1634:                buffer_free(&m);
1.24      djm      1635:                error("%s: forwarding request failed: %s", __func__, e);
1.10      djm      1636:                return -1;
1.1       djm      1637:        default:
1.10      djm      1638:                fatal("%s: unexpected response from master 0x%08x",
                   1639:                    __func__, type);
                   1640:        }
                   1641:        buffer_free(&m);
                   1642:
                   1643:        muxclient_request_id++;
                   1644:        return 0;
                   1645: }
                   1646:
                   1647: static int
1.30      djm      1648: mux_client_forwards(int fd, int cancel_flag)
1.10      djm      1649: {
1.30      djm      1650:        int i, ret = 0;
1.10      djm      1651:
1.30      djm      1652:        debug3("%s: %s forwardings: %d local, %d remote", __func__,
                   1653:            cancel_flag ? "cancel" : "request",
1.10      djm      1654:            options.num_local_forwards, options.num_remote_forwards);
                   1655:
                   1656:        /* XXX ExitOnForwardingFailure */
                   1657:        for (i = 0; i < options.num_local_forwards; i++) {
1.30      djm      1658:                if (mux_client_forward(fd, cancel_flag,
1.10      djm      1659:                    options.local_forwards[i].connect_port == 0 ?
                   1660:                    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
                   1661:                    options.local_forwards + i) != 0)
1.30      djm      1662:                        ret = -1;
1.10      djm      1663:        }
                   1664:        for (i = 0; i < options.num_remote_forwards; i++) {
1.30      djm      1665:                if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1.10      djm      1666:                    options.remote_forwards + i) != 0)
1.30      djm      1667:                        ret = -1;
1.10      djm      1668:        }
1.30      djm      1669:        return ret;
1.10      djm      1670: }
                   1671:
                   1672: static int
                   1673: mux_client_request_session(int fd)
                   1674: {
                   1675:        Buffer m;
                   1676:        char *e, *term;
                   1677:        u_int i, rid, sid, esid, exitval, type, exitval_seen;
                   1678:        extern char **environ;
1.28      djm      1679:        int devnull, rawmode;
1.10      djm      1680:
                   1681:        debug3("%s: entering", __func__);
                   1682:
                   1683:        if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
                   1684:                error("%s: master alive request failed", __func__);
                   1685:                return -1;
1.1       djm      1686:        }
                   1687:
1.10      djm      1688:        signal(SIGPIPE, SIG_IGN);
                   1689:
                   1690:        if (stdin_null_flag) {
                   1691:                if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1692:                        fatal("open(/dev/null): %s", strerror(errno));
                   1693:                if (dup2(devnull, STDIN_FILENO) == -1)
                   1694:                        fatal("dup2: %s", strerror(errno));
                   1695:                if (devnull > STDERR_FILENO)
                   1696:                        close(devnull);
1.5       djm      1697:        }
1.1       djm      1698:
1.10      djm      1699:        term = getenv("TERM");
                   1700:
                   1701:        buffer_init(&m);
                   1702:        buffer_put_int(&m, MUX_C_NEW_SESSION);
                   1703:        buffer_put_int(&m, muxclient_request_id);
                   1704:        buffer_put_cstring(&m, ""); /* reserved */
                   1705:        buffer_put_int(&m, tty_flag);
                   1706:        buffer_put_int(&m, options.forward_x11);
                   1707:        buffer_put_int(&m, options.forward_agent);
                   1708:        buffer_put_int(&m, subsystem_flag);
                   1709:        buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
                   1710:            0xffffffff : (u_int)options.escape_char);
                   1711:        buffer_put_cstring(&m, term == NULL ? "" : term);
                   1712:        buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
                   1713:
                   1714:        if (options.num_send_env > 0 && environ != NULL) {
                   1715:                /* Pass environment */
                   1716:                for (i = 0; environ[i] != NULL; i++) {
                   1717:                        if (env_permitted(environ[i])) {
                   1718:                                buffer_put_cstring(&m, environ[i]);
                   1719:                        }
                   1720:                }
1.5       djm      1721:        }
                   1722:
1.10      djm      1723:        if (mux_client_write_packet(fd, &m) != 0)
                   1724:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1725:
                   1726:        /* Send the stdio file descriptors */
                   1727:        if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
                   1728:            mm_send_fd(fd, STDOUT_FILENO) == -1 ||
                   1729:            mm_send_fd(fd, STDERR_FILENO) == -1)
                   1730:                fatal("%s: send fds failed", __func__);
                   1731:
                   1732:        debug3("%s: session request sent", __func__);
1.1       djm      1733:
1.10      djm      1734:        /* Read their reply */
1.1       djm      1735:        buffer_clear(&m);
1.10      djm      1736:        if (mux_client_read_packet(fd, &m) != 0) {
                   1737:                error("%s: read from master failed: %s",
                   1738:                    __func__, strerror(errno));
                   1739:                buffer_free(&m);
                   1740:                return -1;
                   1741:        }
                   1742:
                   1743:        type = buffer_get_int(&m);
                   1744:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1745:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1746:                    __func__, muxclient_request_id, rid);
                   1747:        switch (type) {
                   1748:        case MUX_S_SESSION_OPENED:
                   1749:                sid = buffer_get_int(&m);
                   1750:                debug("%s: master session id: %u", __func__, sid);
                   1751:                break;
                   1752:        case MUX_S_PERMISSION_DENIED:
                   1753:                e = buffer_get_string(&m, NULL);
                   1754:                buffer_free(&m);
1.24      djm      1755:                error("Master refused session request: %s", e);
1.10      djm      1756:                return -1;
                   1757:        case MUX_S_FAILURE:
                   1758:                e = buffer_get_string(&m, NULL);
                   1759:                buffer_free(&m);
1.24      djm      1760:                error("%s: session request failed: %s", __func__, e);
1.10      djm      1761:                return -1;
                   1762:        default:
                   1763:                buffer_free(&m);
                   1764:                error("%s: unexpected response from master 0x%08x",
                   1765:                    __func__, type);
                   1766:                return -1;
                   1767:        }
                   1768:        muxclient_request_id++;
1.1       djm      1769:
                   1770:        signal(SIGHUP, control_client_sighandler);
                   1771:        signal(SIGINT, control_client_sighandler);
                   1772:        signal(SIGTERM, control_client_sighandler);
                   1773:        signal(SIGWINCH, control_client_sigrelay);
                   1774:
1.28      djm      1775:        rawmode = tty_flag;
1.1       djm      1776:        if (tty_flag)
1.27      djm      1777:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.1       djm      1778:
                   1779:        /*
                   1780:         * Stick around until the controlee closes the client_fd.
1.10      djm      1781:         * Before it does, it is expected to write an exit message.
                   1782:         * This process must read the value and wait for the closure of
                   1783:         * the client_fd; if this one closes early, the multiplex master will
                   1784:         * terminate early too (possibly losing data).
1.1       djm      1785:         */
1.10      djm      1786:        for (exitval = 255, exitval_seen = 0;;) {
                   1787:                buffer_clear(&m);
                   1788:                if (mux_client_read_packet(fd, &m) != 0)
1.1       djm      1789:                        break;
1.10      djm      1790:                type = buffer_get_int(&m);
1.28      djm      1791:                switch (type) {
                   1792:                case MUX_S_TTY_ALLOC_FAIL:
                   1793:                        if ((esid = buffer_get_int(&m)) != sid)
                   1794:                                fatal("%s: tty alloc fail on unknown session: "
                   1795:                                    "my id %u theirs %u",
                   1796:                                    __func__, sid, esid);
                   1797:                        leave_raw_mode(options.request_tty ==
                   1798:                            REQUEST_TTY_FORCE);
                   1799:                        rawmode = 0;
                   1800:                        continue;
                   1801:                case MUX_S_EXIT_MESSAGE:
                   1802:                        if ((esid = buffer_get_int(&m)) != sid)
                   1803:                                fatal("%s: exit on unknown session: "
                   1804:                                    "my id %u theirs %u",
                   1805:                                    __func__, sid, esid);
                   1806:                        if (exitval_seen)
                   1807:                                fatal("%s: exitval sent twice", __func__);
                   1808:                        exitval = buffer_get_int(&m);
                   1809:                        exitval_seen = 1;
                   1810:                        continue;
                   1811:                default:
1.10      djm      1812:                        e = buffer_get_string(&m, NULL);
                   1813:                        fatal("%s: master returned error: %s", __func__, e);
1.1       djm      1814:                }
                   1815:        }
                   1816:
1.10      djm      1817:        close(fd);
1.28      djm      1818:        if (rawmode)
                   1819:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.10      djm      1820:
1.1       djm      1821:        if (muxclient_terminate) {
                   1822:                debug2("Exiting on signal %d", muxclient_terminate);
1.10      djm      1823:                exitval = 255;
                   1824:        } else if (!exitval_seen) {
1.1       djm      1825:                debug2("Control master terminated unexpectedly");
1.10      djm      1826:                exitval = 255;
1.1       djm      1827:        } else
1.10      djm      1828:                debug2("Received exit status from master %d", exitval);
1.1       djm      1829:
                   1830:        if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
                   1831:                fprintf(stderr, "Shared connection to %s closed.\r\n", host);
                   1832:
1.10      djm      1833:        exit(exitval);
                   1834: }
                   1835:
                   1836: static int
                   1837: mux_client_request_stdio_fwd(int fd)
                   1838: {
                   1839:        Buffer m;
                   1840:        char *e;
                   1841:        u_int type, rid, sid;
                   1842:        int devnull;
                   1843:
                   1844:        debug3("%s: entering", __func__);
                   1845:
                   1846:        if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
                   1847:                error("%s: master alive request failed", __func__);
                   1848:                return -1;
                   1849:        }
                   1850:
                   1851:        signal(SIGPIPE, SIG_IGN);
                   1852:
                   1853:        if (stdin_null_flag) {
                   1854:                if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1855:                        fatal("open(/dev/null): %s", strerror(errno));
                   1856:                if (dup2(devnull, STDIN_FILENO) == -1)
                   1857:                        fatal("dup2: %s", strerror(errno));
                   1858:                if (devnull > STDERR_FILENO)
                   1859:                        close(devnull);
                   1860:        }
                   1861:
                   1862:        buffer_init(&m);
                   1863:        buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
                   1864:        buffer_put_int(&m, muxclient_request_id);
                   1865:        buffer_put_cstring(&m, ""); /* reserved */
                   1866:        buffer_put_cstring(&m, stdio_forward_host);
                   1867:        buffer_put_int(&m, stdio_forward_port);
                   1868:
                   1869:        if (mux_client_write_packet(fd, &m) != 0)
                   1870:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1871:
                   1872:        /* Send the stdio file descriptors */
                   1873:        if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
                   1874:            mm_send_fd(fd, STDOUT_FILENO) == -1)
                   1875:                fatal("%s: send fds failed", __func__);
                   1876:
                   1877:        debug3("%s: stdio forward request sent", __func__);
                   1878:
                   1879:        /* Read their reply */
                   1880:        buffer_clear(&m);
                   1881:
                   1882:        if (mux_client_read_packet(fd, &m) != 0) {
                   1883:                error("%s: read from master failed: %s",
                   1884:                    __func__, strerror(errno));
                   1885:                buffer_free(&m);
                   1886:                return -1;
                   1887:        }
                   1888:
                   1889:        type = buffer_get_int(&m);
                   1890:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1891:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1892:                    __func__, muxclient_request_id, rid);
                   1893:        switch (type) {
                   1894:        case MUX_S_SESSION_OPENED:
                   1895:                sid = buffer_get_int(&m);
                   1896:                debug("%s: master session id: %u", __func__, sid);
                   1897:                break;
                   1898:        case MUX_S_PERMISSION_DENIED:
                   1899:                e = buffer_get_string(&m, NULL);
                   1900:                buffer_free(&m);
1.24      djm      1901:                fatal("Master refused stdio forwarding request: %s", e);
1.10      djm      1902:        case MUX_S_FAILURE:
                   1903:                e = buffer_get_string(&m, NULL);
                   1904:                buffer_free(&m);
                   1905:                fatal("%s: stdio forwarding request failed: %s", __func__, e);
                   1906:        default:
                   1907:                buffer_free(&m);
                   1908:                error("%s: unexpected response from master 0x%08x",
                   1909:                    __func__, type);
                   1910:                return -1;
                   1911:        }
                   1912:        muxclient_request_id++;
                   1913:
                   1914:        signal(SIGHUP, control_client_sighandler);
                   1915:        signal(SIGINT, control_client_sighandler);
                   1916:        signal(SIGTERM, control_client_sighandler);
                   1917:        signal(SIGWINCH, control_client_sigrelay);
                   1918:
                   1919:        /*
                   1920:         * Stick around until the controlee closes the client_fd.
                   1921:         */
                   1922:        buffer_clear(&m);
                   1923:        if (mux_client_read_packet(fd, &m) != 0) {
                   1924:                if (errno == EPIPE ||
                   1925:                    (errno == EINTR && muxclient_terminate != 0))
                   1926:                        return 0;
                   1927:                fatal("%s: mux_client_read_packet: %s",
                   1928:                    __func__, strerror(errno));
                   1929:        }
                   1930:        fatal("%s: master returned unexpected message %u", __func__, type);
                   1931: }
                   1932:
1.25      djm      1933: static void
                   1934: mux_client_request_stop_listening(int fd)
                   1935: {
                   1936:        Buffer m;
                   1937:        char *e;
                   1938:        u_int type, rid;
                   1939:
                   1940:        debug3("%s: entering", __func__);
                   1941:
                   1942:        buffer_init(&m);
                   1943:        buffer_put_int(&m, MUX_C_STOP_LISTENING);
                   1944:        buffer_put_int(&m, muxclient_request_id);
                   1945:
                   1946:        if (mux_client_write_packet(fd, &m) != 0)
                   1947:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1948:
                   1949:        buffer_clear(&m);
                   1950:
                   1951:        /* Read their reply */
                   1952:        if (mux_client_read_packet(fd, &m) != 0)
                   1953:                fatal("%s: read from master failed: %s",
                   1954:                    __func__, strerror(errno));
                   1955:
                   1956:        type = buffer_get_int(&m);
                   1957:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1958:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1959:                    __func__, muxclient_request_id, rid);
                   1960:        switch (type) {
                   1961:        case MUX_S_OK:
                   1962:                break;
                   1963:        case MUX_S_PERMISSION_DENIED:
                   1964:                e = buffer_get_string(&m, NULL);
                   1965:                fatal("Master refused stop listening request: %s", e);
                   1966:        case MUX_S_FAILURE:
                   1967:                e = buffer_get_string(&m, NULL);
                   1968:                fatal("%s: stop listening request failed: %s", __func__, e);
                   1969:        default:
                   1970:                fatal("%s: unexpected response from master 0x%08x",
                   1971:                    __func__, type);
                   1972:        }
                   1973:        buffer_free(&m);
                   1974:        muxclient_request_id++;
                   1975: }
                   1976:
1.10      djm      1977: /* Multiplex client main loop. */
                   1978: void
                   1979: muxclient(const char *path)
                   1980: {
                   1981:        struct sockaddr_un addr;
                   1982:        int sock;
                   1983:        u_int pid;
                   1984:
                   1985:        if (muxclient_command == 0) {
                   1986:                if (stdio_forward_host != NULL)
                   1987:                        muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
                   1988:                else
                   1989:                        muxclient_command = SSHMUX_COMMAND_OPEN;
                   1990:        }
                   1991:
                   1992:        switch (options.control_master) {
                   1993:        case SSHCTL_MASTER_AUTO:
                   1994:        case SSHCTL_MASTER_AUTO_ASK:
                   1995:                debug("auto-mux: Trying existing master");
                   1996:                /* FALLTHROUGH */
                   1997:        case SSHCTL_MASTER_NO:
                   1998:                break;
                   1999:        default:
                   2000:                return;
                   2001:        }
                   2002:
                   2003:        memset(&addr, '\0', sizeof(addr));
                   2004:        addr.sun_family = AF_UNIX;
                   2005:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   2006:            strlen(path) + 1;
                   2007:
                   2008:        if (strlcpy(addr.sun_path, path,
                   2009:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   2010:                fatal("ControlPath too long");
                   2011:
                   2012:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   2013:                fatal("%s socket(): %s", __func__, strerror(errno));
                   2014:
                   2015:        if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
                   2016:                switch (muxclient_command) {
                   2017:                case SSHMUX_COMMAND_OPEN:
                   2018:                case SSHMUX_COMMAND_STDIO_FWD:
                   2019:                        break;
                   2020:                default:
                   2021:                        fatal("Control socket connect(%.100s): %s", path,
                   2022:                            strerror(errno));
                   2023:                }
1.22      djm      2024:                if (errno == ECONNREFUSED &&
                   2025:                    options.control_master != SSHCTL_MASTER_NO) {
                   2026:                        debug("Stale control socket %.100s, unlinking", path);
                   2027:                        unlink(path);
                   2028:                } else if (errno == ENOENT) {
1.10      djm      2029:                        debug("Control socket \"%.100s\" does not exist", path);
1.22      djm      2030:                } else {
1.10      djm      2031:                        error("Control socket connect(%.100s): %s", path,
                   2032:                            strerror(errno));
                   2033:                }
                   2034:                close(sock);
                   2035:                return;
                   2036:        }
                   2037:        set_nonblock(sock);
                   2038:
                   2039:        if (mux_client_hello_exchange(sock) != 0) {
                   2040:                error("%s: master hello exchange failed", __func__);
                   2041:                close(sock);
                   2042:                return;
                   2043:        }
                   2044:
                   2045:        switch (muxclient_command) {
                   2046:        case SSHMUX_COMMAND_ALIVE_CHECK:
                   2047:                if ((pid = mux_client_request_alive(sock)) == 0)
                   2048:                        fatal("%s: master alive check failed", __func__);
                   2049:                fprintf(stderr, "Master running (pid=%d)\r\n", pid);
                   2050:                exit(0);
                   2051:        case SSHMUX_COMMAND_TERMINATE:
                   2052:                mux_client_request_terminate(sock);
                   2053:                fprintf(stderr, "Exit request sent.\r\n");
1.18      markus   2054:                exit(0);
                   2055:        case SSHMUX_COMMAND_FORWARD:
1.30      djm      2056:                if (mux_client_forwards(sock, 0) != 0)
1.18      markus   2057:                        fatal("%s: master forward request failed", __func__);
1.10      djm      2058:                exit(0);
                   2059:        case SSHMUX_COMMAND_OPEN:
1.30      djm      2060:                if (mux_client_forwards(sock, 0) != 0) {
1.10      djm      2061:                        error("%s: master forward request failed", __func__);
                   2062:                        return;
                   2063:                }
                   2064:                mux_client_request_session(sock);
                   2065:                return;
                   2066:        case SSHMUX_COMMAND_STDIO_FWD:
                   2067:                mux_client_request_stdio_fwd(sock);
1.25      djm      2068:                exit(0);
                   2069:        case SSHMUX_COMMAND_STOP:
                   2070:                mux_client_request_stop_listening(sock);
                   2071:                fprintf(stderr, "Stop listening request sent.\r\n");
1.30      djm      2072:                exit(0);
                   2073:        case SSHMUX_COMMAND_CANCEL_FWD:
                   2074:                if (mux_client_forwards(sock, 1) != 0)
                   2075:                        error("%s: master cancel forward request failed",
                   2076:                            __func__);
1.10      djm      2077:                exit(0);
                   2078:        default:
                   2079:                fatal("unrecognised muxclient_command %d", muxclient_command);
                   2080:        }
1.1       djm      2081: }