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

1.28    ! djm         1: /* $OpenBSD: mux.c,v 1.27 2011/05/06 21:34:32 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: {
                    763:        Forward fwd;
                    764:        char *fwd_desc = NULL;
                    765:        u_int ftype;
                    766:        int ret = 0;
                    767:
                    768:        fwd.listen_host = fwd.connect_host = NULL;
                    769:        if (buffer_get_int_ret(&ftype, m) != 0 ||
                    770:            (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    771:            buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
                    772:            (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
                    773:            buffer_get_int_ret(&fwd.connect_port, m) != 0) {
                    774:                error("%s: malformed message", __func__);
                    775:                ret = -1;
                    776:                goto out;
                    777:        }
                    778:
                    779:        if (*fwd.listen_host == '\0') {
                    780:                xfree(fwd.listen_host);
                    781:                fwd.listen_host = NULL;
                    782:        }
                    783:        if (*fwd.connect_host == '\0') {
                    784:                xfree(fwd.connect_host);
                    785:                fwd.connect_host = NULL;
                    786:        }
                    787:
                    788:        debug2("%s: channel %d: request %s", __func__, c->self,
                    789:            (fwd_desc = format_forward(ftype, &fwd)));
                    790:
                    791:        /* XXX implement this */
                    792:        buffer_put_int(r, MUX_S_FAILURE);
                    793:        buffer_put_int(r, rid);
                    794:        buffer_put_cstring(r, "unimplemented");
                    795:
                    796:  out:
                    797:        if (fwd_desc != NULL)
                    798:                xfree(fwd_desc);
                    799:        if (fwd.listen_host != NULL)
                    800:                xfree(fwd.listen_host);
                    801:        if (fwd.connect_host != NULL)
                    802:                xfree(fwd.connect_host);
                    803:
                    804:        return ret;
                    805: }
                    806:
                    807: static int
                    808: process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    809: {
                    810:        Channel *nc;
                    811:        char *reserved, *chost;
                    812:        u_int cport, i, j;
                    813:        int new_fd[2];
                    814:
1.11      djm       815:        chost = reserved = NULL;
1.10      djm       816:        if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
                    817:           (chost = buffer_get_string_ret(m, NULL)) == NULL ||
                    818:            buffer_get_int_ret(&cport, m) != 0) {
1.11      djm       819:                if (reserved != NULL)
                    820:                        xfree(reserved);
1.10      djm       821:                if (chost != NULL)
                    822:                        xfree(chost);
                    823:                error("%s: malformed message", __func__);
                    824:                return -1;
                    825:        }
                    826:        xfree(reserved);
                    827:
                    828:        debug2("%s: channel %d: request stdio fwd to %s:%u",
                    829:            __func__, c->self, chost, cport);
                    830:
                    831:        /* Gather fds from client */
                    832:        for(i = 0; i < 2; i++) {
                    833:                if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
                    834:                        error("%s: failed to receive fd %d from slave",
                    835:                            __func__, i);
                    836:                        for (j = 0; j < i; j++)
                    837:                                close(new_fd[j]);
                    838:                        xfree(chost);
                    839:
                    840:                        /* prepare reply */
                    841:                        buffer_put_int(r, MUX_S_FAILURE);
                    842:                        buffer_put_int(r, rid);
                    843:                        buffer_put_cstring(r,
                    844:                            "did not receive file descriptors");
                    845:                        return -1;
                    846:                }
                    847:        }
                    848:
                    849:        debug3("%s: got fds stdin %d, stdout %d", __func__,
                    850:            new_fd[0], new_fd[1]);
                    851:
                    852:        /* XXX support multiple child sessions in future */
                    853:        if (c->remote_id != -1) {
                    854:                debug2("%s: session already open", __func__);
                    855:                /* prepare reply */
                    856:                buffer_put_int(r, MUX_S_FAILURE);
                    857:                buffer_put_int(r, rid);
                    858:                buffer_put_cstring(r, "Multiple sessions not supported");
                    859:  cleanup:
                    860:                close(new_fd[0]);
                    861:                close(new_fd[1]);
                    862:                xfree(chost);
                    863:                return 0;
                    864:        }
                    865:
                    866:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    867:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1.23      dtucker   868:                if (!ask_permission("Allow forward to %s:%u? ",
1.10      djm       869:                    chost, cport)) {
                    870:                        debug2("%s: stdio fwd refused by user", __func__);
                    871:                        /* prepare reply */
                    872:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    873:                        buffer_put_int(r, rid);
                    874:                        buffer_put_cstring(r, "Permission denied");
                    875:                        goto cleanup;
                    876:                }
                    877:        }
                    878:
                    879:        /* enable nonblocking unless tty */
                    880:        if (!isatty(new_fd[0]))
                    881:                set_nonblock(new_fd[0]);
                    882:        if (!isatty(new_fd[1]))
                    883:                set_nonblock(new_fd[1]);
                    884:
                    885:        nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
                    886:
                    887:        nc->ctl_chan = c->self;         /* link session -> control channel */
                    888:        c->remote_id = nc->self;        /* link control -> session channel */
                    889:
                    890:        debug2("%s: channel_new: %d linked to control channel %d",
                    891:            __func__, nc->self, nc->ctl_chan);
                    892:
1.16      djm       893:        channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1.10      djm       894:
                    895:        /* prepare reply */
                    896:        /* XXX defer until channel confirmed */
                    897:        buffer_put_int(r, MUX_S_SESSION_OPENED);
                    898:        buffer_put_int(r, rid);
                    899:        buffer_put_int(r, nc->self);
                    900:
                    901:        return 0;
                    902: }
                    903:
1.25      djm       904: static int
                    905: process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
                    906: {
                    907:        debug("%s: channel %d: stop listening", __func__, c->self);
                    908:
                    909:        if (options.control_master == SSHCTL_MASTER_ASK ||
                    910:            options.control_master == SSHCTL_MASTER_AUTO_ASK) {
                    911:                if (!ask_permission("Disable further multiplexing on shared "
                    912:                    "connection to %s? ", host)) {
                    913:                        debug2("%s: stop listen refused by user", __func__);
                    914:                        buffer_put_int(r, MUX_S_PERMISSION_DENIED);
                    915:                        buffer_put_int(r, rid);
                    916:                        buffer_put_cstring(r, "Permission denied");
                    917:                        return 0;
                    918:                }
                    919:        }
                    920:
                    921:        if (mux_listener_channel != NULL) {
                    922:                channel_free(mux_listener_channel);
                    923:                client_stop_mux();
                    924:                xfree(options.control_path);
                    925:                options.control_path = NULL;
                    926:                mux_listener_channel = NULL;
                    927:                muxserver_sock = -1;
                    928:        }
                    929:
                    930:        /* prepare reply */
                    931:        buffer_put_int(r, MUX_S_OK);
                    932:        buffer_put_int(r, rid);
                    933:
                    934:        return 0;
                    935: }
                    936:
