1 /* $OpenBSD: mux.c,v 1.44 2013/07/12 00:19:58 djm Exp $ */
4 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 /* ssh session multiplexing support */
23 * - Better signalling from master to slave, especially passing of
25 * - Better fall-back from mux slave error to new connection.
26 * - ExitOnForwardingFailure
27 * - Maybe extension mechanisms for multi-X11/multi-agent forwarding
28 * - Support ~^Z in mux slaves.
29 * - Inspect or control sessions in master.
30 * - If we ever support the "signal" channel request, send signals on
37 #include <sys/types.h>
38 #include <sys/param.h>
40 #include <sys/socket.h>
59 # ifdef HAVE_SYS_POLL_H
60 # include <sys/poll.h>
68 #include "openbsd-compat/sys-queue.h"
73 #include "pathnames.h"
80 #include "monitor_fdpass.h"
84 #include "clientloop.h"
88 extern Options options;
89 extern int stdin_null_flag;
91 extern int subsystem_flag;
92 extern Buffer command;
93 extern volatile sig_atomic_t quit_pending;
94 extern char *stdio_forward_host;
95 extern int stdio_forward_port;
97 /* Context for session open confirmation callback */
98 struct mux_session_confirm_ctx {
102 u_int want_agent_fwd;
110 /* Context for global channel callback */
111 struct mux_channel_confirm_ctx {
112 u_int cid; /* channel id */
113 u_int rid; /* request id */
114 int fid; /* forward id */
117 /* fd to control socket */
118 int muxserver_sock = -1;
120 /* client request id */
121 u_int muxclient_request_id = 0;
123 /* Multiplexing control command */
124 u_int muxclient_command = 0;
126 /* Set when signalled. */
127 static volatile sig_atomic_t muxclient_terminate = 0;
129 /* PID of multiplex server */
130 static u_int muxserver_pid = 0;
132 static Channel *mux_listener_channel = NULL;
134 struct mux_master_state {
138 /* mux protocol messages */
139 #define MUX_MSG_HELLO 0x00000001
140 #define MUX_C_NEW_SESSION 0x10000002
141 #define MUX_C_ALIVE_CHECK 0x10000004
142 #define MUX_C_TERMINATE 0x10000005
143 #define MUX_C_OPEN_FWD 0x10000006
144 #define MUX_C_CLOSE_FWD 0x10000007
145 #define MUX_C_NEW_STDIO_FWD 0x10000008
146 #define MUX_C_STOP_LISTENING 0x10000009
147 #define MUX_S_OK 0x80000001
148 #define MUX_S_PERMISSION_DENIED 0x80000002
149 #define MUX_S_FAILURE 0x80000003
150 #define MUX_S_EXIT_MESSAGE 0x80000004
151 #define MUX_S_ALIVE 0x80000005
152 #define MUX_S_SESSION_OPENED 0x80000006
153 #define MUX_S_REMOTE_PORT 0x80000007
154 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
156 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
157 #define MUX_FWD_LOCAL 1
158 #define MUX_FWD_REMOTE 2
159 #define MUX_FWD_DYNAMIC 3
161 static void mux_session_confirm(int, int, void *);
163 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
164 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
165 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
172 static const struct {
174 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
175 } mux_master_handlers[] = {
176 { MUX_MSG_HELLO, process_mux_master_hello },
177 { MUX_C_NEW_SESSION, process_mux_new_session },
178 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
179 { MUX_C_TERMINATE, process_mux_terminate },
180 { MUX_C_OPEN_FWD, process_mux_open_fwd },
181 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
182 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
183 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
187 /* Cleanup callback fired on closure of mux slave _session_ channel */
190 mux_master_session_cleanup_cb(int cid, void *unused)
192 Channel *cc, *c = channel_by_id(cid);
194 debug3("%s: entering for channel %d", __func__, cid);
196 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
197 if (c->ctl_chan != -1) {
198 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
199 fatal("%s: channel %d missing control channel %d",
200 __func__, c->self, c->ctl_chan);
203 chan_rcvd_oclose(cc);
205 channel_cancel_cleanup(c->self);
208 /* Cleanup callback fired on closure of mux slave _control_ channel */
211 mux_master_control_cleanup_cb(int cid, void *unused)
213 Channel *sc, *c = channel_by_id(cid);
215 debug3("%s: entering for channel %d", __func__, cid);
217 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
218 if (c->remote_id != -1) {
219 if ((sc = channel_by_id(c->remote_id)) == NULL)
220 fatal("%s: channel %d missing session channel %d",
221 __func__, c->self, c->remote_id);
224 if (sc->type != SSH_CHANNEL_OPEN &&
225 sc->type != SSH_CHANNEL_OPENING) {
226 debug2("%s: channel %d: not open", __func__, sc->self);
229 if (sc->istate == CHAN_INPUT_OPEN)
230 chan_read_failed(sc);
231 if (sc->ostate == CHAN_OUTPUT_OPEN)
232 chan_write_failed(sc);
235 channel_cancel_cleanup(c->self);
238 /* Check mux client environment variables before passing them to mux master. */
240 env_permitted(char *env)
243 char name[1024], *cp;
245 if ((cp = strchr(env, '=')) == NULL || cp == env)
247 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
248 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
249 error("env_permitted: name '%.100s...' too long", env);
253 for (i = 0; i < options.num_send_env; i++)
254 if (match_pattern(name, options.send_env[i]))
260 /* Mux master protocol message handlers */
263 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
266 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
269 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
270 if (state->hello_rcvd) {
271 error("%s: HELLO received twice", __func__);
274 if (buffer_get_int_ret(&ver, m) != 0) {
276 error("%s: malformed message", __func__);
279 if (ver != SSHMUX_VER) {
280 error("Unsupported multiplexing protocol version %d "
281 "(expected %d)", ver, SSHMUX_VER);
284 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
286 /* No extensions are presently defined */
287 while (buffer_len(m) > 0) {
288 char *name = buffer_get_string_ret(m, NULL);
289 char *value = buffer_get_string_ret(m, NULL);
291 if (name == NULL || value == NULL) {
296 debug2("Unrecognised slave extension \"%s\"", name);
300 state->hello_rcvd = 1;
305 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
308 struct mux_session_confirm_ctx *cctx;
309 char *reserved, *cmd, *cp;
310 u_int i, j, len, env_len, escape_char, window, packetmax;
313 /* Reply for SSHMUX_COMMAND_OPEN */
314 cctx = xcalloc(1, sizeof(*cctx));
317 cmd = reserved = NULL;
320 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
321 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
322 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
323 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
324 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
325 buffer_get_int_ret(&escape_char, m) != 0 ||
326 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
327 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
331 for (j = 0; j < env_len; j++)
336 error("%s: malformed message", __func__);
342 while (buffer_len(m) > 0) {
343 #define MUX_MAX_ENV_VARS 4096
344 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
346 if (!env_permitted(cp)) {
350 cctx->env = xrealloc(cctx->env, env_len + 2,
352 cctx->env[env_len++] = cp;
353 cctx->env[env_len] = NULL;
354 if (env_len > MUX_MAX_ENV_VARS) {
355 error(">%d environment variables received, ignoring "
356 "additional", MUX_MAX_ENV_VARS);
361 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
362 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
363 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
364 cctx->want_subsys, cctx->term, cmd, env_len);
366 buffer_init(&cctx->cmd);
367 buffer_append(&cctx->cmd, cmd, strlen(cmd));
371 /* Gather fds from client */
372 for(i = 0; i < 3; i++) {
373 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
374 error("%s: failed to receive fd %d from slave",
376 for (j = 0; j < i; j++)
378 for (j = 0; j < env_len; j++)
382 buffer_free(&cctx->cmd);
386 buffer_put_int(r, MUX_S_FAILURE);
387 buffer_put_int(r, rid);
388 buffer_put_cstring(r,
389 "did not receive file descriptors");
394 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
395 new_fd[0], new_fd[1], new_fd[2]);
397 /* XXX support multiple child sessions in future */
398 if (c->remote_id != -1) {
399 debug2("%s: session already open", __func__);
401 buffer_put_int(r, MUX_S_FAILURE);
402 buffer_put_int(r, rid);
403 buffer_put_cstring(r, "Multiple sessions not supported");
410 for (i = 0; i < env_len; i++)
414 buffer_free(&cctx->cmd);
419 if (options.control_master == SSHCTL_MASTER_ASK ||
420 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
421 if (!ask_permission("Allow shared connection to %s? ", host)) {
422 debug2("%s: session refused by user", __func__);
424 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
425 buffer_put_int(r, rid);
426 buffer_put_cstring(r, "Permission denied");
431 /* Try to pick up ttymodes from client before it goes raw */
432 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
433 error("%s: tcgetattr: %s", __func__, strerror(errno));
435 /* enable nonblocking unless tty */
436 if (!isatty(new_fd[0]))
437 set_nonblock(new_fd[0]);
438 if (!isatty(new_fd[1]))
439 set_nonblock(new_fd[1]);
440 if (!isatty(new_fd[2]))
441 set_nonblock(new_fd[2]);
443 window = CHAN_SES_WINDOW_DEFAULT;
444 packetmax = CHAN_SES_PACKET_DEFAULT;
445 if (cctx->want_tty) {
450 nc = channel_new("session", SSH_CHANNEL_OPENING,
451 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
452 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
454 nc->ctl_chan = c->self; /* link session -> control channel */
455 c->remote_id = nc->self; /* link control -> session channel */
457 if (cctx->want_tty && escape_char != 0xffffffff) {
458 channel_register_filter(nc->self,
459 client_simple_escape_filter, NULL,
460 client_filter_cleanup,
461 client_new_escape_filter_ctx((int)escape_char));
464 debug2("%s: channel_new: %d linked to control channel %d",
465 __func__, nc->self, nc->ctl_chan);
467 channel_send_open(nc->self);
468 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
469 c->mux_pause = 1; /* stop handling messages until open_confirm done */
470 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
472 /* reply is deferred, sent by mux_session_confirm */
477 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
479 debug2("%s: channel %d: alive check", __func__, c->self);
482 buffer_put_int(r, MUX_S_ALIVE);
483 buffer_put_int(r, rid);
484 buffer_put_int(r, (u_int)getpid());
490 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
492 debug2("%s: channel %d: terminate request", __func__, c->self);
494 if (options.control_master == SSHCTL_MASTER_ASK ||
495 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
496 if (!ask_permission("Terminate shared connection to %s? ",
498 debug2("%s: termination refused by user", __func__);
499 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
500 buffer_put_int(r, rid);
501 buffer_put_cstring(r, "Permission denied");
507 buffer_put_int(r, MUX_S_OK);
508 buffer_put_int(r, rid);
509 /* XXX exit happens too soon - message never makes it to client */
514 format_forward(u_int ftype, Forward *fwd)
520 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
521 (fwd->listen_host == NULL) ?
522 (options.gateway_ports ? "*" : "LOCALHOST") :
523 fwd->listen_host, fwd->listen_port,
524 fwd->connect_host, fwd->connect_port);
526 case MUX_FWD_DYNAMIC:
527 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
528 (fwd->listen_host == NULL) ?
529 (options.gateway_ports ? "*" : "LOCALHOST") :
530 fwd->listen_host, fwd->listen_port);
533 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
534 (fwd->listen_host == NULL) ?
535 "LOCALHOST" : fwd->listen_host,
537 fwd->connect_host, fwd->connect_port);
540 fatal("%s: unknown forward type %u", __func__, ftype);
546 compare_host(const char *a, const char *b)
548 if (a == NULL && b == NULL)
550 if (a == NULL || b == NULL)
552 return strcmp(a, b) == 0;
556 compare_forward(Forward *a, Forward *b)
558 if (!compare_host(a->listen_host, b->listen_host))
560 if (a->listen_port != b->listen_port)
562 if (!compare_host(a->connect_host, b->connect_host))
564 if (a->connect_port != b->connect_port)
571 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
573 struct mux_channel_confirm_ctx *fctx = ctxt;
574 char *failmsg = NULL;
579 if ((c = channel_by_id(fctx->cid)) == NULL) {
580 /* no channel for reply */
581 error("%s: unknown channel", __func__);
585 if (fctx->fid >= options.num_remote_forwards) {
586 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
589 rfwd = &options.remote_forwards[fctx->fid];
590 debug("%s: %s for: listen %d, connect %s:%d", __func__,
591 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
592 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
593 if (type == SSH2_MSG_REQUEST_SUCCESS) {
594 if (rfwd->listen_port == 0) {
595 rfwd->allocated_port = packet_get_int();
596 logit("Allocated port %u for mux remote forward"
597 " to %s:%d", rfwd->allocated_port,
598 rfwd->connect_host, rfwd->connect_port);
599 buffer_put_int(&out, MUX_S_REMOTE_PORT);
600 buffer_put_int(&out, fctx->rid);
601 buffer_put_int(&out, rfwd->allocated_port);
602 channel_update_permitted_opens(rfwd->handle,
603 rfwd->allocated_port);
605 buffer_put_int(&out, MUX_S_OK);
606 buffer_put_int(&out, fctx->rid);
610 if (rfwd->listen_port == 0)
611 channel_update_permitted_opens(rfwd->handle, -1);
612 xasprintf(&failmsg, "remote port forwarding failed for "
613 "listen port %d", rfwd->listen_port);
616 error("%s: %s", __func__, failmsg);
617 buffer_put_int(&out, MUX_S_FAILURE);
618 buffer_put_int(&out, fctx->rid);
619 buffer_put_cstring(&out, failmsg);
622 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
624 if (c->mux_pause <= 0)
625 fatal("%s: mux_pause %d", __func__, c->mux_pause);
626 c->mux_pause = 0; /* start processing messages again */
630 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
633 char *fwd_desc = NULL;
636 int i, ret = 0, freefwd = 1;
638 fwd.listen_host = fwd.connect_host = NULL;
639 if (buffer_get_int_ret(&ftype, m) != 0 ||
640 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
641 buffer_get_int_ret(&lport, m) != 0 ||
642 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
643 buffer_get_int_ret(&cport, m) != 0 ||
644 lport > 65535 || cport > 65535) {
645 error("%s: malformed message", __func__);
649 fwd.listen_port = lport;
650 fwd.connect_port = cport;
651 if (*fwd.listen_host == '\0') {
652 free(fwd.listen_host);
653 fwd.listen_host = NULL;
655 if (*fwd.connect_host == '\0') {
656 free(fwd.connect_host);
657 fwd.connect_host = NULL;
660 debug2("%s: channel %d: request %s", __func__, c->self,
661 (fwd_desc = format_forward(ftype, &fwd)));
663 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
664 ftype != MUX_FWD_DYNAMIC) {
665 logit("%s: invalid forwarding type %u", __func__, ftype);
667 free(fwd.listen_host);
668 free(fwd.connect_host);
669 buffer_put_int(r, MUX_S_FAILURE);
670 buffer_put_int(r, rid);
671 buffer_put_cstring(r, "Invalid forwarding request");
674 if (fwd.listen_port >= 65536) {
675 logit("%s: invalid listen port %u", __func__,
679 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
680 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
681 logit("%s: invalid connect port %u", __func__,
685 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
686 logit("%s: missing connect host", __func__);
690 /* Skip forwards that have already been requested */
693 case MUX_FWD_DYNAMIC:
694 for (i = 0; i < options.num_local_forwards; i++) {
695 if (compare_forward(&fwd,
696 options.local_forwards + i)) {
698 debug2("%s: found existing forwarding",
700 buffer_put_int(r, MUX_S_OK);
701 buffer_put_int(r, rid);
707 for (i = 0; i < options.num_remote_forwards; i++) {
708 if (compare_forward(&fwd,
709 options.remote_forwards + i)) {
710 if (fwd.listen_port != 0)
712 debug2("%s: found allocated port",
714 buffer_put_int(r, MUX_S_REMOTE_PORT);
715 buffer_put_int(r, rid);
717 options.remote_forwards[i].allocated_port);
724 if (options.control_master == SSHCTL_MASTER_ASK ||
725 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
726 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
727 debug2("%s: forwarding refused by user", __func__);
728 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
729 buffer_put_int(r, rid);
730 buffer_put_cstring(r, "Permission denied");
735 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
736 if (!channel_setup_local_fwd_listener(fwd.listen_host,
737 fwd.listen_port, fwd.connect_host, fwd.connect_port,
738 options.gateway_ports)) {
740 logit("slave-requested %s failed", fwd_desc);
741 buffer_put_int(r, MUX_S_FAILURE);
742 buffer_put_int(r, rid);
743 buffer_put_cstring(r, "Port forwarding failed");
746 add_local_forward(&options, &fwd);
749 struct mux_channel_confirm_ctx *fctx;
751 fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
752 fwd.listen_port, fwd.connect_host, fwd.connect_port);
755 add_remote_forward(&options, &fwd);
756 fctx = xcalloc(1, sizeof(*fctx));
759 fctx->fid = options.num_remote_forwards - 1;
760 client_register_global_confirm(mux_confirm_remote_forward,
763 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
764 /* delayed reply in mux_confirm_remote_forward */
767 buffer_put_int(r, MUX_S_OK);
768 buffer_put_int(r, rid);
772 free(fwd.listen_host);
773 free(fwd.connect_host);
779 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
781 Forward fwd, *found_fwd;
782 char *fwd_desc = NULL;
783 const char *error_reason = NULL;
785 int i, listen_port, ret = 0;
788 fwd.listen_host = fwd.connect_host = NULL;
789 if (buffer_get_int_ret(&ftype, m) != 0 ||
790 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
791 buffer_get_int_ret(&lport, m) != 0 ||
792 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
793 buffer_get_int_ret(&cport, m) != 0 ||
794 lport > 65535 || cport > 65535) {
795 error("%s: malformed message", __func__);
799 fwd.listen_port = lport;
800 fwd.connect_port = cport;
802 if (*fwd.listen_host == '\0') {
803 free(fwd.listen_host);
804 fwd.listen_host = NULL;
806 if (*fwd.connect_host == '\0') {
807 free(fwd.connect_host);
808 fwd.connect_host = NULL;
811 debug2("%s: channel %d: request cancel %s", __func__, c->self,
812 (fwd_desc = format_forward(ftype, &fwd)));
814 /* make sure this has been requested */
818 case MUX_FWD_DYNAMIC:
819 for (i = 0; i < options.num_local_forwards; i++) {
820 if (compare_forward(&fwd,
821 options.local_forwards + i)) {
822 found_fwd = options.local_forwards + i;
828 for (i = 0; i < options.num_remote_forwards; i++) {
829 if (compare_forward(&fwd,
830 options.remote_forwards + i)) {
831 found_fwd = options.remote_forwards + i;
838 if (found_fwd == NULL)
839 error_reason = "port not forwarded";
840 else if (ftype == MUX_FWD_REMOTE) {
842 * This shouldn't fail unless we confused the host/port
843 * between options.remote_forwards and permitted_opens.
844 * However, for dynamic allocated listen ports we need
845 * to lookup the actual listen port.
847 listen_port = (fwd.listen_port == 0) ?
848 found_fwd->allocated_port : fwd.listen_port;
849 if (channel_request_rforward_cancel(fwd.listen_host,
851 error_reason = "port not in permitted opens";
852 } else { /* local and dynamic forwards */
854 if (channel_cancel_lport_listener(fwd.listen_host,
855 fwd.listen_port, fwd.connect_port,
856 options.gateway_ports) == -1)
857 error_reason = "port not found";
860 if (error_reason == NULL) {
861 buffer_put_int(r, MUX_S_OK);
862 buffer_put_int(r, rid);
864 free(found_fwd->listen_host);
865 free(found_fwd->connect_host);
866 found_fwd->listen_host = found_fwd->connect_host = NULL;
867 found_fwd->listen_port = found_fwd->connect_port = 0;
869 buffer_put_int(r, MUX_S_FAILURE);
870 buffer_put_int(r, rid);
871 buffer_put_cstring(r, error_reason);
875 free(fwd.listen_host);
876 free(fwd.connect_host);
882 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
885 char *reserved, *chost;
889 chost = reserved = NULL;
890 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
891 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
892 buffer_get_int_ret(&cport, m) != 0) {
895 error("%s: malformed message", __func__);
900 debug2("%s: channel %d: request stdio fwd to %s:%u",
901 __func__, c->self, chost, cport);
903 /* Gather fds from client */
904 for(i = 0; i < 2; i++) {
905 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
906 error("%s: failed to receive fd %d from slave",
908 for (j = 0; j < i; j++)
913 buffer_put_int(r, MUX_S_FAILURE);
914 buffer_put_int(r, rid);
915 buffer_put_cstring(r,
916 "did not receive file descriptors");
921 debug3("%s: got fds stdin %d, stdout %d", __func__,
922 new_fd[0], new_fd[1]);
924 /* XXX support multiple child sessions in future */
925 if (c->remote_id != -1) {
926 debug2("%s: session already open", __func__);
928 buffer_put_int(r, MUX_S_FAILURE);
929 buffer_put_int(r, rid);
930 buffer_put_cstring(r, "Multiple sessions not supported");
938 if (options.control_master == SSHCTL_MASTER_ASK ||
939 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
940 if (!ask_permission("Allow forward to %s:%u? ",
942 debug2("%s: stdio fwd refused by user", __func__);
944 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
945 buffer_put_int(r, rid);
946 buffer_put_cstring(r, "Permission denied");
951 /* enable nonblocking unless tty */
952 if (!isatty(new_fd[0]))
953 set_nonblock(new_fd[0]);
954 if (!isatty(new_fd[1]))
955 set_nonblock(new_fd[1]);
957 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
959 nc->ctl_chan = c->self; /* link session -> control channel */
960 c->remote_id = nc->self; /* link control -> session channel */
962 debug2("%s: channel_new: %d linked to control channel %d",
963 __func__, nc->self, nc->ctl_chan);
965 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
968 /* XXX defer until channel confirmed */
969 buffer_put_int(r, MUX_S_SESSION_OPENED);
970 buffer_put_int(r, rid);
971 buffer_put_int(r, nc->self);
977 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
979 debug("%s: channel %d: stop listening", __func__, c->self);
981 if (options.control_master == SSHCTL_MASTER_ASK ||
982 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
983 if (!ask_permission("Disable further multiplexing on shared "
984 "connection to %s? ", host)) {
985 debug2("%s: stop listen refused by user", __func__);
986 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
987 buffer_put_int(r, rid);
988 buffer_put_cstring(r, "Permission denied");
993 if (mux_listener_channel != NULL) {
994 channel_free(mux_listener_channel);
996 free(options.control_path);
997 options.control_path = NULL;
998 mux_listener_channel = NULL;
1003 buffer_put_int(r, MUX_S_OK);
1004 buffer_put_int(r, rid);
1009 /* Channel callbacks fired on read/write from mux slave fd */
1011 mux_master_read_cb(Channel *c)
1013 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1016 u_int type, rid, have, i;
1020 if (c->mux_ctx == NULL) {
1021 state = xcalloc(1, sizeof(*state));
1023 channel_register_cleanup(c->self,
1024 mux_master_control_cleanup_cb, 0);
1028 buffer_put_int(&out, MUX_MSG_HELLO);
1029 buffer_put_int(&out, SSHMUX_VER);
1031 buffer_put_string(&c->output, buffer_ptr(&out),
1034 debug3("%s: channel %d: hello sent", __func__, c->self);
1041 /* Channel code ensures that we receive whole packets */
1042 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1044 error("%s: malformed message", __func__);
1047 buffer_append(&in, ptr, have);
1049 if (buffer_get_int_ret(&type, &in) != 0)
1051 debug3("%s: channel %d packet type 0x%08x len %u",
1052 __func__, c->self, type, buffer_len(&in));
1054 if (type == MUX_MSG_HELLO)
1057 if (!state->hello_rcvd) {
1058 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1059 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1062 if (buffer_get_int_ret(&rid, &in) != 0)
1066 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1067 if (type == mux_master_handlers[i].type) {
1068 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1072 if (mux_master_handlers[i].handler == NULL) {
1073 error("%s: unsupported mux message 0x%08x", __func__, type);
1074 buffer_put_int(&out, MUX_S_FAILURE);
1075 buffer_put_int(&out, rid);
1076 buffer_put_cstring(&out, "unsupported request");
1079 /* Enqueue reply packet */
1080 if (buffer_len(&out) != 0) {
1081 buffer_put_string(&c->output, buffer_ptr(&out),
1091 mux_exit_message(Channel *c, int exitval)
1096 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1099 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1100 fatal("%s: channel %d missing mux channel %d",
1101 __func__, c->self, c->ctl_chan);
1103 /* Append exit message packet to control socket output queue */
1105 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1106 buffer_put_int(&m, c->self);
1107 buffer_put_int(&m, exitval);
1109 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1114 mux_tty_alloc_failed(Channel *c)
1119 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1121 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1122 fatal("%s: channel %d missing mux channel %d",
1123 __func__, c->self, c->ctl_chan);
1125 /* Append exit message packet to control socket output queue */
1127 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1128 buffer_put_int(&m, c->self);
1130 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1134 /* Prepare a mux master to listen on a Unix domain socket. */
1136 muxserver_listen(void)
1138 struct sockaddr_un addr;
1141 char *orig_control_path = options.control_path;
1145 if (options.control_path == NULL ||
1146 options.control_master == SSHCTL_MASTER_NO)
1149 debug("setting up multiplex master socket");
1152 * Use a temporary path before listen so we can pseudo-atomically
1153 * establish the listening socket in its final location to avoid
1154 * other processes racing in between bind() and listen() and hitting
1155 * an unready socket.
1157 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1158 r = arc4random_uniform(26+26+10);
1159 rbuf[i] = (r < 26) ? 'a' + r :
1160 (r < 26*2) ? 'A' + r - 26 :
1163 rbuf[sizeof(rbuf) - 1] = '\0';
1164 options.control_path = NULL;
1165 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1166 debug3("%s: temporary control path %s", __func__, options.control_path);
1168 memset(&addr, '\0', sizeof(addr));
1169 addr.sun_family = AF_UNIX;
1170 sun_len = offsetof(struct sockaddr_un, sun_path) +
1171 strlen(options.control_path) + 1;
1173 if (strlcpy(addr.sun_path, options.control_path,
1174 sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1175 error("ControlPath \"%s\" too long for Unix domain socket",
1176 options.control_path);
1177 goto disable_mux_master;
1180 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1181 fatal("%s socket(): %s", __func__, strerror(errno));
1183 old_umask = umask(0177);
1184 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1185 if (errno == EINVAL || errno == EADDRINUSE) {
1186 error("ControlSocket %s already exists, "
1187 "disabling multiplexing", options.control_path);
1189 if (muxserver_sock != -1) {
1190 close(muxserver_sock);
1191 muxserver_sock = -1;
1193 free(orig_control_path);
1194 free(options.control_path);
1195 options.control_path = NULL;
1196 options.control_master = SSHCTL_MASTER_NO;
1199 fatal("%s bind(): %s", __func__, strerror(errno));
1203 if (listen(muxserver_sock, 64) == -1)
1204 fatal("%s listen(): %s", __func__, strerror(errno));
1206 /* Now atomically "move" the mux socket into position */
1207 if (link(options.control_path, orig_control_path) != 0) {
1208 if (errno != EEXIST) {
1209 fatal("%s: link mux listener %s => %s: %s", __func__,
1210 options.control_path, orig_control_path,
1213 error("ControlSocket %s already exists, disabling multiplexing",
1215 unlink(options.control_path);
1216 goto disable_mux_master;
1218 unlink(options.control_path);
1219 free(options.control_path);
1220 options.control_path = orig_control_path;
1222 set_nonblock(muxserver_sock);
1224 mux_listener_channel = channel_new("mux listener",
1225 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1226 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1227 0, options.control_path, 1);
1228 mux_listener_channel->mux_rcb = mux_master_read_cb;
1229 debug3("%s: mux listener channel %d fd %d", __func__,
1230 mux_listener_channel->self, mux_listener_channel->sock);
1233 /* Callback on open confirmation in mux master for a mux client session. */
1235 mux_session_confirm(int id, int success, void *arg)
1237 struct mux_session_confirm_ctx *cctx = arg;
1238 const char *display;
1244 fatal("%s: cctx == NULL", __func__);
1245 if ((c = channel_by_id(id)) == NULL)
1246 fatal("%s: no channel for id %d", __func__, id);
1247 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1248 fatal("%s: channel %d lacks control channel %d", __func__,
1252 debug3("%s: sending failure reply", __func__);
1254 buffer_init(&reply);
1255 buffer_put_int(&reply, MUX_S_FAILURE);
1256 buffer_put_int(&reply, cctx->rid);
1257 buffer_put_cstring(&reply, "Session open refused by peer");
1261 display = getenv("DISPLAY");
1262 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1265 /* Get reasonable local authentication information. */
1266 client_x11_get_proto(display, options.xauth_location,
1267 options.forward_x11_trusted, options.forward_x11_timeout,
1269 /* Request forwarding with authentication spoofing. */
1270 debug("Requesting X11 forwarding with authentication "
1272 x11_request_forwarding_with_spoofing(id, display, proto,
1274 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1275 /* XXX exit_on_forward_failure */
1278 if (cctx->want_agent_fwd && options.forward_agent) {
1279 debug("Requesting authentication agent forwarding.");
1280 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1284 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1285 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1287 debug3("%s: sending success reply", __func__);
1289 buffer_init(&reply);
1290 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1291 buffer_put_int(&reply, cctx->rid);
1292 buffer_put_int(&reply, c->self);
1296 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1297 buffer_free(&reply);
1299 if (cc->mux_pause <= 0)
1300 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1301 cc->mux_pause = 0; /* start processing messages again */
1302 c->open_confirm_ctx = NULL;
1303 buffer_free(&cctx->cmd);
1305 if (cctx->env != NULL) {
1306 for (i = 0; cctx->env[i] != NULL; i++)
1313 /* ** Multiplexing client support */
1315 /* Exit signal handler */
1317 control_client_sighandler(int signo)
1319 muxclient_terminate = signo;
1323 * Relay signal handler - used to pass some signals from mux client to
1327 control_client_sigrelay(int signo)
1329 int save_errno = errno;
1331 if (muxserver_pid > 1)
1332 kill(muxserver_pid, signo);
1338 mux_client_read(int fd, Buffer *b, u_int need)
1346 pfd.events = POLLIN;
1347 p = buffer_append_space(b, need);
1348 for (have = 0; have < need; ) {
1349 if (muxclient_terminate) {
1353 len = read(fd, p + have, need - have);
1356 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1360 (void)poll(&pfd, 1, -1);
1378 mux_client_write_packet(int fd, Buffer *m)
1387 pfd.events = POLLOUT;
1388 buffer_init(&queue);
1389 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1391 need = buffer_len(&queue);
1392 ptr = buffer_ptr(&queue);
1394 for (have = 0; have < need; ) {
1395 if (muxclient_terminate) {
1396 buffer_free(&queue);
1400 len = write(fd, ptr + have, need - have);
1403 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1407 (void)poll(&pfd, 1, -1);
1413 buffer_free(&queue);
1419 buffer_free(&queue);
1425 buffer_free(&queue);
1430 mux_client_read_packet(int fd, Buffer *m)
1437 buffer_init(&queue);
1438 if (mux_client_read(fd, &queue, 4) != 0) {
1439 if ((oerrno = errno) == EPIPE)
1440 debug3("%s: read header failed: %s", __func__,
1442 buffer_free(&queue);
1446 need = get_u32(buffer_ptr(&queue));
1447 if (mux_client_read(fd, &queue, need) != 0) {
1449 debug3("%s: read body failed: %s", __func__, strerror(errno));
1450 buffer_free(&queue);
1454 ptr = buffer_get_string_ptr(&queue, &have);
1455 buffer_append(m, ptr, have);
1456 buffer_free(&queue);
1461 mux_client_hello_exchange(int fd)
1467 buffer_put_int(&m, MUX_MSG_HELLO);
1468 buffer_put_int(&m, SSHMUX_VER);
1471 if (mux_client_write_packet(fd, &m) != 0)
1472 fatal("%s: write packet: %s", __func__, strerror(errno));
1476 /* Read their HELLO */
1477 if (mux_client_read_packet(fd, &m) != 0) {
1482 type = buffer_get_int(&m);
1483 if (type != MUX_MSG_HELLO)
1484 fatal("%s: expected HELLO (%u) received %u",
1485 __func__, MUX_MSG_HELLO, type);
1486 ver = buffer_get_int(&m);
1487 if (ver != SSHMUX_VER)
1488 fatal("Unsupported multiplexing protocol version %d "
1489 "(expected %d)", ver, SSHMUX_VER);
1490 debug2("%s: master version %u", __func__, ver);
1491 /* No extensions are presently defined */
1492 while (buffer_len(&m) > 0) {
1493 char *name = buffer_get_string(&m, NULL);
1494 char *value = buffer_get_string(&m, NULL);
1496 debug2("Unrecognised master extension \"%s\"", name);
1505 mux_client_request_alive(int fd)
1509 u_int pid, type, rid;
1511 debug3("%s: entering", __func__);
1514 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1515 buffer_put_int(&m, muxclient_request_id);
1517 if (mux_client_write_packet(fd, &m) != 0)
1518 fatal("%s: write packet: %s", __func__, strerror(errno));
1522 /* Read their reply */
1523 if (mux_client_read_packet(fd, &m) != 0) {
1528 type = buffer_get_int(&m);
1529 if (type != MUX_S_ALIVE) {
1530 e = buffer_get_string(&m, NULL);
1531 fatal("%s: master returned error: %s", __func__, e);
1534 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1535 fatal("%s: out of sequence reply: my id %u theirs %u",
1536 __func__, muxclient_request_id, rid);
1537 pid = buffer_get_int(&m);
1540 debug3("%s: done pid = %u", __func__, pid);
1542 muxclient_request_id++;
1548 mux_client_request_terminate(int fd)
1554 debug3("%s: entering", __func__);
1557 buffer_put_int(&m, MUX_C_TERMINATE);
1558 buffer_put_int(&m, muxclient_request_id);
1560 if (mux_client_write_packet(fd, &m) != 0)
1561 fatal("%s: write packet: %s", __func__, strerror(errno));
1565 /* Read their reply */
1566 if (mux_client_read_packet(fd, &m) != 0) {
1567 /* Remote end exited already */
1568 if (errno == EPIPE) {
1572 fatal("%s: read from master failed: %s",
1573 __func__, strerror(errno));
1576 type = buffer_get_int(&m);
1577 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1578 fatal("%s: out of sequence reply: my id %u theirs %u",
1579 __func__, muxclient_request_id, rid);
1583 case MUX_S_PERMISSION_DENIED:
1584 e = buffer_get_string(&m, NULL);
1585 fatal("Master refused termination request: %s", e);
1587 e = buffer_get_string(&m, NULL);
1588 fatal("%s: termination request failed: %s", __func__, e);
1590 fatal("%s: unexpected response from master 0x%08x",
1594 muxclient_request_id++;
1598 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1604 fwd_desc = format_forward(ftype, fwd);
1605 debug("Requesting %s %s",
1606 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1610 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1611 buffer_put_int(&m, muxclient_request_id);
1612 buffer_put_int(&m, ftype);
1613 buffer_put_cstring(&m,
1614 fwd->listen_host == NULL ? "" : fwd->listen_host);
1615 buffer_put_int(&m, fwd->listen_port);
1616 buffer_put_cstring(&m,
1617 fwd->connect_host == NULL ? "" : fwd->connect_host);
1618 buffer_put_int(&m, fwd->connect_port);
1620 if (mux_client_write_packet(fd, &m) != 0)
1621 fatal("%s: write packet: %s", __func__, strerror(errno));
1625 /* Read their reply */
1626 if (mux_client_read_packet(fd, &m) != 0) {
1631 type = buffer_get_int(&m);
1632 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1633 fatal("%s: out of sequence reply: my id %u theirs %u",
1634 __func__, muxclient_request_id, rid);
1638 case MUX_S_REMOTE_PORT:
1640 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1641 fwd->allocated_port = buffer_get_int(&m);
1642 logit("Allocated port %u for remote forward to %s:%d",
1643 fwd->allocated_port,
1644 fwd->connect_host ? fwd->connect_host : "",
1646 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1647 fprintf(stdout, "%u\n", fwd->allocated_port);
1649 case MUX_S_PERMISSION_DENIED:
1650 e = buffer_get_string(&m, NULL);
1652 error("Master refused forwarding request: %s", e);
1655 e = buffer_get_string(&m, NULL);
1657 error("%s: forwarding request failed: %s", __func__, e);
1660 fatal("%s: unexpected response from master 0x%08x",
1665 muxclient_request_id++;
1670 mux_client_forwards(int fd, int cancel_flag)
1674 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1675 cancel_flag ? "cancel" : "request",
1676 options.num_local_forwards, options.num_remote_forwards);
1678 /* XXX ExitOnForwardingFailure */
1679 for (i = 0; i < options.num_local_forwards; i++) {
1680 if (mux_client_forward(fd, cancel_flag,
1681 options.local_forwards[i].connect_port == 0 ?
1682 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1683 options.local_forwards + i) != 0)
1686 for (i = 0; i < options.num_remote_forwards; i++) {
1687 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1688 options.remote_forwards + i) != 0)
1695 mux_client_request_session(int fd)
1699 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1700 extern char **environ;
1701 int devnull, rawmode;
1703 debug3("%s: entering", __func__);
1705 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1706 error("%s: master alive request failed", __func__);
1710 signal(SIGPIPE, SIG_IGN);
1712 if (stdin_null_flag) {
1713 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1714 fatal("open(/dev/null): %s", strerror(errno));
1715 if (dup2(devnull, STDIN_FILENO) == -1)
1716 fatal("dup2: %s", strerror(errno));
1717 if (devnull > STDERR_FILENO)
1721 term = getenv("TERM");
1724 buffer_put_int(&m, MUX_C_NEW_SESSION);
1725 buffer_put_int(&m, muxclient_request_id);
1726 buffer_put_cstring(&m, ""); /* reserved */
1727 buffer_put_int(&m, tty_flag);
1728 buffer_put_int(&m, options.forward_x11);
1729 buffer_put_int(&m, options.forward_agent);
1730 buffer_put_int(&m, subsystem_flag);
1731 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1732 0xffffffff : (u_int)options.escape_char);
1733 buffer_put_cstring(&m, term == NULL ? "" : term);
1734 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1736 if (options.num_send_env > 0 && environ != NULL) {
1737 /* Pass environment */
1738 for (i = 0; environ[i] != NULL; i++) {
1739 if (env_permitted(environ[i])) {
1740 buffer_put_cstring(&m, environ[i]);
1745 if (mux_client_write_packet(fd, &m) != 0)
1746 fatal("%s: write packet: %s", __func__, strerror(errno));
1748 /* Send the stdio file descriptors */
1749 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1750 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1751 mm_send_fd(fd, STDERR_FILENO) == -1)
1752 fatal("%s: send fds failed", __func__);
1754 debug3("%s: session request sent", __func__);
1756 /* Read their reply */
1758 if (mux_client_read_packet(fd, &m) != 0) {
1759 error("%s: read from master failed: %s",
1760 __func__, strerror(errno));
1765 type = buffer_get_int(&m);
1766 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1767 fatal("%s: out of sequence reply: my id %u theirs %u",
1768 __func__, muxclient_request_id, rid);
1770 case MUX_S_SESSION_OPENED:
1771 sid = buffer_get_int(&m);
1772 debug("%s: master session id: %u", __func__, sid);
1774 case MUX_S_PERMISSION_DENIED:
1775 e = buffer_get_string(&m, NULL);
1777 error("Master refused session request: %s", e);
1780 e = buffer_get_string(&m, NULL);
1782 error("%s: session request failed: %s", __func__, e);
1786 error("%s: unexpected response from master 0x%08x",
1790 muxclient_request_id++;
1792 signal(SIGHUP, control_client_sighandler);
1793 signal(SIGINT, control_client_sighandler);
1794 signal(SIGTERM, control_client_sighandler);
1795 signal(SIGWINCH, control_client_sigrelay);
1799 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1802 * Stick around until the controlee closes the client_fd.
1803 * Before it does, it is expected to write an exit message.
1804 * This process must read the value and wait for the closure of
1805 * the client_fd; if this one closes early, the multiplex master will
1806 * terminate early too (possibly losing data).
1808 for (exitval = 255, exitval_seen = 0;;) {
1810 if (mux_client_read_packet(fd, &m) != 0)
1812 type = buffer_get_int(&m);
1814 case MUX_S_TTY_ALLOC_FAIL:
1815 if ((esid = buffer_get_int(&m)) != sid)
1816 fatal("%s: tty alloc fail on unknown session: "
1817 "my id %u theirs %u",
1818 __func__, sid, esid);
1819 leave_raw_mode(options.request_tty ==
1823 case MUX_S_EXIT_MESSAGE:
1824 if ((esid = buffer_get_int(&m)) != sid)
1825 fatal("%s: exit on unknown session: "
1826 "my id %u theirs %u",
1827 __func__, sid, esid);
1829 fatal("%s: exitval sent twice", __func__);
1830 exitval = buffer_get_int(&m);
1834 e = buffer_get_string(&m, NULL);
1835 fatal("%s: master returned error: %s", __func__, e);
1841 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1843 if (muxclient_terminate) {
1844 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1846 } else if (!exitval_seen) {
1847 debug2("Control master terminated unexpectedly");
1850 debug2("Received exit status from master %d", exitval);
1852 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1853 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1859 mux_client_request_stdio_fwd(int fd)
1863 u_int type, rid, sid;
1866 debug3("%s: entering", __func__);
1868 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1869 error("%s: master alive request failed", __func__);
1873 signal(SIGPIPE, SIG_IGN);
1875 if (stdin_null_flag) {
1876 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1877 fatal("open(/dev/null): %s", strerror(errno));
1878 if (dup2(devnull, STDIN_FILENO) == -1)
1879 fatal("dup2: %s", strerror(errno));
1880 if (devnull > STDERR_FILENO)
1885 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1886 buffer_put_int(&m, muxclient_request_id);
1887 buffer_put_cstring(&m, ""); /* reserved */
1888 buffer_put_cstring(&m, stdio_forward_host);
1889 buffer_put_int(&m, stdio_forward_port);
1891 if (mux_client_write_packet(fd, &m) != 0)
1892 fatal("%s: write packet: %s", __func__, strerror(errno));
1894 /* Send the stdio file descriptors */
1895 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1896 mm_send_fd(fd, STDOUT_FILENO) == -1)
1897 fatal("%s: send fds failed", __func__);
1899 debug3("%s: stdio forward request sent", __func__);
1901 /* Read their reply */
1904 if (mux_client_read_packet(fd, &m) != 0) {
1905 error("%s: read from master failed: %s",
1906 __func__, strerror(errno));
1911 type = buffer_get_int(&m);
1912 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1913 fatal("%s: out of sequence reply: my id %u theirs %u",
1914 __func__, muxclient_request_id, rid);
1916 case MUX_S_SESSION_OPENED:
1917 sid = buffer_get_int(&m);
1918 debug("%s: master session id: %u", __func__, sid);
1920 case MUX_S_PERMISSION_DENIED:
1921 e = buffer_get_string(&m, NULL);
1923 fatal("Master refused stdio forwarding request: %s", e);
1925 e = buffer_get_string(&m, NULL);
1927 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1930 error("%s: unexpected response from master 0x%08x",
1934 muxclient_request_id++;
1936 signal(SIGHUP, control_client_sighandler);
1937 signal(SIGINT, control_client_sighandler);
1938 signal(SIGTERM, control_client_sighandler);
1939 signal(SIGWINCH, control_client_sigrelay);
1942 * Stick around until the controlee closes the client_fd.
1945 if (mux_client_read_packet(fd, &m) != 0) {
1946 if (errno == EPIPE ||
1947 (errno == EINTR && muxclient_terminate != 0))
1949 fatal("%s: mux_client_read_packet: %s",
1950 __func__, strerror(errno));
1952 fatal("%s: master returned unexpected message %u", __func__, type);
1956 mux_client_request_stop_listening(int fd)
1962 debug3("%s: entering", __func__);
1965 buffer_put_int(&m, MUX_C_STOP_LISTENING);
1966 buffer_put_int(&m, muxclient_request_id);
1968 if (mux_client_write_packet(fd, &m) != 0)
1969 fatal("%s: write packet: %s", __func__, strerror(errno));
1973 /* Read their reply */
1974 if (mux_client_read_packet(fd, &m) != 0)
1975 fatal("%s: read from master failed: %s",
1976 __func__, strerror(errno));
1978 type = buffer_get_int(&m);
1979 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1980 fatal("%s: out of sequence reply: my id %u theirs %u",
1981 __func__, muxclient_request_id, rid);
1985 case MUX_S_PERMISSION_DENIED:
1986 e = buffer_get_string(&m, NULL);
1987 fatal("Master refused stop listening request: %s", e);
1989 e = buffer_get_string(&m, NULL);
1990 fatal("%s: stop listening request failed: %s", __func__, e);
1992 fatal("%s: unexpected response from master 0x%08x",
1996 muxclient_request_id++;
1999 /* Multiplex client main loop. */
2001 muxclient(const char *path)
2003 struct sockaddr_un addr;
2008 if (muxclient_command == 0) {
2009 if (stdio_forward_host != NULL)
2010 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2012 muxclient_command = SSHMUX_COMMAND_OPEN;
2015 switch (options.control_master) {
2016 case SSHCTL_MASTER_AUTO:
2017 case SSHCTL_MASTER_AUTO_ASK:
2018 debug("auto-mux: Trying existing master");
2020 case SSHCTL_MASTER_NO:
2026 memset(&addr, '\0', sizeof(addr));
2027 addr.sun_family = AF_UNIX;
2028 sun_len = offsetof(struct sockaddr_un, sun_path) +
2031 if (strlcpy(addr.sun_path, path,
2032 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2033 fatal("ControlPath too long");
2035 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2036 fatal("%s socket(): %s", __func__, strerror(errno));
2038 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2039 switch (muxclient_command) {
2040 case SSHMUX_COMMAND_OPEN:
2041 case SSHMUX_COMMAND_STDIO_FWD:
2044 fatal("Control socket connect(%.100s): %s", path,
2047 if (errno == ECONNREFUSED &&
2048 options.control_master != SSHCTL_MASTER_NO) {
2049 debug("Stale control socket %.100s, unlinking", path);
2051 } else if (errno == ENOENT) {
2052 debug("Control socket \"%.100s\" does not exist", path);
2054 error("Control socket connect(%.100s): %s", path,
2062 if (mux_client_hello_exchange(sock) != 0) {
2063 error("%s: master hello exchange failed", __func__);
2068 switch (muxclient_command) {
2069 case SSHMUX_COMMAND_ALIVE_CHECK:
2070 if ((pid = mux_client_request_alive(sock)) == 0)
2071 fatal("%s: master alive check failed", __func__);
2072 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2074 case SSHMUX_COMMAND_TERMINATE:
2075 mux_client_request_terminate(sock);
2076 fprintf(stderr, "Exit request sent.\r\n");
2078 case SSHMUX_COMMAND_FORWARD:
2079 if (mux_client_forwards(sock, 0) != 0)
2080 fatal("%s: master forward request failed", __func__);
2082 case SSHMUX_COMMAND_OPEN:
2083 if (mux_client_forwards(sock, 0) != 0) {
2084 error("%s: master forward request failed", __func__);
2087 mux_client_request_session(sock);
2089 case SSHMUX_COMMAND_STDIO_FWD:
2090 mux_client_request_stdio_fwd(sock);
2092 case SSHMUX_COMMAND_STOP:
2093 mux_client_request_stop_listening(sock);
2094 fprintf(stderr, "Stop listening request sent.\r\n");
2096 case SSHMUX_COMMAND_CANCEL_FWD:
2097 if (mux_client_forwards(sock, 1) != 0)
2098 error("%s: master cancel forward request failed",
2102 fatal("unrecognised muxclient_command %d", muxclient_command);