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

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