1.10      djm       937: /* Channel callbacks fired on read/write from mux slave fd */
                    938: static int
                    939: mux_master_read_cb(Channel *c)
                    940: {
                    941:        struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
                    942:        Buffer in, out;
                    943:        void *ptr;
                    944:        u_int type, rid, have, i;
                    945:        int ret = -1;
                    946:
                    947:        /* Setup ctx and  */
                    948:        if (c->mux_ctx == NULL) {
1.19      djm       949:                state = xcalloc(1, sizeof(*state));
1.10      djm       950:                c->mux_ctx = state;
                    951:                channel_register_cleanup(c->self,
                    952:                    mux_master_control_cleanup_cb, 0);
                    953:
                    954:                /* Send hello */
                    955:                buffer_init(&out);
                    956:                buffer_put_int(&out, MUX_MSG_HELLO);
                    957:                buffer_put_int(&out, SSHMUX_VER);
                    958:                /* no extensions */
                    959:                buffer_put_string(&c->output, buffer_ptr(&out),
                    960:                    buffer_len(&out));
                    961:                buffer_free(&out);
                    962:                debug3("%s: channel %d: hello sent", __func__, c->self);
                    963:                return 0;
                    964:        }
                    965:
                    966:        buffer_init(&in);
                    967:        buffer_init(&out);
                    968:
                    969:        /* Channel code ensures that we receive whole packets */
                    970:        if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
                    971:  malf:
                    972:                error("%s: malformed message", __func__);
                    973:                goto out;
                    974:        }
                    975:        buffer_append(&in, ptr, have);
                    976:
                    977:        if (buffer_get_int_ret(&type, &in) != 0)
                    978:                goto malf;
                    979:        debug3("%s: channel %d packet type 0x%08x len %u",
                    980:            __func__, c->self, type, buffer_len(&in));
                    981:
                    982:        if (type == MUX_MSG_HELLO)
                    983:                rid = 0;
                    984:        else {
                    985:                if (!state->hello_rcvd) {
                    986:                        error("%s: expected MUX_MSG_HELLO(0x%08x), "
                    987:                            "received 0x%08x", __func__, MUX_MSG_HELLO, type);
                    988:                        goto out;
1.1       djm       989:                }
1.10      djm       990:                if (buffer_get_int_ret(&rid, &in) != 0)
                    991:                        goto malf;
                    992:        }
                    993:
                    994:        for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
                    995:                if (type == mux_master_handlers[i].type) {
                    996:                        ret = mux_master_handlers[i].handler(rid, c, &in, &out);
                    997:                        break;
1.1       djm       998:                }
1.10      djm       999:        }
                   1000:        if (mux_master_handlers[i].handler == NULL) {
                   1001:                error("%s: unsupported mux message 0x%08x", __func__, type);
                   1002:                buffer_put_int(&out, MUX_S_FAILURE);
                   1003:                buffer_put_int(&out, rid);
                   1004:                buffer_put_cstring(&out, "unsupported request");
                   1005:                ret = 0;
                   1006:        }
                   1007:        /* Enqueue reply packet */
                   1008:        if (buffer_len(&out) != 0) {
                   1009:                buffer_put_string(&c->output, buffer_ptr(&out),
                   1010:                    buffer_len(&out));
                   1011:        }
                   1012:  out:
                   1013:        buffer_free(&in);
                   1014:        buffer_free(&out);
                   1015:        return ret;
                   1016: }
                   1017:
                   1018: void
                   1019: mux_exit_message(Channel *c, int exitval)
                   1020: {
                   1021:        Buffer m;
                   1022:        Channel *mux_chan;
                   1023:
                   1024:        debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
                   1025:            exitval);
                   1026:
                   1027:        if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
                   1028:                fatal("%s: channel %d missing mux channel %d",
                   1029:                    __func__, c->self, c->ctl_chan);
                   1030:
                   1031:        /* Append exit message packet to control socket output queue */
                   1032:        buffer_init(&m);
                   1033:        buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
                   1034:        buffer_put_int(&m, c->self);
                   1035:        buffer_put_int(&m, exitval);
                   1036:
                   1037:        buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
                   1038:        buffer_free(&m);
                   1039: }
                   1040:
1.28    ! djm      1041: void
        !          1042: mux_tty_alloc_failed(Channel *c)
        !          1043: {
        !          1044:        Buffer m;
        !          1045:        Channel *mux_chan;
        !          1046:
        !          1047:        debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
        !          1048:
        !          1049:        if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
        !          1050:                fatal("%s: channel %d missing mux channel %d",
        !          1051:                    __func__, c->self, c->ctl_chan);
        !          1052:
        !          1053:        /* Append exit message packet to control socket output queue */
        !          1054:        buffer_init(&m);
        !          1055:        buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
        !          1056:        buffer_put_int(&m, c->self);
        !          1057:
        !          1058:        buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
        !          1059:        buffer_free(&m);
        !          1060: }
        !          1061:
