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

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