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

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