1.10      djm      1062: /* Prepare a mux master to listen on a Unix domain socket. */
                   1063: void
                   1064: muxserver_listen(void)
                   1065: {
                   1066:        struct sockaddr_un addr;
                   1067:        mode_t old_umask;
1.22      djm      1068:        char *orig_control_path = options.control_path;
                   1069:        char rbuf[16+1];
                   1070:        u_int i, r;
1.10      djm      1071:
                   1072:        if (options.control_path == NULL ||
                   1073:            options.control_master == SSHCTL_MASTER_NO)
1.1       djm      1074:                return;
1.10      djm      1075:
                   1076:        debug("setting up multiplex master socket");
                   1077:
1.22      djm      1078:        /*
                   1079:         * Use a temporary path before listen so we can pseudo-atomically
                   1080:         * establish the listening socket in its final location to avoid
                   1081:         * other processes racing in between bind() and listen() and hitting
                   1082:         * an unready socket.
                   1083:         */
                   1084:        for (i = 0; i < sizeof(rbuf) - 1; i++) {
                   1085:                r = arc4random_uniform(26+26+10);
                   1086:                rbuf[i] = (r < 26) ? 'a' + r :
                   1087:                    (r < 26*2) ? 'A' + r - 26 :
                   1088:                    '0' + r - 26 - 26;
                   1089:        }
                   1090:        rbuf[sizeof(rbuf) - 1] = '\0';
                   1091:        options.control_path = NULL;
                   1092:        xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
                   1093:        debug3("%s: temporary control path %s", __func__, options.control_path);
                   1094:
1.10      djm      1095:        memset(&addr, '\0', sizeof(addr));
                   1096:        addr.sun_family = AF_UNIX;
                   1097:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1098:            strlen(options.control_path) + 1;
                   1099:
                   1100:        if (strlcpy(addr.sun_path, options.control_path,
1.26      djm      1101:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
                   1102:                error("ControlPath \"%s\" too long for Unix domain socket",
                   1103:                    options.control_path);
                   1104:                goto disable_mux_master;
                   1105:        }
1.10      djm      1106:
                   1107:        if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1108:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1109:
                   1110:        old_umask = umask(0177);
                   1111:        if (bind(muxserver_sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
                   1112:                if (errno == EINVAL || errno == EADDRINUSE) {
                   1113:                        error("ControlSocket %s already exists, "
                   1114:                            "disabling multiplexing", options.control_path);
1.22      djm      1115:  disable_mux_master:
1.26      djm      1116:                        if (muxserver_sock != -1) {
                   1117:                                close(muxserver_sock);
                   1118:                                muxserver_sock = -1;
                   1119:                        }
1.10      djm      1120:                        xfree(options.control_path);
                   1121:                        options.control_path = NULL;
                   1122:                        options.control_master = SSHCTL_MASTER_NO;
                   1123:                        return;
                   1124:                } else
                   1125:                        fatal("%s bind(): %s", __func__, strerror(errno));
                   1126:        }
                   1127:        umask(old_umask);
                   1128:
                   1129:        if (listen(muxserver_sock, 64) == -1)
                   1130:                fatal("%s listen(): %s", __func__, strerror(errno));
                   1131:
1.22      djm      1132:        /* Now atomically "move" the mux socket into position */
                   1133:        if (link(options.control_path, orig_control_path) != 0) {
                   1134:                if (errno != EEXIST) {
                   1135:                        fatal("%s: link mux listener %s => %s: %s", __func__,
                   1136:                            options.control_path, orig_control_path,
                   1137:                            strerror(errno));
                   1138:                }
                   1139:                error("ControlSocket %s already exists, disabling multiplexing",
                   1140:                    orig_control_path);
                   1141:                xfree(orig_control_path);
                   1142:                unlink(options.control_path);
                   1143:                goto disable_mux_master;
                   1144:        }
                   1145:        unlink(options.control_path);
                   1146:        xfree(options.control_path);
                   1147:        options.control_path = orig_control_path;
                   1148:
1.10      djm      1149:        set_nonblock(muxserver_sock);
                   1150:
                   1151:        mux_listener_channel = channel_new("mux listener",
                   1152:            SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
                   1153:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1.22      djm      1154:            0, options.control_path, 1);
1.10      djm      1155:        mux_listener_channel->mux_rcb = mux_master_read_cb;
                   1156:        debug3("%s: mux listener channel %d fd %d", __func__,
                   1157:            mux_listener_channel->self, mux_listener_channel->sock);
                   1158: }
                   1159:
                   1160: /* Callback on open confirmation in mux master for a mux client session. */
                   1161: static void
1.17      djm      1162: mux_session_confirm(int id, int success, void *arg)
1.10      djm      1163: {
                   1164:        struct mux_session_confirm_ctx *cctx = arg;
                   1165:        const char *display;
1.17      djm      1166:        Channel *c, *cc;
1.10      djm      1167:        int i;
1.17      djm      1168:        Buffer reply;
1.10      djm      1169:
                   1170:        if (cctx == NULL)
                   1171:                fatal("%s: cctx == NULL", __func__);
                   1172:        if ((c = channel_by_id(id)) == NULL)
                   1173:                fatal("%s: no channel for id %d", __func__, id);
1.17      djm      1174:        if ((cc = channel_by_id(c->ctl_chan)) == NULL)
                   1175:                fatal("%s: channel %d lacks control channel %d", __func__,
                   1176:                    id, c->ctl_chan);
                   1177:
                   1178:        if (!success) {
                   1179:                debug3("%s: sending failure reply", __func__);
                   1180:                /* prepare reply */
                   1181:                buffer_init(&reply);
                   1182:                buffer_put_int(&reply, MUX_S_FAILURE);
                   1183:                buffer_put_int(&reply, cctx->rid);
                   1184:                buffer_put_cstring(&reply, "Session open refused by peer");
                   1185:                goto done;
                   1186:        }
1.10      djm      1187:
                   1188:        display = getenv("DISPLAY");
                   1189:        if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
                   1190:                char *proto, *data;
1.21      djm      1191:
1.10      djm      1192:                /* Get reasonable local authentication information. */
                   1193:                client_x11_get_proto(display, options.xauth_location,
1.21      djm      1194:                    options.forward_x11_trusted, options.forward_x11_timeout,
                   1195:                    &proto, &data);
1.10      djm      1196:                /* Request forwarding with authentication spoofing. */
1.21      djm      1197:                debug("Requesting X11 forwarding with authentication "
                   1198:                    "spoofing.");
1.10      djm      1199:                x11_request_forwarding_with_spoofing(id, display, proto, data);
                   1200:                /* XXX wait for reply */
                   1201:        }
                   1202:
                   1203:        if (cctx->want_agent_fwd && options.forward_agent) {
                   1204:                debug("Requesting authentication agent forwarding.");
                   1205:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1206:                packet_send();
                   1207:        }
                   1208:
                   1209:        client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
                   1210:            cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
                   1211:
1.17      djm      1212:        debug3("%s: sending success reply", __func__);
                   1213:        /* prepare reply */
                   1214:        buffer_init(&reply);
                   1215:        buffer_put_int(&reply, MUX_S_SESSION_OPENED);
                   1216:        buffer_put_int(&reply, cctx->rid);
                   1217:        buffer_put_int(&reply, c->self);
                   1218:
                   1219:  done:
                   1220:        /* Send reply */
                   1221:        buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
                   1222:        buffer_free(&reply);
                   1223:
                   1224:        if (cc->mux_pause <= 0)
                   1225:                fatal("%s: mux_pause %d", __func__, cc->mux_pause);
                   1226:        cc->mux_pause = 0; /* start processing messages again */
1.10      djm      1227:        c->open_confirm_ctx = NULL;
                   1228:        buffer_free(&cctx->cmd);
                   1229:        xfree(cctx->term);
                   1230:        if (cctx->env != NULL) {
                   1231:                for (i = 0; cctx->env[i] != NULL; i++)
                   1232:                        xfree(cctx->env[i]);
                   1233:                xfree(cctx->env);
1.1       djm      1234:        }
1.10      djm      1235:        xfree(cctx);
                   1236: }
                   1237:
                   1238: /* ** Multiplexing client support */
                   1239:
                   1240: /* Exit signal handler */
                   1241: static void
                   1242: control_client_sighandler(int signo)
                   1243: {
                   1244:        muxclient_terminate = signo;
                   1245: }
                   1246:
                   1247: /*
                   1248:  * Relay signal handler - used to pass some signals from mux client to
                   1249:  * mux master.
                   1250:  */
                   1251: static void
                   1252: control_client_sigrelay(int signo)
                   1253: {
                   1254:        int save_errno = errno;
                   1255:
                   1256:        if (muxserver_pid > 1)
                   1257:                kill(muxserver_pid, signo);
                   1258:
                   1259:        errno = save_errno;
                   1260: }
1.1       djm      1261:
1.10      djm      1262: static int
                   1263: mux_client_read(int fd, Buffer *b, u_int need)
                   1264: {
                   1265:        u_int have;
                   1266:        ssize_t len;
                   1267:        u_char *p;
                   1268:        struct pollfd pfd;
                   1269:
                   1270:        pfd.fd = fd;
                   1271:        pfd.events = POLLIN;
                   1272:        p = buffer_append_space(b, need);
                   1273:        for (have = 0; have < need; ) {
                   1274:                if (muxclient_terminate) {
                   1275:                        errno = EINTR;
                   1276:                        return -1;
                   1277:                }
                   1278:                len = read(fd, p + have, need - have);
                   1279:                if (len < 0) {
                   1280:                        switch (errno) {
                   1281:                        case EAGAIN:
                   1282:                                (void)poll(&pfd, 1, -1);
                   1283:                                /* FALLTHROUGH */
                   1284:                        case EINTR:
                   1285:                                continue;
                   1286:                        default:
                   1287:                                return -1;
                   1288:                        }
                   1289:                }
                   1290:                if (len == 0) {
                   1291:                        errno = EPIPE;
                   1292:                        return -1;
                   1293:                }
                   1294:                have += (u_int)len;
1.1       djm      1295:        }
1.10      djm      1296:        return 0;
                   1297: }
1.1       djm      1298:
1.10      djm      1299: static int
                   1300: mux_client_write_packet(int fd, Buffer *m)
                   1301: {
                   1302:        Buffer queue;
                   1303:        u_int have, need;
                   1304:        int oerrno, len;
                   1305:        u_char *ptr;
                   1306:        struct pollfd pfd;
                   1307:
                   1308:        pfd.fd = fd;
                   1309:        pfd.events = POLLOUT;
                   1310:        buffer_init(&queue);
                   1311:        buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
                   1312:
                   1313:        need = buffer_len(&queue);
                   1314:        ptr = buffer_ptr(&queue);
                   1315:
                   1316:        for (have = 0; have < need; ) {
                   1317:                if (muxclient_terminate) {
                   1318:                        buffer_free(&queue);
                   1319:                        errno = EINTR;
                   1320:                        return -1;
                   1321:                }
                   1322:                len = write(fd, ptr + have, need - have);
                   1323:                if (len < 0) {
                   1324:                        switch (errno) {
                   1325:                        case EAGAIN:
                   1326:                                (void)poll(&pfd, 1, -1);
                   1327:                                /* FALLTHROUGH */
                   1328:                        case EINTR:
                   1329:                                continue;
                   1330:                        default:
                   1331:                                oerrno = errno;
                   1332:                                buffer_free(&queue);
                   1333:                                errno = oerrno;
                   1334:                                return -1;
                   1335:                        }
                   1336:                }
                   1337:                if (len == 0) {
                   1338:                        buffer_free(&queue);
                   1339:                        errno = EPIPE;
                   1340:                        return -1;
                   1341:                }
                   1342:                have += (u_int)len;
                   1343:        }
                   1344:        buffer_free(&queue);
                   1345:        return 0;
                   1346: }
1.1       djm      1347:
1.10      djm      1348: static int
                   1349: mux_client_read_packet(int fd, Buffer *m)
                   1350: {
                   1351:        Buffer queue;
                   1352:        u_int need, have;
                   1353:        void *ptr;
                   1354:        int oerrno;
                   1355:
                   1356:        buffer_init(&queue);
                   1357:        if (mux_client_read(fd, &queue, 4) != 0) {
                   1358:                if ((oerrno = errno) == EPIPE)
                   1359:                debug3("%s: read header failed: %s", __func__, strerror(errno));
                   1360:                errno = oerrno;
                   1361:                return -1;
                   1362:        }
                   1363:        need = get_u32(buffer_ptr(&queue));
                   1364:        if (mux_client_read(fd, &queue, need) != 0) {
                   1365:                oerrno = errno;
                   1366:                debug3("%s: read body failed: %s", __func__, strerror(errno));
                   1367:                errno = oerrno;
                   1368:                return -1;
                   1369:        }
                   1370:        ptr = buffer_get_string_ptr(&queue, &have);
                   1371:        buffer_append(m, ptr, have);
                   1372:        buffer_free(&queue);
                   1373:        return 0;
                   1374: }
1.1       djm      1375:
1.10      djm      1376: static int
                   1377: mux_client_hello_exchange(int fd)
                   1378: {
                   1379:        Buffer m;
                   1380:        u_int type, ver;
1.1       djm      1381:
                   1382:        buffer_init(&m);
1.10      djm      1383:        buffer_put_int(&m, MUX_MSG_HELLO);
                   1384:        buffer_put_int(&m, SSHMUX_VER);
                   1385:        /* no extensions */
                   1386:
                   1387:        if (mux_client_write_packet(fd, &m) != 0)
                   1388:                fatal("%s: write packet: %s", __func__, strerror(errno));
1.1       djm      1389:
1.10      djm      1390:        buffer_clear(&m);
                   1391:
                   1392:        /* Read their HELLO */
                   1393:        if (mux_client_read_packet(fd, &m) != 0) {
1.5       djm      1394:                buffer_free(&m);
1.10      djm      1395:                return -1;
                   1396:        }
                   1397:
                   1398:        type = buffer_get_int(&m);
                   1399:        if (type != MUX_MSG_HELLO)
                   1400:                fatal("%s: expected HELLO (%u) received %u",
                   1401:                    __func__, MUX_MSG_HELLO, type);
                   1402:        ver = buffer_get_int(&m);
                   1403:        if (ver != SSHMUX_VER)
                   1404:                fatal("Unsupported multiplexing protocol version %d "
                   1405:                    "(expected %d)", ver, SSHMUX_VER);
                   1406:        debug2("%s: master version %u", __func__, ver);
                   1407:        /* No extensions are presently defined */
                   1408:        while (buffer_len(&m) > 0) {
                   1409:                char *name = buffer_get_string(&m, NULL);
                   1410:                char *value = buffer_get_string(&m, NULL);
                   1411:
                   1412:                debug2("Unrecognised master extension \"%s\"", name);
                   1413:                xfree(name);
                   1414:                xfree(value);
1.5       djm      1415:        }
1.10      djm      1416:        buffer_free(&m);
                   1417:        return 0;
                   1418: }
                   1419:
                   1420: static u_int
                   1421: mux_client_request_alive(int fd)
                   1422: {
                   1423:        Buffer m;
                   1424:        char *e;
                   1425:        u_int pid, type, rid;
                   1426:
                   1427:        debug3("%s: entering", __func__);
                   1428:
                   1429:        buffer_init(&m);
                   1430:        buffer_put_int(&m, MUX_C_ALIVE_CHECK);
                   1431:        buffer_put_int(&m, muxclient_request_id);
                   1432:
                   1433:        if (mux_client_write_packet(fd, &m) != 0)
                   1434:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1435:
1.1       djm      1436:        buffer_clear(&m);
                   1437:
1.10      djm      1438:        /* Read their reply */
                   1439:        if (mux_client_read_packet(fd, &m) != 0) {
                   1440:                buffer_free(&m);
                   1441:                return 0;
                   1442:        }
                   1443:
                   1444:        type = buffer_get_int(&m);
                   1445:        if (type != MUX_S_ALIVE) {
                   1446:                e = buffer_get_string(&m, NULL);
                   1447:                fatal("%s: master returned error: %s", __func__, e);
1.5       djm      1448:        }
1.10      djm      1449:
                   1450:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1451:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1452:                    __func__, muxclient_request_id, rid);
                   1453:        pid = buffer_get_int(&m);
                   1454:        buffer_free(&m);
                   1455:
                   1456:        debug3("%s: done pid = %u", __func__, pid);
                   1457:
                   1458:        muxclient_request_id++;
                   1459:
                   1460:        return pid;
                   1461: }
                   1462:
                   1463: static void
                   1464: mux_client_request_terminate(int fd)
                   1465: {
                   1466:        Buffer m;
                   1467:        char *e;
                   1468:        u_int type, rid;
                   1469:
                   1470:        debug3("%s: entering", __func__);
                   1471:
                   1472:        buffer_init(&m);
                   1473:        buffer_put_int(&m, MUX_C_TERMINATE);
                   1474:        buffer_put_int(&m, muxclient_request_id);
                   1475:
                   1476:        if (mux_client_write_packet(fd, &m) != 0)
                   1477:                fatal("%s: write packet: %s", __func__, strerror(errno));
1.1       djm      1478:
                   1479:        buffer_clear(&m);
                   1480:
1.10      djm      1481:        /* Read their reply */
                   1482:        if (mux_client_read_packet(fd, &m) != 0) {
                   1483:                /* Remote end exited already */
                   1484:                if (errno == EPIPE) {
                   1485:                        buffer_free(&m);
                   1486:                        return;
1.2       djm      1487:                }
1.10      djm      1488:                fatal("%s: read from master failed: %s",
                   1489:                    __func__, strerror(errno));
                   1490:        }
                   1491:
                   1492:        type = buffer_get_int(&m);
                   1493:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1494:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1495:                    __func__, muxclient_request_id, rid);
                   1496:        switch (type) {
                   1497:        case MUX_S_OK:
                   1498:                break;
                   1499:        case MUX_S_PERMISSION_DENIED:
                   1500:                e = buffer_get_string(&m, NULL);
                   1501:                fatal("Master refused termination request: %s", e);
                   1502:        case MUX_S_FAILURE:
                   1503:                e = buffer_get_string(&m, NULL);
                   1504:                fatal("%s: termination request failed: %s", __func__, e);
                   1505:        default:
                   1506:                fatal("%s: unexpected response from master 0x%08x",
                   1507:                    __func__, type);
                   1508:        }
                   1509:        buffer_free(&m);
                   1510:        muxclient_request_id++;
                   1511: }
                   1512:
                   1513: static int
                   1514: mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
                   1515: {
                   1516:        Buffer m;
                   1517:        char *e, *fwd_desc;
                   1518:        u_int type, rid;
                   1519:
                   1520:        fwd_desc = format_forward(ftype, fwd);
                   1521:        debug("Requesting %s", fwd_desc);
                   1522:        xfree(fwd_desc);
                   1523:
                   1524:        buffer_init(&m);
                   1525:        buffer_put_int(&m, MUX_C_OPEN_FWD);
                   1526:        buffer_put_int(&m, muxclient_request_id);
                   1527:        buffer_put_int(&m, ftype);
                   1528:        buffer_put_cstring(&m,
                   1529:            fwd->listen_host == NULL ? "" : fwd->listen_host);
                   1530:        buffer_put_int(&m, fwd->listen_port);
                   1531:        buffer_put_cstring(&m,
                   1532:            fwd->connect_host == NULL ? "" : fwd->connect_host);
                   1533:        buffer_put_int(&m, fwd->connect_port);
                   1534:
                   1535:        if (mux_client_write_packet(fd, &m) != 0)
                   1536:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1537:
                   1538:        buffer_clear(&m);
                   1539:
                   1540:        /* Read their reply */
                   1541:        if (mux_client_read_packet(fd, &m) != 0) {
                   1542:                buffer_free(&m);
                   1543:                return -1;
                   1544:        }
                   1545:
                   1546:        type = buffer_get_int(&m);
                   1547:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1548:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1549:                    __func__, muxclient_request_id, rid);
                   1550:        switch (type) {
                   1551:        case MUX_S_OK:
1.1       djm      1552:                break;
1.18      markus   1553:        case MUX_S_REMOTE_PORT:
                   1554:                fwd->allocated_port = buffer_get_int(&m);
                   1555:                logit("Allocated port %u for remote forward to %s:%d",
                   1556:                    fwd->allocated_port,
                   1557:                    fwd->connect_host ? fwd->connect_host : "",
                   1558:                    fwd->connect_port);
                   1559:                if (muxclient_command == SSHMUX_COMMAND_FORWARD)
                   1560:                        fprintf(stdout, "%u\n", fwd->allocated_port);
                   1561:                break;
1.10      djm      1562:        case MUX_S_PERMISSION_DENIED:
                   1563:                e = buffer_get_string(&m, NULL);
                   1564:                buffer_free(&m);
                   1565:                error("Master refused forwarding request: %s", e);
                   1566:                return -1;
                   1567:        case MUX_S_FAILURE:
                   1568:                e = buffer_get_string(&m, NULL);
                   1569:                buffer_free(&m);
1.24      djm      1570:                error("%s: forwarding request failed: %s", __func__, e);
1.10      djm      1571:                return -1;
1.1       djm      1572:        default:
1.10      djm      1573:                fatal("%s: unexpected response from master 0x%08x",
                   1574:                    __func__, type);
                   1575:        }
                   1576:        buffer_free(&m);
                   1577:
                   1578:        muxclient_request_id++;
                   1579:        return 0;
                   1580: }
                   1581:
                   1582: static int
                   1583: mux_client_request_forwards(int fd)
                   1584: {
                   1585:        int i;
                   1586:
                   1587:        debug3("%s: requesting forwardings: %d local, %d remote", __func__,
                   1588:            options.num_local_forwards, options.num_remote_forwards);
                   1589:
                   1590:        /* XXX ExitOnForwardingFailure */
                   1591:        for (i = 0; i < options.num_local_forwards; i++) {
                   1592:                if (mux_client_request_forward(fd,
                   1593:                    options.local_forwards[i].connect_port == 0 ?
                   1594:                    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
                   1595:                    options.local_forwards + i) != 0)
                   1596:                        return -1;
                   1597:        }
                   1598:        for (i = 0; i < options.num_remote_forwards; i++) {
                   1599:                if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
                   1600:                    options.remote_forwards + i) != 0)
                   1601:                        return -1;
                   1602:        }
                   1603:        return 0;
                   1604: }
                   1605:
                   1606: static int
                   1607: mux_client_request_session(int fd)
                   1608: {
                   1609:        Buffer m;
                   1610:        char *e, *term;
                   1611:        u_int i, rid, sid, esid, exitval, type, exitval_seen;
                   1612:        extern char **environ;
1.28    ! djm      1613:        int devnull, rawmode;
1.10      djm      1614:
                   1615:        debug3("%s: entering", __func__);
                   1616:
                   1617:        if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
                   1618:                error("%s: master alive request failed", __func__);
                   1619:                return -1;
1.1       djm      1620:        }
                   1621:
