1 /* $OpenBSD: mux.c,v 1.14 2010/01/30 02:54:53 djm Exp $ */
3 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
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.
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.
18 /* ssh session multiplexing support */
22 * - Better signalling from master to slave, especially passing of
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
35 #include <sys/types.h>
36 #include <sys/param.h>
38 #include <sys/socket.h>
57 # ifdef HAVE_SYS_POLL_H
58 # include <sys/poll.h>
70 #include "openbsd-compat/sys-queue.h"
74 #include "pathnames.h"
81 #include "monitor_fdpass.h"
85 #include "clientloop.h"
89 extern int force_tty_flag;
90 extern Options options;
91 extern int stdin_null_flag;
93 extern int subsystem_flag;
94 extern Buffer command;
95 extern volatile sig_atomic_t quit_pending;
96 extern char *stdio_forward_host;
97 extern int stdio_forward_port;
99 /* Context for session open confirmation callback */
100 struct mux_session_confirm_ctx {
104 u_int want_agent_fwd;
111 /* fd to control socket */
112 int muxserver_sock = -1;
114 /* client request id */
115 u_int muxclient_request_id = 0;
117 /* Multiplexing control command */
118 u_int muxclient_command = 0;
120 /* Set when signalled. */
121 static volatile sig_atomic_t muxclient_terminate = 0;
123 /* PID of multiplex server */
124 static u_int muxserver_pid = 0;
126 static Channel *mux_listener_channel = NULL;
128 struct mux_master_state {
132 /* mux protocol messages */
133 #define MUX_MSG_HELLO 0x00000001
134 #define MUX_C_NEW_SESSION 0x10000002
135 #define MUX_C_ALIVE_CHECK 0x10000004
136 #define MUX_C_TERMINATE 0x10000005
137 #define MUX_C_OPEN_FWD 0x10000006
138 #define MUX_C_CLOSE_FWD 0x10000007
139 #define MUX_C_NEW_STDIO_FWD 0x10000008
140 #define MUX_S_OK 0x80000001
141 #define MUX_S_PERMISSION_DENIED 0x80000002
142 #define MUX_S_FAILURE 0x80000003
143 #define MUX_S_EXIT_MESSAGE 0x80000004
144 #define MUX_S_ALIVE 0x80000005
145 #define MUX_S_SESSION_OPENED 0x80000006
147 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
148 #define MUX_FWD_LOCAL 1
149 #define MUX_FWD_REMOTE 2
150 #define MUX_FWD_DYNAMIC 3
152 static void mux_session_confirm(int, void *);
154 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
155 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
156 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
157 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
158 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
159 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
160 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
162 static const struct {
164 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
165 } mux_master_handlers[] = {
166 { MUX_MSG_HELLO, process_mux_master_hello },
167 { MUX_C_NEW_SESSION, process_mux_new_session },
168 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
169 { MUX_C_TERMINATE, process_mux_terminate },
170 { MUX_C_OPEN_FWD, process_mux_open_fwd },
171 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
172 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
176 /* Cleanup callback fired on closure of mux slave _session_ channel */
179 mux_master_session_cleanup_cb(int cid, void *unused)
181 Channel *cc, *c = channel_by_id(cid);
183 debug3("%s: entering for channel %d", __func__, cid);
185 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
186 if (c->ctl_chan != -1) {
187 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
188 fatal("%s: channel %d missing control channel %d",
189 __func__, c->self, c->ctl_chan);
192 chan_rcvd_oclose(cc);
194 channel_cancel_cleanup(c->self);
197 /* Cleanup callback fired on closure of mux slave _control_ channel */
200 mux_master_control_cleanup_cb(int cid, void *unused)
202 Channel *sc, *c = channel_by_id(cid);
204 debug3("%s: entering for channel %d", __func__, cid);
206 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
207 if (c->remote_id != -1) {
208 if ((sc = channel_by_id(c->remote_id)) == NULL)
209 debug2("%s: channel %d n session channel %d",
210 __func__, c->self, c->remote_id);
213 if (sc->type != SSH_CHANNEL_OPEN) {
214 debug2("%s: channel %d: not open", __func__, sc->self);
217 if (sc->istate == CHAN_INPUT_OPEN)
218 chan_read_failed(sc);
219 if (sc->ostate == CHAN_OUTPUT_OPEN)
220 chan_write_failed(sc);
223 channel_cancel_cleanup(c->self);
226 /* Check mux client environment variables before passing them to mux master. */
228 env_permitted(char *env)
231 char name[1024], *cp;
233 if ((cp = strchr(env, '=')) == NULL || cp == env)
235 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
236 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
237 error("env_permitted: name '%.100s...' too long", env);
241 for (i = 0; i < options.num_send_env; i++)
242 if (match_pattern(name, options.send_env[i]))
248 /* Mux master protocol message handlers */
251 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
254 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
257 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
258 if (state->hello_rcvd) {
259 error("%s: HELLO received twice", __func__);
262 if (buffer_get_int_ret(&ver, m) != 0) {
264 error("%s: malformed message", __func__);
267 if (ver != SSHMUX_VER) {
268 error("Unsupported multiplexing protocol version %d "
269 "(expected %d)", ver, SSHMUX_VER);
272 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
274 /* No extensions are presently defined */
275 while (buffer_len(m) > 0) {
276 char *name = buffer_get_string_ret(m, NULL);
277 char *value = buffer_get_string_ret(m, NULL);
279 if (name == NULL || value == NULL) {
284 debug2("Unrecognised slave extension \"%s\"", name);
288 state->hello_rcvd = 1;
293 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
296 struct mux_session_confirm_ctx *cctx;
297 char *reserved, *cmd, *cp;
298 u_int i, j, len, env_len, escape_char, window, packetmax;
301 /* Reply for SSHMUX_COMMAND_OPEN */
302 cctx = xcalloc(1, sizeof(*cctx));
304 cmd = reserved = NULL;
305 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
306 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
307 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
308 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
309 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
310 buffer_get_int_ret(&escape_char, m) != 0 ||
311 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
312 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
316 if (reserved != NULL)
318 if (cctx->term != NULL)
320 error("%s: malformed message", __func__);
328 while (buffer_len(m) > 0) {
329 #define MUX_MAX_ENV_VARS 4096
330 if ((cp = buffer_get_string_ret(m, &len)) == NULL) {
334 if (!env_permitted(cp)) {
338 cctx->env = xrealloc(cctx->env, env_len + 2,
340 cctx->env[env_len++] = cp;
341 cctx->env[env_len] = NULL;
342 if (env_len > MUX_MAX_ENV_VARS) {
343 error(">%d environment variables received, ignoring "
344 "additional", MUX_MAX_ENV_VARS);
349 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
350 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
351 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
352 cctx->want_subsys, cctx->term, cmd, env_len);
354 buffer_init(&cctx->cmd);
355 buffer_append(&cctx->cmd, cmd, strlen(cmd));
359 /* Gather fds from client */
360 for(i = 0; i < 3; i++) {
361 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
362 error("%s: failed to receive fd %d from slave",
364 for (j = 0; j < i; j++)
366 for (j = 0; j < env_len; j++)
371 buffer_free(&cctx->cmd);
375 buffer_put_int(r, MUX_S_FAILURE);
376 buffer_put_int(r, rid);
377 buffer_put_cstring(r,
378 "did not receive file descriptors");
383 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
384 new_fd[0], new_fd[1], new_fd[2]);
386 /* XXX support multiple child sessions in future */
387 if (c->remote_id != -1) {
388 debug2("%s: session already open", __func__);
390 buffer_put_int(r, MUX_S_FAILURE);
391 buffer_put_int(r, rid);
392 buffer_put_cstring(r, "Multiple sessions not supported");
399 for (i = 0; i < env_len; i++)
403 buffer_free(&cctx->cmd);
407 if (options.control_master == SSHCTL_MASTER_ASK ||
408 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
409 if (!ask_permission("Allow shared connection to %s? ", host)) {
410 debug2("%s: session refused by user", __func__);
412 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
413 buffer_put_int(r, rid);
414 buffer_put_cstring(r, "Permission denied");
419 /* Try to pick up ttymodes from client before it goes raw */
420 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
421 error("%s: tcgetattr: %s", __func__, strerror(errno));
423 /* enable nonblocking unless tty */
424 if (!isatty(new_fd[0]))
425 set_nonblock(new_fd[0]);
426 if (!isatty(new_fd[1]))
427 set_nonblock(new_fd[1]);
428 if (!isatty(new_fd[2]))
429 set_nonblock(new_fd[2]);
431 window = CHAN_SES_WINDOW_DEFAULT;
432 packetmax = CHAN_SES_PACKET_DEFAULT;
433 if (cctx->want_tty) {
438 nc = channel_new("session", SSH_CHANNEL_OPENING,
439 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
440 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
442 nc->ctl_chan = c->self; /* link session -> control channel */
443 c->remote_id = nc->self; /* link control -> session channel */
445 if (cctx->want_tty && escape_char != 0xffffffff) {
446 channel_register_filter(nc->self,
447 client_simple_escape_filter, NULL,
448 client_filter_cleanup,
449 client_new_escape_filter_ctx((int)escape_char));
452 debug2("%s: channel_new: %d linked to control channel %d",
453 __func__, nc->self, nc->ctl_chan);
455 channel_send_open(nc->self);
456 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
457 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
460 /* XXX defer until mux_session_confirm() fires */
461 buffer_put_int(r, MUX_S_SESSION_OPENED);
462 buffer_put_int(r, rid);
463 buffer_put_int(r, nc->self);
469 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
471 debug2("%s: channel %d: alive check", __func__, c->self);
474 buffer_put_int(r, MUX_S_ALIVE);
475 buffer_put_int(r, rid);
476 buffer_put_int(r, (u_int)getpid());
482 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
484 debug2("%s: channel %d: terminate request", __func__, c->self);
486 if (options.control_master == SSHCTL_MASTER_ASK ||
487 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
488 if (!ask_permission("Terminate shared connection to %s? ",
490 debug2("%s: termination refused by user", __func__);
491 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
492 buffer_put_int(r, rid);
493 buffer_put_cstring(r, "Permission denied");
499 buffer_put_int(r, MUX_S_OK);
500 buffer_put_int(r, rid);
501 /* XXX exit happens too soon - message never makes it to client */
506 format_forward(u_int ftype, Forward *fwd)
512 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
513 (fwd->listen_host == NULL) ?
514 (options.gateway_ports ? "*" : "LOCALHOST") :
515 fwd->listen_host, fwd->listen_port,
516 fwd->connect_host, fwd->connect_port);
518 case MUX_FWD_DYNAMIC:
519 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
520 (fwd->listen_host == NULL) ?
521 (options.gateway_ports ? "*" : "LOCALHOST") :
522 fwd->listen_host, fwd->listen_port);
525 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
526 (fwd->listen_host == NULL) ?
527 "LOCALHOST" : fwd->listen_host,
529 fwd->connect_host, fwd->connect_port);
532 fatal("%s: unknown forward type %u", __func__, ftype);
538 compare_host(const char *a, const char *b)
540 if (a == NULL && b == NULL)
542 if (a == NULL || b == NULL)
544 return strcmp(a, b) == 0;
548 compare_forward(Forward *a, Forward *b)
550 if (!compare_host(a->listen_host, b->listen_host))
552 if (a->listen_port != b->listen_port)
554 if (!compare_host(a->connect_host, b->connect_host))
556 if (a->connect_port != b->connect_port)
563 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
566 char *fwd_desc = NULL;
568 int i, ret = 0, freefwd = 1;
570 fwd.listen_host = fwd.connect_host = NULL;
571 if (buffer_get_int_ret(&ftype, m) != 0 ||
572 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
573 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
574 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
575 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
576 error("%s: malformed message", __func__);
581 if (*fwd.listen_host == '\0') {
582 xfree(fwd.listen_host);
583 fwd.listen_host = NULL;
585 if (*fwd.connect_host == '\0') {
586 xfree(fwd.connect_host);
587 fwd.connect_host = NULL;
590 debug2("%s: channel %d: request %s", __func__, c->self,
591 (fwd_desc = format_forward(ftype, &fwd)));
593 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
594 ftype != MUX_FWD_DYNAMIC) {
595 logit("%s: invalid forwarding type %u", __func__, ftype);
597 xfree(fwd.listen_host);
598 xfree(fwd.connect_host);
599 buffer_put_int(r, MUX_S_FAILURE);
600 buffer_put_int(r, rid);
601 buffer_put_cstring(r, "Invalid forwarding request");
604 /* XXX support rport0 forwarding with reply of port assigned */
605 if (fwd.listen_port == 0 || fwd.listen_port >= 65536) {
606 logit("%s: invalid listen port %u", __func__,
610 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
611 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
612 logit("%s: invalid connect port %u", __func__,
616 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
617 logit("%s: missing connect host", __func__);
621 /* Skip forwards that have already been requested */
624 case MUX_FWD_DYNAMIC:
625 for (i = 0; i < options.num_local_forwards; i++) {
626 if (compare_forward(&fwd,
627 options.local_forwards + i)) {
629 debug2("%s: found existing forwarding",
631 buffer_put_int(r, MUX_S_OK);
632 buffer_put_int(r, rid);
638 for (i = 0; i < options.num_remote_forwards; i++) {
639 if (compare_forward(&fwd,
640 options.remote_forwards + i))
646 if (options.control_master == SSHCTL_MASTER_ASK ||
647 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
648 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
649 debug2("%s: forwarding refused by user", __func__);
650 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
651 buffer_put_int(r, rid);
652 buffer_put_cstring(r, "Permission denied");
657 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
658 if (options.num_local_forwards + 1 >=
659 SSH_MAX_FORWARDS_PER_DIRECTION ||
660 channel_setup_local_fwd_listener(fwd.listen_host,
661 fwd.listen_port, fwd.connect_host, fwd.connect_port,
662 options.gateway_ports) < 0) {
664 logit("slave-requested %s failed", fwd_desc);
665 buffer_put_int(r, MUX_S_FAILURE);
666 buffer_put_int(r, rid);
667 buffer_put_cstring(r, "Port forwarding failed");
670 add_local_forward(&options, &fwd);
673 /* XXX wait for remote to confirm */
674 if (options.num_remote_forwards + 1 >=
675 SSH_MAX_FORWARDS_PER_DIRECTION ||
676 channel_request_remote_forwarding(fwd.listen_host,
677 fwd.listen_port, fwd.connect_host, fwd.connect_port) < 0)
679 add_remote_forward(&options, &fwd);
682 buffer_put_int(r, MUX_S_OK);
683 buffer_put_int(r, rid);
685 if (fwd_desc != NULL)
688 if (fwd.listen_host != NULL)
689 xfree(fwd.listen_host);
690 if (fwd.connect_host != NULL)
691 xfree(fwd.connect_host);
697 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
700 char *fwd_desc = NULL;
704 fwd.listen_host = fwd.connect_host = NULL;
705 if (buffer_get_int_ret(&ftype, m) != 0 ||
706 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
707 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
708 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
709 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
710 error("%s: malformed message", __func__);
715 if (*fwd.listen_host == '\0') {
716 xfree(fwd.listen_host);
717 fwd.listen_host = NULL;
719 if (*fwd.connect_host == '\0') {
720 xfree(fwd.connect_host);
721 fwd.connect_host = NULL;
724 debug2("%s: channel %d: request %s", __func__, c->self,
725 (fwd_desc = format_forward(ftype, &fwd)));
727 /* XXX implement this */
728 buffer_put_int(r, MUX_S_FAILURE);
729 buffer_put_int(r, rid);
730 buffer_put_cstring(r, "unimplemented");
733 if (fwd_desc != NULL)
735 if (fwd.listen_host != NULL)
736 xfree(fwd.listen_host);
737 if (fwd.connect_host != NULL)
738 xfree(fwd.connect_host);
744 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
747 char *reserved, *chost;
751 chost = reserved = NULL;
752 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
753 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
754 buffer_get_int_ret(&cport, m) != 0) {
755 if (reserved != NULL)
759 error("%s: malformed message", __func__);
764 debug2("%s: channel %d: request stdio fwd to %s:%u",
765 __func__, c->self, chost, cport);
767 /* Gather fds from client */
768 for(i = 0; i < 2; i++) {
769 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
770 error("%s: failed to receive fd %d from slave",
772 for (j = 0; j < i; j++)
777 buffer_put_int(r, MUX_S_FAILURE);
778 buffer_put_int(r, rid);
779 buffer_put_cstring(r,
780 "did not receive file descriptors");
785 debug3("%s: got fds stdin %d, stdout %d", __func__,
786 new_fd[0], new_fd[1]);
788 /* XXX support multiple child sessions in future */
789 if (c->remote_id != -1) {
790 debug2("%s: session already open", __func__);
792 buffer_put_int(r, MUX_S_FAILURE);
793 buffer_put_int(r, rid);
794 buffer_put_cstring(r, "Multiple sessions not supported");
802 if (options.control_master == SSHCTL_MASTER_ASK ||
803 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
804 if (!ask_permission("Allow forward to to %s:%u? ",
806 debug2("%s: stdio fwd refused by user", __func__);
808 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
809 buffer_put_int(r, rid);
810 buffer_put_cstring(r, "Permission denied");
815 /* enable nonblocking unless tty */
816 if (!isatty(new_fd[0]))
817 set_nonblock(new_fd[0]);
818 if (!isatty(new_fd[1]))
819 set_nonblock(new_fd[1]);
821 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
823 nc->ctl_chan = c->self; /* link session -> control channel */
824 c->remote_id = nc->self; /* link control -> session channel */
826 debug2("%s: channel_new: %d linked to control channel %d",
827 __func__, nc->self, nc->ctl_chan);
829 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
832 /* XXX defer until channel confirmed */
833 buffer_put_int(r, MUX_S_SESSION_OPENED);
834 buffer_put_int(r, rid);
835 buffer_put_int(r, nc->self);
840 /* Channel callbacks fired on read/write from mux slave fd */
842 mux_master_read_cb(Channel *c)
844 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
847 u_int type, rid, have, i;
851 if (c->mux_ctx == NULL) {
852 state = xcalloc(1, sizeof(state));
854 channel_register_cleanup(c->self,
855 mux_master_control_cleanup_cb, 0);
859 buffer_put_int(&out, MUX_MSG_HELLO);
860 buffer_put_int(&out, SSHMUX_VER);
862 buffer_put_string(&c->output, buffer_ptr(&out),
865 debug3("%s: channel %d: hello sent", __func__, c->self);
872 /* Channel code ensures that we receive whole packets */
873 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
875 error("%s: malformed message", __func__);
878 buffer_append(&in, ptr, have);
880 if (buffer_get_int_ret(&type, &in) != 0)
882 debug3("%s: channel %d packet type 0x%08x len %u",
883 __func__, c->self, type, buffer_len(&in));
885 if (type == MUX_MSG_HELLO)
888 if (!state->hello_rcvd) {
889 error("%s: expected MUX_MSG_HELLO(0x%08x), "
890 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
893 if (buffer_get_int_ret(&rid, &in) != 0)
897 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
898 if (type == mux_master_handlers[i].type) {
899 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
903 if (mux_master_handlers[i].handler == NULL) {
904 error("%s: unsupported mux message 0x%08x", __func__, type);
905 buffer_put_int(&out, MUX_S_FAILURE);
906 buffer_put_int(&out, rid);
907 buffer_put_cstring(&out, "unsupported request");
910 /* Enqueue reply packet */
911 if (buffer_len(&out) != 0) {
912 buffer_put_string(&c->output, buffer_ptr(&out),
922 mux_exit_message(Channel *c, int exitval)
927 debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
930 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
931 fatal("%s: channel %d missing mux channel %d",
932 __func__, c->self, c->ctl_chan);
934 /* Append exit message packet to control socket output queue */
936 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
937 buffer_put_int(&m, c->self);
938 buffer_put_int(&m, exitval);
940 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
944 /* Prepare a mux master to listen on a Unix domain socket. */
946 muxserver_listen(void)
948 struct sockaddr_un addr;
952 if (options.control_path == NULL ||
953 options.control_master == SSHCTL_MASTER_NO)
956 debug("setting up multiplex master socket");
958 memset(&addr, '\0', sizeof(addr));
959 addr.sun_family = AF_UNIX;
960 sun_len = offsetof(struct sockaddr_un, sun_path) +
961 strlen(options.control_path) + 1;
963 if (strlcpy(addr.sun_path, options.control_path,
964 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
965 fatal("ControlPath too long");
967 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
968 fatal("%s socket(): %s", __func__, strerror(errno));
970 old_umask = umask(0177);
971 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
973 if (errno == EINVAL || errno == EADDRINUSE) {
974 error("ControlSocket %s already exists, "
975 "disabling multiplexing", options.control_path);
976 close(muxserver_sock);
978 xfree(options.control_path);
979 options.control_path = NULL;
980 options.control_master = SSHCTL_MASTER_NO;
983 fatal("%s bind(): %s", __func__, strerror(errno));
987 if (listen(muxserver_sock, 64) == -1)
988 fatal("%s listen(): %s", __func__, strerror(errno));
990 set_nonblock(muxserver_sock);
992 mux_listener_channel = channel_new("mux listener",
993 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
994 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
995 0, addr.sun_path, 1);
996 mux_listener_channel->mux_rcb = mux_master_read_cb;
997 debug3("%s: mux listener channel %d fd %d", __func__,
998 mux_listener_channel->self, mux_listener_channel->sock);
1001 /* Callback on open confirmation in mux master for a mux client session. */
1003 mux_session_confirm(int id, void *arg)
1005 struct mux_session_confirm_ctx *cctx = arg;
1006 const char *display;
1011 fatal("%s: cctx == NULL", __func__);
1012 if ((c = channel_by_id(id)) == NULL)
1013 fatal("%s: no channel for id %d", __func__, id);
1015 display = getenv("DISPLAY");
1016 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1018 /* Get reasonable local authentication information. */
1019 client_x11_get_proto(display, options.xauth_location,
1020 options.forward_x11_trusted, &proto, &data);
1021 /* Request forwarding with authentication spoofing. */
1022 debug("Requesting X11 forwarding with authentication spoofing.");
1023 x11_request_forwarding_with_spoofing(id, display, proto, data);
1024 /* XXX wait for reply */
1027 if (cctx->want_agent_fwd && options.forward_agent) {
1028 debug("Requesting authentication agent forwarding.");
1029 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1033 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1034 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1036 c->open_confirm_ctx = NULL;
1037 buffer_free(&cctx->cmd);
1039 if (cctx->env != NULL) {
1040 for (i = 0; cctx->env[i] != NULL; i++)
1041 xfree(cctx->env[i]);
1047 /* ** Multiplexing client support */
1049 /* Exit signal handler */
1051 control_client_sighandler(int signo)
1053 muxclient_terminate = signo;
1057 * Relay signal handler - used to pass some signals from mux client to
1061 control_client_sigrelay(int signo)
1063 int save_errno = errno;
1065 if (muxserver_pid > 1)
1066 kill(muxserver_pid, signo);
1072 mux_client_read(int fd, Buffer *b, u_int need)
1080 pfd.events = POLLIN;
1081 p = buffer_append_space(b, need);
1082 for (have = 0; have < need; ) {
1083 if (muxclient_terminate) {
1087 len = read(fd, p + have, need - have);
1090 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1094 (void)poll(&pfd, 1, -1);
1112 mux_client_write_packet(int fd, Buffer *m)
1121 pfd.events = POLLOUT;
1122 buffer_init(&queue);
1123 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1125 need = buffer_len(&queue);
1126 ptr = buffer_ptr(&queue);
1128 for (have = 0; have < need; ) {
1129 if (muxclient_terminate) {
1130 buffer_free(&queue);
1134 len = write(fd, ptr + have, need - have);
1137 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1141 (void)poll(&pfd, 1, -1);
1147 buffer_free(&queue);
1153 buffer_free(&queue);
1159 buffer_free(&queue);
1164 mux_client_read_packet(int fd, Buffer *m)
1171 buffer_init(&queue);
1172 if (mux_client_read(fd, &queue, 4) != 0) {
1173 if ((oerrno = errno) == EPIPE)
1174 debug3("%s: read header failed: %s", __func__, strerror(errno));
1178 need = get_u32(buffer_ptr(&queue));
1179 if (mux_client_read(fd, &queue, need) != 0) {
1181 debug3("%s: read body failed: %s", __func__, strerror(errno));
1185 ptr = buffer_get_string_ptr(&queue, &have);
1186 buffer_append(m, ptr, have);
1187 buffer_free(&queue);
1192 mux_client_hello_exchange(int fd)
1198 buffer_put_int(&m, MUX_MSG_HELLO);
1199 buffer_put_int(&m, SSHMUX_VER);
1202 if (mux_client_write_packet(fd, &m) != 0)
1203 fatal("%s: write packet: %s", __func__, strerror(errno));
1207 /* Read their HELLO */
1208 if (mux_client_read_packet(fd, &m) != 0) {
1213 type = buffer_get_int(&m);
1214 if (type != MUX_MSG_HELLO)
1215 fatal("%s: expected HELLO (%u) received %u",
1216 __func__, MUX_MSG_HELLO, type);
1217 ver = buffer_get_int(&m);
1218 if (ver != SSHMUX_VER)
1219 fatal("Unsupported multiplexing protocol version %d "
1220 "(expected %d)", ver, SSHMUX_VER);
1221 debug2("%s: master version %u", __func__, ver);
1222 /* No extensions are presently defined */
1223 while (buffer_len(&m) > 0) {
1224 char *name = buffer_get_string(&m, NULL);
1225 char *value = buffer_get_string(&m, NULL);
1227 debug2("Unrecognised master extension \"%s\"", name);
1236 mux_client_request_alive(int fd)
1240 u_int pid, type, rid;
1242 debug3("%s: entering", __func__);
1245 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1246 buffer_put_int(&m, muxclient_request_id);
1248 if (mux_client_write_packet(fd, &m) != 0)
1249 fatal("%s: write packet: %s", __func__, strerror(errno));
1253 /* Read their reply */
1254 if (mux_client_read_packet(fd, &m) != 0) {
1259 type = buffer_get_int(&m);
1260 if (type != MUX_S_ALIVE) {
1261 e = buffer_get_string(&m, NULL);
1262 fatal("%s: master returned error: %s", __func__, e);
1265 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1266 fatal("%s: out of sequence reply: my id %u theirs %u",
1267 __func__, muxclient_request_id, rid);
1268 pid = buffer_get_int(&m);
1271 debug3("%s: done pid = %u", __func__, pid);
1273 muxclient_request_id++;
1279 mux_client_request_terminate(int fd)
1285 debug3("%s: entering", __func__);
1288 buffer_put_int(&m, MUX_C_TERMINATE);
1289 buffer_put_int(&m, muxclient_request_id);
1291 if (mux_client_write_packet(fd, &m) != 0)
1292 fatal("%s: write packet: %s", __func__, strerror(errno));
1296 /* Read their reply */
1297 if (mux_client_read_packet(fd, &m) != 0) {
1298 /* Remote end exited already */
1299 if (errno == EPIPE) {
1303 fatal("%s: read from master failed: %s",
1304 __func__, strerror(errno));
1307 type = buffer_get_int(&m);
1308 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1309 fatal("%s: out of sequence reply: my id %u theirs %u",
1310 __func__, muxclient_request_id, rid);
1314 case MUX_S_PERMISSION_DENIED:
1315 e = buffer_get_string(&m, NULL);
1316 fatal("Master refused termination request: %s", e);
1318 e = buffer_get_string(&m, NULL);
1319 fatal("%s: termination request failed: %s", __func__, e);
1321 fatal("%s: unexpected response from master 0x%08x",
1325 muxclient_request_id++;
1329 mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
1335 fwd_desc = format_forward(ftype, fwd);
1336 debug("Requesting %s", fwd_desc);
1340 buffer_put_int(&m, MUX_C_OPEN_FWD);
1341 buffer_put_int(&m, muxclient_request_id);
1342 buffer_put_int(&m, ftype);
1343 buffer_put_cstring(&m,
1344 fwd->listen_host == NULL ? "" : fwd->listen_host);
1345 buffer_put_int(&m, fwd->listen_port);
1346 buffer_put_cstring(&m,
1347 fwd->connect_host == NULL ? "" : fwd->connect_host);
1348 buffer_put_int(&m, fwd->connect_port);
1350 if (mux_client_write_packet(fd, &m) != 0)
1351 fatal("%s: write packet: %s", __func__, strerror(errno));
1355 /* Read their reply */
1356 if (mux_client_read_packet(fd, &m) != 0) {
1361 type = buffer_get_int(&m);
1362 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1363 fatal("%s: out of sequence reply: my id %u theirs %u",
1364 __func__, muxclient_request_id, rid);
1368 case MUX_S_PERMISSION_DENIED:
1369 e = buffer_get_string(&m, NULL);
1371 error("Master refused forwarding request: %s", e);
1374 e = buffer_get_string(&m, NULL);
1376 error("%s: session request failed: %s", __func__, e);
1379 fatal("%s: unexpected response from master 0x%08x",
1384 muxclient_request_id++;
1389 mux_client_request_forwards(int fd)
1393 debug3("%s: requesting forwardings: %d local, %d remote", __func__,
1394 options.num_local_forwards, options.num_remote_forwards);
1396 /* XXX ExitOnForwardingFailure */
1397 for (i = 0; i < options.num_local_forwards; i++) {
1398 if (mux_client_request_forward(fd,
1399 options.local_forwards[i].connect_port == 0 ?
1400 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1401 options.local_forwards + i) != 0)
1404 for (i = 0; i < options.num_remote_forwards; i++) {
1405 if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
1406 options.remote_forwards + i) != 0)
1413 mux_client_request_session(int fd)
1417 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1418 extern char **environ;
1421 debug3("%s: entering", __func__);
1423 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1424 error("%s: master alive request failed", __func__);
1428 signal(SIGPIPE, SIG_IGN);
1430 if (stdin_null_flag) {
1431 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1432 fatal("open(/dev/null): %s", strerror(errno));
1433 if (dup2(devnull, STDIN_FILENO) == -1)
1434 fatal("dup2: %s", strerror(errno));
1435 if (devnull > STDERR_FILENO)
1439 term = getenv("TERM");
1442 buffer_put_int(&m, MUX_C_NEW_SESSION);
1443 buffer_put_int(&m, muxclient_request_id);
1444 buffer_put_cstring(&m, ""); /* reserved */
1445 buffer_put_int(&m, tty_flag);
1446 buffer_put_int(&m, options.forward_x11);
1447 buffer_put_int(&m, options.forward_agent);
1448 buffer_put_int(&m, subsystem_flag);
1449 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1450 0xffffffff : (u_int)options.escape_char);
1451 buffer_put_cstring(&m, term == NULL ? "" : term);
1452 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1454 if (options.num_send_env > 0 && environ != NULL) {
1455 /* Pass environment */
1456 for (i = 0; environ[i] != NULL; i++) {
1457 if (env_permitted(environ[i])) {
1458 buffer_put_cstring(&m, environ[i]);
1463 if (mux_client_write_packet(fd, &m) != 0)
1464 fatal("%s: write packet: %s", __func__, strerror(errno));
1466 /* Send the stdio file descriptors */
1467 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1468 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1469 mm_send_fd(fd, STDERR_FILENO) == -1)
1470 fatal("%s: send fds failed", __func__);
1472 debug3("%s: session request sent", __func__);
1474 /* Read their reply */
1476 if (mux_client_read_packet(fd, &m) != 0) {
1477 error("%s: read from master failed: %s",
1478 __func__, strerror(errno));
1483 type = buffer_get_int(&m);
1484 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1485 fatal("%s: out of sequence reply: my id %u theirs %u",
1486 __func__, muxclient_request_id, rid);
1488 case MUX_S_SESSION_OPENED:
1489 sid = buffer_get_int(&m);
1490 debug("%s: master session id: %u", __func__, sid);
1492 case MUX_S_PERMISSION_DENIED:
1493 e = buffer_get_string(&m, NULL);
1495 error("Master refused forwarding request: %s", e);
1498 e = buffer_get_string(&m, NULL);
1500 error("%s: forwarding request failed: %s", __func__, e);
1504 error("%s: unexpected response from master 0x%08x",
1508 muxclient_request_id++;
1510 signal(SIGHUP, control_client_sighandler);
1511 signal(SIGINT, control_client_sighandler);
1512 signal(SIGTERM, control_client_sighandler);
1513 signal(SIGWINCH, control_client_sigrelay);
1516 enter_raw_mode(force_tty_flag);
1519 * Stick around until the controlee closes the client_fd.
1520 * Before it does, it is expected to write an exit message.
1521 * This process must read the value and wait for the closure of
1522 * the client_fd; if this one closes early, the multiplex master will
1523 * terminate early too (possibly losing data).
1525 for (exitval = 255, exitval_seen = 0;;) {
1527 if (mux_client_read_packet(fd, &m) != 0)
1529 type = buffer_get_int(&m);
1530 if (type != MUX_S_EXIT_MESSAGE) {
1531 e = buffer_get_string(&m, NULL);
1532 fatal("%s: master returned error: %s", __func__, e);
1534 if ((esid = buffer_get_int(&m)) != sid)
1535 fatal("%s: exit on unknown session: my id %u theirs %u",
1536 __func__, sid, esid);
1537 debug("%s: master session id: %u", __func__, sid);
1539 fatal("%s: exitval sent twice", __func__);
1540 exitval = buffer_get_int(&m);
1545 leave_raw_mode(force_tty_flag);
1547 if (muxclient_terminate) {
1548 debug2("Exiting on signal %d", muxclient_terminate);
1550 } else if (!exitval_seen) {
1551 debug2("Control master terminated unexpectedly");
1554 debug2("Received exit status from master %d", exitval);
1556 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1557 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1563 mux_client_request_stdio_fwd(int fd)
1567 u_int type, rid, sid;
1570 debug3("%s: entering", __func__);
1572 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1573 error("%s: master alive request failed", __func__);
1577 signal(SIGPIPE, SIG_IGN);
1579 if (stdin_null_flag) {
1580 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1581 fatal("open(/dev/null): %s", strerror(errno));
1582 if (dup2(devnull, STDIN_FILENO) == -1)
1583 fatal("dup2: %s", strerror(errno));
1584 if (devnull > STDERR_FILENO)
1589 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1590 buffer_put_int(&m, muxclient_request_id);
1591 buffer_put_cstring(&m, ""); /* reserved */
1592 buffer_put_cstring(&m, stdio_forward_host);
1593 buffer_put_int(&m, stdio_forward_port);
1595 if (mux_client_write_packet(fd, &m) != 0)
1596 fatal("%s: write packet: %s", __func__, strerror(errno));
1598 /* Send the stdio file descriptors */
1599 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1600 mm_send_fd(fd, STDOUT_FILENO) == -1)
1601 fatal("%s: send fds failed", __func__);
1603 debug3("%s: stdio forward request sent", __func__);
1605 /* Read their reply */
1608 if (mux_client_read_packet(fd, &m) != 0) {
1609 error("%s: read from master failed: %s",
1610 __func__, strerror(errno));
1615 type = buffer_get_int(&m);
1616 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1617 fatal("%s: out of sequence reply: my id %u theirs %u",
1618 __func__, muxclient_request_id, rid);
1620 case MUX_S_SESSION_OPENED:
1621 sid = buffer_get_int(&m);
1622 debug("%s: master session id: %u", __func__, sid);
1624 case MUX_S_PERMISSION_DENIED:
1625 e = buffer_get_string(&m, NULL);
1627 fatal("Master refused forwarding request: %s", e);
1629 e = buffer_get_string(&m, NULL);
1631 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1634 error("%s: unexpected response from master 0x%08x",
1638 muxclient_request_id++;
1640 signal(SIGHUP, control_client_sighandler);
1641 signal(SIGINT, control_client_sighandler);
1642 signal(SIGTERM, control_client_sighandler);
1643 signal(SIGWINCH, control_client_sigrelay);
1646 * Stick around until the controlee closes the client_fd.
1649 if (mux_client_read_packet(fd, &m) != 0) {
1650 if (errno == EPIPE ||
1651 (errno == EINTR && muxclient_terminate != 0))
1653 fatal("%s: mux_client_read_packet: %s",
1654 __func__, strerror(errno));
1656 fatal("%s: master returned unexpected message %u", __func__, type);
1659 /* Multiplex client main loop. */
1661 muxclient(const char *path)
1663 struct sockaddr_un addr;
1668 if (muxclient_command == 0) {
1669 if (stdio_forward_host != NULL)
1670 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1672 muxclient_command = SSHMUX_COMMAND_OPEN;
1675 switch (options.control_master) {
1676 case SSHCTL_MASTER_AUTO:
1677 case SSHCTL_MASTER_AUTO_ASK:
1678 debug("auto-mux: Trying existing master");
1680 case SSHCTL_MASTER_NO:
1686 memset(&addr, '\0', sizeof(addr));
1687 addr.sun_family = AF_UNIX;
1688 sun_len = offsetof(struct sockaddr_un, sun_path) +
1691 if (strlcpy(addr.sun_path, path,
1692 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1693 fatal("ControlPath too long");
1695 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1696 fatal("%s socket(): %s", __func__, strerror(errno));
1698 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
1699 switch (muxclient_command) {
1700 case SSHMUX_COMMAND_OPEN:
1701 case SSHMUX_COMMAND_STDIO_FWD:
1704 fatal("Control socket connect(%.100s): %s", path,
1707 if (errno == ENOENT)
1708 debug("Control socket \"%.100s\" does not exist", path);
1710 error("Control socket connect(%.100s): %s", path,
1718 if (mux_client_hello_exchange(sock) != 0) {
1719 error("%s: master hello exchange failed", __func__);
1724 switch (muxclient_command) {
1725 case SSHMUX_COMMAND_ALIVE_CHECK:
1726 if ((pid = mux_client_request_alive(sock)) == 0)
1727 fatal("%s: master alive check failed", __func__);
1728 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
1730 case SSHMUX_COMMAND_TERMINATE:
1731 mux_client_request_terminate(sock);
1732 fprintf(stderr, "Exit request sent.\r\n");
1734 case SSHMUX_COMMAND_OPEN:
1735 if (mux_client_request_forwards(sock) != 0) {
1736 error("%s: master forward request failed", __func__);
1739 mux_client_request_session(sock);
1741 case SSHMUX_COMMAND_STDIO_FWD:
1742 mux_client_request_stdio_fwd(sock);
1745 fatal("unrecognised muxclient_command %d", muxclient_command);