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

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