1.10      djm      1622:        signal(SIGPIPE, SIG_IGN);
                   1623:
                   1624:        if (stdin_null_flag) {
                   1625:                if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1626:                        fatal("open(/dev/null): %s", strerror(errno));
                   1627:                if (dup2(devnull, STDIN_FILENO) == -1)
                   1628:                        fatal("dup2: %s", strerror(errno));
                   1629:                if (devnull > STDERR_FILENO)
                   1630:                        close(devnull);
1.5       djm      1631:        }
1.1       djm      1632:
1.10      djm      1633:        term = getenv("TERM");
                   1634:
                   1635:        buffer_init(&m);
                   1636:        buffer_put_int(&m, MUX_C_NEW_SESSION);
                   1637:        buffer_put_int(&m, muxclient_request_id);
                   1638:        buffer_put_cstring(&m, ""); /* reserved */
                   1639:        buffer_put_int(&m, tty_flag);
                   1640:        buffer_put_int(&m, options.forward_x11);
                   1641:        buffer_put_int(&m, options.forward_agent);
                   1642:        buffer_put_int(&m, subsystem_flag);
                   1643:        buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
                   1644:            0xffffffff : (u_int)options.escape_char);
                   1645:        buffer_put_cstring(&m, term == NULL ? "" : term);
                   1646:        buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
                   1647:
                   1648:        if (options.num_send_env > 0 && environ != NULL) {
                   1649:                /* Pass environment */
                   1650:                for (i = 0; environ[i] != NULL; i++) {
                   1651:                        if (env_permitted(environ[i])) {
                   1652:                                buffer_put_cstring(&m, environ[i]);
                   1653:                        }
                   1654:                }
1.5       djm      1655:        }
                   1656:
1.10      djm      1657:        if (mux_client_write_packet(fd, &m) != 0)
                   1658:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1659:
                   1660:        /* Send the stdio file descriptors */
                   1661:        if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
                   1662:            mm_send_fd(fd, STDOUT_FILENO) == -1 ||
                   1663:            mm_send_fd(fd, STDERR_FILENO) == -1)
                   1664:                fatal("%s: send fds failed", __func__);
                   1665:
                   1666:        debug3("%s: session request sent", __func__);
1.1       djm      1667:
1.10      djm      1668:        /* Read their reply */
1.1       djm      1669:        buffer_clear(&m);
1.10      djm      1670:        if (mux_client_read_packet(fd, &m) != 0) {
                   1671:                error("%s: read from master failed: %s",
                   1672:                    __func__, strerror(errno));
                   1673:                buffer_free(&m);
                   1674:                return -1;
                   1675:        }
                   1676:
                   1677:        type = buffer_get_int(&m);
                   1678:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1679:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1680:                    __func__, muxclient_request_id, rid);
                   1681:        switch (type) {
                   1682:        case MUX_S_SESSION_OPENED:
                   1683:                sid = buffer_get_int(&m);
                   1684:                debug("%s: master session id: %u", __func__, sid);
                   1685:                break;
                   1686:        case MUX_S_PERMISSION_DENIED:
                   1687:                e = buffer_get_string(&m, NULL);
                   1688:                buffer_free(&m);
1.24      djm      1689:                error("Master refused session request: %s", e);
1.10      djm      1690:                return -1;
                   1691:        case MUX_S_FAILURE:
                   1692:                e = buffer_get_string(&m, NULL);
                   1693:                buffer_free(&m);
1.24      djm      1694:                error("%s: session request failed: %s", __func__, e);
1.10      djm      1695:                return -1;
                   1696:        default:
                   1697:                buffer_free(&m);
                   1698:                error("%s: unexpected response from master 0x%08x",
                   1699:                    __func__, type);
                   1700:                return -1;
                   1701:        }
                   1702:        muxclient_request_id++;
1.1       djm      1703:
                   1704:        signal(SIGHUP, control_client_sighandler);
                   1705:        signal(SIGINT, control_client_sighandler);
                   1706:        signal(SIGTERM, control_client_sighandler);
                   1707:        signal(SIGWINCH, control_client_sigrelay);
                   1708:
1.28    ! djm      1709:        rawmode = tty_flag;
1.1       djm      1710:        if (tty_flag)
1.27      djm      1711:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.1       djm      1712:
                   1713:        /*
                   1714:         * Stick around until the controlee closes the client_fd.
1.10      djm      1715:         * Before it does, it is expected to write an exit message.
                   1716:         * This process must read the value and wait for the closure of
                   1717:         * the client_fd; if this one closes early, the multiplex master will
                   1718:         * terminate early too (possibly losing data).
1.1       djm      1719:         */
1.10      djm      1720:        for (exitval = 255, exitval_seen = 0;;) {
                   1721:                buffer_clear(&m);
                   1722:                if (mux_client_read_packet(fd, &m) != 0)
1.1       djm      1723:                        break;
1.10      djm      1724:                type = buffer_get_int(&m);
1.28    ! djm      1725:                switch (type) {
        !          1726:                case MUX_S_TTY_ALLOC_FAIL:
        !          1727:                        if ((esid = buffer_get_int(&m)) != sid)
        !          1728:                                fatal("%s: tty alloc fail on unknown session: "
        !          1729:                                    "my id %u theirs %u",
        !          1730:                                    __func__, sid, esid);
        !          1731:                        leave_raw_mode(options.request_tty ==
        !          1732:                            REQUEST_TTY_FORCE);
        !          1733:                        rawmode = 0;
        !          1734:                        continue;
        !          1735:                case MUX_S_EXIT_MESSAGE:
        !          1736:                        if ((esid = buffer_get_int(&m)) != sid)
        !          1737:                                fatal("%s: exit on unknown session: "
        !          1738:                                    "my id %u theirs %u",
        !          1739:                                    __func__, sid, esid);
        !          1740:                        if (exitval_seen)
        !          1741:                                fatal("%s: exitval sent twice", __func__);
        !          1742:                        exitval = buffer_get_int(&m);
        !          1743:                        exitval_seen = 1;
        !          1744:                        continue;
        !          1745:                default:
1.10      djm      1746:                        e = buffer_get_string(&m, NULL);
                   1747:                        fatal("%s: master returned error: %s", __func__, e);
1.1       djm      1748:                }
                   1749:        }
                   1750:
1.10      djm      1751:        close(fd);
1.28    ! djm      1752:        if (rawmode)
        !          1753:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.10      djm      1754:
1.1       djm      1755:        if (muxclient_terminate) {
                   1756:                debug2("Exiting on signal %d", muxclient_terminate);
1.10      djm      1757:                exitval = 255;
                   1758:        } else if (!exitval_seen) {
1.1       djm      1759:                debug2("Control master terminated unexpectedly");
1.10      djm      1760:                exitval = 255;
1.1       djm      1761:        } else
1.10      djm      1762:                debug2("Received exit status from master %d", exitval);
1.1       djm      1763:
                   1764:        if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
                   1765:                fprintf(stderr, "Shared connection to %s closed.\r\n", host);
                   1766:
1.10      djm      1767:        exit(exitval);
                   1768: }
                   1769:
                   1770: static int
                   1771: mux_client_request_stdio_fwd(int fd)
                   1772: {
                   1773:        Buffer m;
                   1774:        char *e;
                   1775:        u_int type, rid, sid;
                   1776:        int devnull;
                   1777:
                   1778:        debug3("%s: entering", __func__);
                   1779:
                   1780:        if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
                   1781:                error("%s: master alive request failed", __func__);
                   1782:                return -1;
                   1783:        }
                   1784:
                   1785:        signal(SIGPIPE, SIG_IGN);
                   1786:
                   1787:        if (stdin_null_flag) {
                   1788:                if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1789:                        fatal("open(/dev/null): %s", strerror(errno));
                   1790:                if (dup2(devnull, STDIN_FILENO) == -1)
                   1791:                        fatal("dup2: %s", strerror(errno));
                   1792:                if (devnull > STDERR_FILENO)
                   1793:                        close(devnull);
                   1794:        }
                   1795:
                   1796:        buffer_init(&m);
                   1797:        buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
                   1798:        buffer_put_int(&m, muxclient_request_id);
                   1799:        buffer_put_cstring(&m, ""); /* reserved */
                   1800:        buffer_put_cstring(&m, stdio_forward_host);
                   1801:        buffer_put_int(&m, stdio_forward_port);
                   1802:
                   1803:        if (mux_client_write_packet(fd, &m) != 0)
                   1804:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1805:
                   1806:        /* Send the stdio file descriptors */
                   1807:        if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
                   1808:            mm_send_fd(fd, STDOUT_FILENO) == -1)
                   1809:                fatal("%s: send fds failed", __func__);
                   1810:
                   1811:        debug3("%s: stdio forward request sent", __func__);
                   1812:
                   1813:        /* Read their reply */
                   1814:        buffer_clear(&m);
                   1815:
                   1816:        if (mux_client_read_packet(fd, &m) != 0) {
                   1817:                error("%s: read from master failed: %s",
                   1818:                    __func__, strerror(errno));
                   1819:                buffer_free(&m);
                   1820:                return -1;
                   1821:        }
                   1822:
                   1823:        type = buffer_get_int(&m);
                   1824:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1825:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1826:                    __func__, muxclient_request_id, rid);
                   1827:        switch (type) {
                   1828:        case MUX_S_SESSION_OPENED:
                   1829:                sid = buffer_get_int(&m);
                   1830:                debug("%s: master session id: %u", __func__, sid);
                   1831:                break;
                   1832:        case MUX_S_PERMISSION_DENIED:
                   1833:                e = buffer_get_string(&m, NULL);
                   1834:                buffer_free(&m);
1.24      djm      1835:                fatal("Master refused stdio forwarding request: %s", e);
1.10      djm      1836:        case MUX_S_FAILURE:
                   1837:                e = buffer_get_string(&m, NULL);
                   1838:                buffer_free(&m);
                   1839:                fatal("%s: stdio forwarding request failed: %s", __func__, e);
                   1840:        default:
                   1841:                buffer_free(&m);
                   1842:                error("%s: unexpected response from master 0x%08x",
                   1843:                    __func__, type);
                   1844:                return -1;
                   1845:        }
                   1846:        muxclient_request_id++;
                   1847:
                   1848:        signal(SIGHUP, control_client_sighandler);
                   1849:        signal(SIGINT, control_client_sighandler);
                   1850:        signal(SIGTERM, control_client_sighandler);
                   1851:        signal(SIGWINCH, control_client_sigrelay);
                   1852:
                   1853:        /*
                   1854:         * Stick around until the controlee closes the client_fd.
                   1855:         */
                   1856:        buffer_clear(&m);
                   1857:        if (mux_client_read_packet(fd, &m) != 0) {
                   1858:                if (errno == EPIPE ||
                   1859:                    (errno == EINTR && muxclient_terminate != 0))
                   1860:                        return 0;
                   1861:                fatal("%s: mux_client_read_packet: %s",
                   1862:                    __func__, strerror(errno));
                   1863:        }
                   1864:        fatal("%s: master returned unexpected message %u", __func__, type);
                   1865: }
                   1866:
1.25      djm      1867: static void
                   1868: mux_client_request_stop_listening(int fd)
                   1869: {
                   1870:        Buffer m;
                   1871:        char *e;
                   1872:        u_int type, rid;
                   1873:
                   1874:        debug3("%s: entering", __func__);
                   1875:
                   1876:        buffer_init(&m);
                   1877:        buffer_put_int(&m, MUX_C_STOP_LISTENING);
                   1878:        buffer_put_int(&m, muxclient_request_id);
                   1879:
                   1880:        if (mux_client_write_packet(fd, &m) != 0)
                   1881:                fatal("%s: write packet: %s", __func__, strerror(errno));
                   1882:
                   1883:        buffer_clear(&m);
                   1884:
                   1885:        /* Read their reply */
                   1886:        if (mux_client_read_packet(fd, &m) != 0)
                   1887:                fatal("%s: read from master failed: %s",
                   1888:                    __func__, strerror(errno));
                   1889:
                   1890:        type = buffer_get_int(&m);
                   1891:        if ((rid = buffer_get_int(&m)) != muxclient_request_id)
                   1892:                fatal("%s: out of sequence reply: my id %u theirs %u",
                   1893:                    __func__, muxclient_request_id, rid);
                   1894:        switch (type) {
                   1895:        case MUX_S_OK:
                   1896:                break;
                   1897:        case MUX_S_PERMISSION_DENIED:
                   1898:                e = buffer_get_string(&m, NULL);
                   1899:                fatal("Master refused stop listening request: %s", e);
                   1900:        case MUX_S_FAILURE:
                   1901:                e = buffer_get_string(&m, NULL);
                   1902:                fatal("%s: stop listening request failed: %s", __func__, e);
                   1903:        default:
                   1904:                fatal("%s: unexpected response from master 0x%08x",
                   1905:                    __func__, type);
                   1906:        }
                   1907:        buffer_free(&m);
                   1908:        muxclient_request_id++;
                   1909: }
                   1910:
1.10      djm      1911: /* Multiplex client main loop. */
                   1912: void
                   1913: muxclient(const char *path)
                   1914: {
                   1915:        struct sockaddr_un addr;
                   1916:        int sock;
                   1917:        u_int pid;
                   1918:
                   1919:        if (muxclient_command == 0) {
                   1920:                if (stdio_forward_host != NULL)
                   1921:                        muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
                   1922:                else
                   1923:                        muxclient_command = SSHMUX_COMMAND_OPEN;
                   1924:        }
                   1925:
                   1926:        switch (options.control_master) {
                   1927:        case SSHCTL_MASTER_AUTO:
                   1928:        case SSHCTL_MASTER_AUTO_ASK:
                   1929:                debug("auto-mux: Trying existing master");
                   1930:                /* FALLTHROUGH */
                   1931:        case SSHCTL_MASTER_NO:
                   1932:                break;
                   1933:        default:
                   1934:                return;
                   1935:        }
                   1936:
                   1937:        memset(&addr, '\0', sizeof(addr));
                   1938:        addr.sun_family = AF_UNIX;
                   1939:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1940:            strlen(path) + 1;
                   1941:
                   1942:        if (strlcpy(addr.sun_path, path,
                   1943:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1944:                fatal("ControlPath too long");
                   1945:
                   1946:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1947:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1948:
                   1949:        if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
                   1950:                switch (muxclient_command) {
                   1951:                case SSHMUX_COMMAND_OPEN:
                   1952:                case SSHMUX_COMMAND_STDIO_FWD:
                   1953:                        break;
                   1954:                default:
                   1955:                        fatal("Control socket connect(%.100s): %s", path,
                   1956:                            strerror(errno));
                   1957:                }
1.22      djm      1958:                if (errno == ECONNREFUSED &&
                   1959:                    options.control_master != SSHCTL_MASTER_NO) {
                   1960:                        debug("Stale control socket %.100s, unlinking", path);
                   1961:                        unlink(path);
                   1962:                } else if (errno == ENOENT) {
1.10      djm      1963:                        debug("Control socket \"%.100s\" does not exist", path);
1.22      djm      1964:                } else {
1.10      djm      1965:                        error("Control socket connect(%.100s): %s", path,
                   1966:                            strerror(errno));
                   1967:                }
                   1968:                close(sock);
                   1969:                return;
                   1970:        }
                   1971:        set_nonblock(sock);
                   1972:
                   1973:        if (mux_client_hello_exchange(sock) != 0) {
                   1974:                error("%s: master hello exchange failed", __func__);
                   1975:                close(sock);
                   1976:                return;
                   1977:        }
                   1978:
                   1979:        switch (muxclient_command) {
                   1980:        case SSHMUX_COMMAND_ALIVE_CHECK:
                   1981:                if ((pid = mux_client_request_alive(sock)) == 0)
                   1982:                        fatal("%s: master alive check failed", __func__);
                   1983:                fprintf(stderr, "Master running (pid=%d)\r\n", pid);
                   1984:                exit(0);
                   1985:        case SSHMUX_COMMAND_TERMINATE:
                   1986:                mux_client_request_terminate(sock);
                   1987:                fprintf(stderr, "Exit request sent.\r\n");
1.18      markus   1988:                exit(0);
                   1989:        case SSHMUX_COMMAND_FORWARD:
                   1990:                if (mux_client_request_forwards(sock) != 0)
                   1991:                        fatal("%s: master forward request failed", __func__);
1.10      djm      1992:                exit(0);
                   1993:        case SSHMUX_COMMAND_OPEN:
                   1994:                if (mux_client_request_forwards(sock) != 0) {
                   1995:                        error("%s: master forward request failed", __func__);
                   1996:                        return;
                   1997:                }
                   1998:                mux_client_request_session(sock);
                   1999:                return;
                   2000:        case SSHMUX_COMMAND_STDIO_FWD:
                   2001:                mux_client_request_stdio_fwd(sock);
1.25      djm      2002:                exit(0);
                   2003:        case SSHMUX_COMMAND_STOP:
                   2004:                mux_client_request_stop_listening(sock);
                   2005:                fprintf(stderr, "Stop listening request sent.\r\n");
1.10      djm      2006:                exit(0);
                   2007:        default:
                   2008:                fatal("unrecognised muxclient_command %d", muxclient_command);
                   2009:        }
1.1       djm      2010: }