1 /* $OpenBSD: mux.c,v 1.11 2010/01/26 02:15:20 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);
215 channel_cancel_cleanup(c->self);
218 /* Check mux client environment variables before passing them to mux master. */
220 env_permitted(char *env)
223 char name[1024], *cp;
225 if ((cp = strchr(env, '=')) == NULL || cp == env)
227 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
228 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
229 error("env_permitted: name '%.100s...' too long", env);
233 for (i = 0; i < options.num_send_env; i++)
234 if (match_pattern(name, options.send_env[i]))
240 /* Mux master protocol message handlers */
243 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
246 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
249 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
250 if (state->hello_rcvd) {
251 error("%s: HELLO received twice", __func__);
254 if (buffer_get_int_ret(&ver, m) != 0) {
256 error("%s: malformed message", __func__);
259 if (ver != SSHMUX_VER) {
260 error("Unsupported multiplexing protocol version %d "
261 "(expected %d)", ver, SSHMUX_VER);
264 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
266 /* No extensions are presently defined */
267 while (buffer_len(m) > 0) {
268 char *name = buffer_get_string_ret(m, NULL);
269 char *value = buffer_get_string_ret(m, NULL);
271 if (name == NULL || value == NULL) {
276 debug2("Unrecognised slave extension \"%s\"", name);
280 state->hello_rcvd = 1;
285 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
288 struct mux_session_confirm_ctx *cctx;
289 char *reserved, *cmd, *cp;
290 u_int i, j, len, env_len, escape_char, window, packetmax;
293 /* Reply for SSHMUX_COMMAND_OPEN */
294 cctx = xcalloc(1, sizeof(*cctx));
296 cmd = reserved = NULL;
297 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
298 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
299 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
300 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
301 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
302 buffer_get_int_ret(&escape_char, m) != 0 ||
303 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
304 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
308 if (reserved != NULL)
310 if (cctx->term != NULL)
312 error("%s: malformed message", __func__);
320 while (buffer_len(m) > 0) {
321 #define MUX_MAX_ENV_VARS 4096
322 if ((cp = buffer_get_string_ret(m, &len)) == NULL) {
326 if (!env_permitted(cp)) {
330 cctx->env = xrealloc(cctx->env, env_len + 2,
332 cctx->env[env_len++] = cp;
333 cctx->env[env_len] = NULL;
334 if (env_len > MUX_MAX_ENV_VARS) {
335 error(">%d environment variables received, ignoring "
336 "additional", MUX_MAX_ENV_VARS);
341 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
342 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
343 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
344 cctx->want_subsys, cctx->term, cmd, env_len);
346 buffer_init(&cctx->cmd);
347 buffer_append(&cctx->cmd, cmd, strlen(cmd));
351 /* Gather fds from client */
352 for(i = 0; i < 3; i++) {
353 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
354 error("%s: failed to receive fd %d from slave",
356 for (j = 0; j < i; j++)
358 for (j = 0; j < env_len; j++)
363 buffer_free(&cctx->cmd);
367 buffer_put_int(r, MUX_S_FAILURE);
368 buffer_put_int(r, rid);
369 buffer_put_cstring(r,
370 "did not receive file descriptors");
375 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
376 new_fd[0], new_fd[1], new_fd[2]);
378 /* XXX support multiple child sessions in future */
379 if (c->remote_id != -1) {
380 debug2("%s: session already open", __func__);
382 buffer_put_int(r, MUX_S_FAILURE);
383 buffer_put_int(r, rid);
384 buffer_put_cstring(r, "Multiple sessions not supported");
391 for (i = 0; i < env_len; i++)
395 buffer_free(&cctx->cmd);
399 if (options.control_master == SSHCTL_MASTER_ASK ||
400 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
401 if (!ask_permission("Allow shared connection to %s? ", host)) {
402 debug2("%s: session refused by user", __func__);
404 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
405 buffer_put_int(r, rid);
406 buffer_put_cstring(r, "Permission denied");
411 /* Try to pick up ttymodes from client before it goes raw */
412 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
413 error("%s: tcgetattr: %s", __func__, strerror(errno));
415 /* enable nonblocking unless tty */
416 if (!isatty(new_fd[0]))
417 set_nonblock(new_fd[0]);
418 if (!isatty(new_fd[1]))
419 set_nonblock(new_fd[1]);
420 if (!isatty(new_fd[2]))
421 set_nonblock(new_fd[2]);
423 window = CHAN_SES_WINDOW_DEFAULT;
424 packetmax = CHAN_SES_PACKET_DEFAULT;
425 if (cctx->want_tty) {
430 nc = channel_new("session", SSH_CHANNEL_OPENING,
431 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
432 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
434 nc->ctl_chan = c->self; /* link session -> control channel */
435 c->remote_id = nc->self; /* link control -> session channel */
437 if (cctx->want_tty && escape_char != 0xffffffff) {
438 channel_register_filter(nc->self,
439 client_simple_escape_filter, NULL,
440 client_filter_cleanup,
441 client_new_escape_filter_ctx((int)escape_char));
444 debug2("%s: channel_new: %d linked to control channel %d",
445 __func__, nc->self, nc->ctl_chan);
447 channel_send_open(nc->self);
448 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
449 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
452 /* XXX defer until mux_session_confirm() fires */
453 buffer_put_int(r, MUX_S_SESSION_OPENED);
454 buffer_put_int(r, rid);
455 buffer_put_int(r, nc->self);
461 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
463 debug2("%s: channel %d: alive check", __func__, c->self);
466 buffer_put_int(r, MUX_S_ALIVE);
467 buffer_put_int(r, rid);
468 buffer_put_int(r, (u_int)getpid());
474 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
476 debug2("%s: channel %d: terminate request", __func__, c->self);
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? ",
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");
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 */
498 format_forward(u_int ftype, Forward *fwd)
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);
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);
517 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
518 (fwd->listen_host == NULL) ?
519 "LOCALHOST" : fwd->listen_host,
521 fwd->connect_host, fwd->connect_port);
524 fatal("%s: unknown forward type %u", __func__, ftype);
530 compare_host(const char *a, const char *b)
532 if (a == NULL && b == NULL)
534 if (a == NULL || b == NULL)
536 return strcmp(a, b) == 0;
540 compare_forward(Forward *a, Forward *b)
542 if (!compare_host(a->listen_host, b->listen_host))
544 if (a->listen_port != b->listen_port)
546 if (!compare_host(a->connect_host, b->connect_host))
548 if (a->connect_port != b->connect_port)
555 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
558 char *fwd_desc = NULL;
560 int i, ret = 0, freefwd = 1;
562 fwd.listen_host = fwd.connect_host = NULL;
563 if (buffer_get_int_ret(&ftype, m) != 0 ||
564 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
565 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
566 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
567 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
568 error("%s: malformed message", __func__);
573 if (*fwd.listen_host == '\0') {
574 xfree(fwd.listen_host);
575 fwd.listen_host = NULL;
577 if (*fwd.connect_host == '\0') {
578 xfree(fwd.connect_host);
579 fwd.connect_host = NULL;
582 debug2("%s: channel %d: request %s", __func__, c->self,
583 (fwd_desc = format_forward(ftype, &fwd)));
585 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
586 ftype != MUX_FWD_DYNAMIC) {
587 logit("%s: invalid forwarding type %u", __func__, ftype);
589 xfree(fwd.listen_host);
590 xfree(fwd.connect_host);
591 buffer_put_int(r, MUX_S_FAILURE);
592 buffer_put_int(r, rid);
593 buffer_put_cstring(r, "Invalid forwarding request");
596 /* XXX support rport0 forwarding with reply of port assigned */
597 if (fwd.listen_port == 0 || fwd.listen_port >= 65536) {
598 logit("%s: invalid listen port %u", __func__,
602 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
603 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
604 logit("%s: invalid connect port %u", __func__,
608 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
609 logit("%s: missing connect host", __func__);
613 /* Skip forwards that have already been requested */
616 case MUX_FWD_DYNAMIC:
617 for (i = 0; i < options.num_local_forwards; i++) {
618 if (compare_forward(&fwd,
619 options.local_forwards + i)) {
621 debug2("%s: found existing forwarding",
623 buffer_put_int(r, MUX_S_OK);
624 buffer_put_int(r, rid);
630 for (i = 0; i < options.num_remote_forwards; i++) {
631 if (compare_forward(&fwd,
632 options.remote_forwards + i))
638 if (options.control_master == SSHCTL_MASTER_ASK ||
639 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
640 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
641 debug2("%s: forwarding refused by user", __func__);
642 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
643 buffer_put_int(r, rid);
644 buffer_put_cstring(r, "Permission denied");
649 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
650 if (options.num_local_forwards + 1 >=
651 SSH_MAX_FORWARDS_PER_DIRECTION ||
652 channel_setup_local_fwd_listener(fwd.listen_host,
653 fwd.listen_port, fwd.connect_host, fwd.connect_port,
654 options.gateway_ports) < 0) {
656 logit("slave-requested %s failed", fwd_desc);
657 buffer_put_int(r, MUX_S_FAILURE);
658 buffer_put_int(r, rid);
659 buffer_put_cstring(r, "Port forwarding failed");
662 add_local_forward(&options, &fwd);
665 /* XXX wait for remote to confirm */
666 if (options.num_remote_forwards + 1 >=
667 SSH_MAX_FORWARDS_PER_DIRECTION ||
668 channel_request_remote_forwarding(fwd.listen_host,
669 fwd.listen_port, fwd.connect_host, fwd.connect_port) < 0)
671 add_remote_forward(&options, &fwd);
674 buffer_put_int(r, MUX_S_OK);
675 buffer_put_int(r, rid);
677 if (fwd_desc != NULL)
680 if (fwd.listen_host != NULL)
681 xfree(fwd.listen_host);
682 if (fwd.connect_host != NULL)
683 xfree(fwd.connect_host);
689 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
692 char *fwd_desc = NULL;
696 fwd.listen_host = fwd.connect_host = NULL;
697 if (buffer_get_int_ret(&ftype, m) != 0 ||
698 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
699 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
700 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
701 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
702 error("%s: malformed message", __func__);
707 if (*fwd.listen_host == '\0') {
708 xfree(fwd.listen_host);
709 fwd.listen_host = NULL;
711 if (*fwd.connect_host == '\0') {
712 xfree(fwd.connect_host);
713 fwd.connect_host = NULL;
716 debug2("%s: channel %d: request %s", __func__, c->self,
717 (fwd_desc = format_forward(ftype, &fwd)));
719 /* XXX implement this */
720 buffer_put_int(r, MUX_S_FAILURE);
721 buffer_put_int(r, rid);
722 buffer_put_cstring(r, "unimplemented");
725 if (fwd_desc != NULL)
727 if (fwd.listen_host != NULL)
728 xfree(fwd.listen_host);
729 if (fwd.connect_host != NULL)
730 xfree(fwd.connect_host);
736 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
739 char *reserved, *chost;
743 chost = reserved = NULL;
744 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
745 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
746 buffer_get_int_ret(&cport, m) != 0) {
747 if (reserved != NULL)
751 error("%s: malformed message", __func__);
756 debug2("%s: channel %d: request stdio fwd to %s:%u",
757 __func__, c->self, chost, cport);
759 /* Gather fds from client */
760 for(i = 0; i < 2; i++) {
761 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
762 error("%s: failed to receive fd %d from slave",
764 for (j = 0; j < i; j++)
769 buffer_put_int(r, MUX_S_FAILURE);
770 buffer_put_int(r, rid);
771 buffer_put_cstring(r,
772 "did not receive file descriptors");
777 debug3("%s: got fds stdin %d, stdout %d", __func__,
778 new_fd[0], new_fd[1]);
780 /* XXX support multiple child sessions in future */
781 if (c->remote_id != -1) {
782 debug2("%s: session already open", __func__);
784 buffer_put_int(r, MUX_S_FAILURE);
785 buffer_put_int(r, rid);
786 buffer_put_cstring(r, "Multiple sessions not supported");
794 if (options.control_master == SSHCTL_MASTER_ASK ||
795 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
796 if (!ask_permission("Allow forward to to %s:%u? ",
798 debug2("%s: stdio fwd refused by user", __func__);
800 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
801 buffer_put_int(r, rid);
802 buffer_put_cstring(r, "Permission denied");
807 /* enable nonblocking unless tty */
808 if (!isatty(new_fd[0]))
809 set_nonblock(new_fd[0]);
810 if (!isatty(new_fd[1]))
811 set_nonblock(new_fd[1]);
813 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
815 nc->ctl_chan = c->self; /* link session -> control channel */
816 c->remote_id = nc->self; /* link control -> session channel */
818 debug2("%s: channel_new: %d linked to control channel %d",
819 __func__, nc->self, nc->ctl_chan);
821 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
824 /* XXX defer until channel confirmed */
825 buffer_put_int(r, MUX_S_SESSION_OPENED);
826 buffer_put_int(r, rid);
827 buffer_put_int(r, nc->self);
832 /* Channel callbacks fired on read/write from mux slave fd */
834 mux_master_read_cb(Channel *c)
836 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
839 u_int type, rid, have, i;
843 if (c->mux_ctx == NULL) {
844 state = xcalloc(1, sizeof(state));
846 channel_register_cleanup(c->self,
847 mux_master_control_cleanup_cb, 0);
851 buffer_put_int(&out, MUX_MSG_HELLO);
852 buffer_put_int(&out, SSHMUX_VER);
854 buffer_put_string(&c->output, buffer_ptr(&out),
857 debug3("%s: channel %d: hello sent", __func__, c->self);
864 /* Channel code ensures that we receive whole packets */
865 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
867 error("%s: malformed message", __func__);
870 buffer_append(&in, ptr, have);
872 if (buffer_get_int_ret(&type, &in) != 0)
874 debug3("%s: channel %d packet type 0x%08x len %u",
875 __func__, c->self, type, buffer_len(&in));
877 if (type == MUX_MSG_HELLO)
880 if (!state->hello_rcvd) {
881 error("%s: expected MUX_MSG_HELLO(0x%08x), "
882 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
885 if (buffer_get_int_ret(&rid, &in) != 0)
889 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
890 if (type == mux_master_handlers[i].type) {
891 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
895 if (mux_master_handlers[i].handler == NULL) {
896 error("%s: unsupported mux message 0x%08x", __func__, type);
897 buffer_put_int(&out, MUX_S_FAILURE);
898 buffer_put_int(&out, rid);
899 buffer_put_cstring(&out, "unsupported request");
902 /* Enqueue reply packet */
903 if (buffer_len(&out) != 0) {
904 buffer_put_string(&c->output, buffer_ptr(&out),
914 mux_exit_message(Channel *c, int exitval)
919 debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
922 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
923 fatal("%s: channel %d missing mux channel %d",
924 __func__, c->self, c->ctl_chan);
926 /* Append exit message packet to control socket output queue */
928 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
929 buffer_put_int(&m, c->self);
930 buffer_put_int(&m, exitval);
932 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
936 /* Prepare a mux master to listen on a Unix domain socket. */
938 muxserver_listen(void)
940 struct sockaddr_un addr;
944 if (options.control_path == NULL ||
945 options.control_master == SSHCTL_MASTER_NO)
948 debug("setting up multiplex master socket");
950 memset(&addr, '\0', sizeof(addr));
951 addr.sun_family = AF_UNIX;
952 sun_len = offsetof(struct sockaddr_un, sun_path) +
953 strlen(options.control_path) + 1;
955 if (strlcpy(addr.sun_path, options.control_path,
956 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
957 fatal("ControlPath too long");
959 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
960 fatal("%s socket(): %s", __func__, strerror(errno));
962 old_umask = umask(0177);
963 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
965 if (errno == EINVAL || errno == EADDRINUSE) {
966 error("ControlSocket %s already exists, "
967 "disabling multiplexing", options.control_path);
968 close(muxserver_sock);
970 xfree(options.control_path);
971 options.control_path = NULL;
972 options.control_master = SSHCTL_MASTER_NO;
975 fatal("%s bind(): %s", __func__, strerror(errno));
979 if (listen(muxserver_sock, 64) == -1)
980 fatal("%s listen(): %s", __func__, strerror(errno));
982 set_nonblock(muxserver_sock);
984 mux_listener_channel = channel_new("mux listener",
985 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
986 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
987 0, addr.sun_path, 1);
988 mux_listener_channel->mux_rcb = mux_master_read_cb;
989 debug3("%s: mux listener channel %d fd %d", __func__,
990 mux_listener_channel->self, mux_listener_channel->sock);
993 /* Callback on open confirmation in mux master for a mux client session. */
995 mux_session_confirm(int id, void *arg)
997 struct mux_session_confirm_ctx *cctx = arg;
1003 fatal("%s: cctx == NULL", __func__);
1004 if ((c = channel_by_id(id)) == NULL)
1005 fatal("%s: no channel for id %d", __func__, id);
1007 display = getenv("DISPLAY");
1008 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1010 /* Get reasonable local authentication information. */
1011 client_x11_get_proto(display, options.xauth_location,
1012 options.forward_x11_trusted, &proto, &data);
1013 /* Request forwarding with authentication spoofing. */
1014 debug("Requesting X11 forwarding with authentication spoofing.");
1015 x11_request_forwarding_with_spoofing(id, display, proto, data);
1016 /* XXX wait for reply */
1019 if (cctx->want_agent_fwd && options.forward_agent) {
1020 debug("Requesting authentication agent forwarding.");
1021 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1025 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1026 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1028 c->open_confirm_ctx = NULL;
1029 buffer_free(&cctx->cmd);
1031 if (cctx->env != NULL) {
1032 for (i = 0; cctx->env[i] != NULL; i++)
1033 xfree(cctx->env[i]);
1039 /* ** Multiplexing client support */
1041 /* Exit signal handler */
1043 control_client_sighandler(int signo)
1045 muxclient_terminate = signo;
1049 * Relay signal handler - used to pass some signals from mux client to
1053 control_client_sigrelay(int signo)
1055 int save_errno = errno;
1057 if (muxserver_pid > 1)
1058 kill(muxserver_pid, signo);
1064 mux_client_read(int fd, Buffer *b, u_int need)
1072 pfd.events = POLLIN;
1073 p = buffer_append_space(b, need);
1074 for (have = 0; have < need; ) {
1075 if (muxclient_terminate) {
1079 len = read(fd, p + have, need - have);
1082 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1086 (void)poll(&pfd, 1, -1);
1104 mux_client_write_packet(int fd, Buffer *m)
1113 pfd.events = POLLOUT;
1114 buffer_init(&queue);
1115 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1117 need = buffer_len(&queue);
1118 ptr = buffer_ptr(&queue);
1120 for (have = 0; have < need; ) {
1121 if (muxclient_terminate) {
1122 buffer_free(&queue);
1126 len = write(fd, ptr + have, need - have);
1129 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1133 (void)poll(&pfd, 1, -1);
1139 buffer_free(&queue);
1145 buffer_free(&queue);
1151 buffer_free(&queue);
1156 mux_client_read_packet(int fd, Buffer *m)
1163 buffer_init(&queue);
1164 if (mux_client_read(fd, &queue, 4) != 0) {
1165 if ((oerrno = errno) == EPIPE)
1166 debug3("%s: read header failed: %s", __func__, strerror(errno));
1170 need = get_u32(buffer_ptr(&queue));
1171 if (mux_client_read(fd, &queue, need) != 0) {
1173 debug3("%s: read body failed: %s", __func__, strerror(errno));
1177 ptr = buffer_get_string_ptr(&queue, &have);
1178 buffer_append(m, ptr, have);
1179 buffer_free(&queue);
1184 mux_client_hello_exchange(int fd)
1190 buffer_put_int(&m, MUX_MSG_HELLO);
1191 buffer_put_int(&m, SSHMUX_VER);
1194 if (mux_client_write_packet(fd, &m) != 0)
1195 fatal("%s: write packet: %s", __func__, strerror(errno));
1199 /* Read their HELLO */
1200 if (mux_client_read_packet(fd, &m) != 0) {
1205 type = buffer_get_int(&m);
1206 if (type != MUX_MSG_HELLO)
1207 fatal("%s: expected HELLO (%u) received %u",
1208 __func__, MUX_MSG_HELLO, type);
1209 ver = buffer_get_int(&m);
1210 if (ver != SSHMUX_VER)
1211 fatal("Unsupported multiplexing protocol version %d "
1212 "(expected %d)", ver, SSHMUX_VER);
1213 debug2("%s: master version %u", __func__, ver);
1214 /* No extensions are presently defined */
1215 while (buffer_len(&m) > 0) {
1216 char *name = buffer_get_string(&m, NULL);
1217 char *value = buffer_get_string(&m, NULL);
1219 debug2("Unrecognised master extension \"%s\"", name);
1228 mux_client_request_alive(int fd)
1232 u_int pid, type, rid;
1234 debug3("%s: entering", __func__);
1237 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1238 buffer_put_int(&m, muxclient_request_id);
1240 if (mux_client_write_packet(fd, &m) != 0)
1241 fatal("%s: write packet: %s", __func__, strerror(errno));
1245 /* Read their reply */
1246 if (mux_client_read_packet(fd, &m) != 0) {
1251 type = buffer_get_int(&m);
1252 if (type != MUX_S_ALIVE) {
1253 e = buffer_get_string(&m, NULL);
1254 fatal("%s: master returned error: %s", __func__, e);
1257 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1258 fatal("%s: out of sequence reply: my id %u theirs %u",
1259 __func__, muxclient_request_id, rid);
1260 pid = buffer_get_int(&m);
1263 debug3("%s: done pid = %u", __func__, pid);
1265 muxclient_request_id++;
1271 mux_client_request_terminate(int fd)
1277 debug3("%s: entering", __func__);
1280 buffer_put_int(&m, MUX_C_TERMINATE);
1281 buffer_put_int(&m, muxclient_request_id);
1283 if (mux_client_write_packet(fd, &m) != 0)
1284 fatal("%s: write packet: %s", __func__, strerror(errno));
1288 /* Read their reply */
1289 if (mux_client_read_packet(fd, &m) != 0) {
1290 /* Remote end exited already */
1291 if (errno == EPIPE) {
1295 fatal("%s: read from master failed: %s",
1296 __func__, strerror(errno));
1299 type = buffer_get_int(&m);
1300 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1301 fatal("%s: out of sequence reply: my id %u theirs %u",
1302 __func__, muxclient_request_id, rid);
1306 case MUX_S_PERMISSION_DENIED:
1307 e = buffer_get_string(&m, NULL);
1308 fatal("Master refused termination request: %s", e);
1310 e = buffer_get_string(&m, NULL);
1311 fatal("%s: termination request failed: %s", __func__, e);
1313 fatal("%s: unexpected response from master 0x%08x",
1317 muxclient_request_id++;
1321 mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
1327 fwd_desc = format_forward(ftype, fwd);
1328 debug("Requesting %s", fwd_desc);
1332 buffer_put_int(&m, MUX_C_OPEN_FWD);
1333 buffer_put_int(&m, muxclient_request_id);
1334 buffer_put_int(&m, ftype);
1335 buffer_put_cstring(&m,
1336 fwd->listen_host == NULL ? "" : fwd->listen_host);
1337 buffer_put_int(&m, fwd->listen_port);
1338 buffer_put_cstring(&m,
1339 fwd->connect_host == NULL ? "" : fwd->connect_host);
1340 buffer_put_int(&m, fwd->connect_port);
1342 if (mux_client_write_packet(fd, &m) != 0)
1343 fatal("%s: write packet: %s", __func__, strerror(errno));
1347 /* Read their reply */
1348 if (mux_client_read_packet(fd, &m) != 0) {
1353 type = buffer_get_int(&m);
1354 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1355 fatal("%s: out of sequence reply: my id %u theirs %u",
1356 __func__, muxclient_request_id, rid);
1360 case MUX_S_PERMISSION_DENIED:
1361 e = buffer_get_string(&m, NULL);
1363 error("Master refused forwarding request: %s", e);
1366 e = buffer_get_string(&m, NULL);
1368 error("%s: session request failed: %s", __func__, e);
1371 fatal("%s: unexpected response from master 0x%08x",
1376 muxclient_request_id++;
1381 mux_client_request_forwards(int fd)
1385 debug3("%s: requesting forwardings: %d local, %d remote", __func__,
1386 options.num_local_forwards, options.num_remote_forwards);
1388 /* XXX ExitOnForwardingFailure */
1389 for (i = 0; i < options.num_local_forwards; i++) {
1390 if (mux_client_request_forward(fd,
1391 options.local_forwards[i].connect_port == 0 ?
1392 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1393 options.local_forwards + i) != 0)
1396 for (i = 0; i < options.num_remote_forwards; i++) {
1397 if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
1398 options.remote_forwards + i) != 0)
1405 mux_client_request_session(int fd)
1409 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1410 extern char **environ;
1413 debug3("%s: entering", __func__);
1415 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1416 error("%s: master alive request failed", __func__);
1420 signal(SIGPIPE, SIG_IGN);
1422 if (stdin_null_flag) {
1423 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1424 fatal("open(/dev/null): %s", strerror(errno));
1425 if (dup2(devnull, STDIN_FILENO) == -1)
1426 fatal("dup2: %s", strerror(errno));
1427 if (devnull > STDERR_FILENO)
1431 term = getenv("TERM");
1434 buffer_put_int(&m, MUX_C_NEW_SESSION);
1435 buffer_put_int(&m, muxclient_request_id);
1436 buffer_put_cstring(&m, ""); /* reserved */
1437 buffer_put_int(&m, tty_flag);
1438 buffer_put_int(&m, options.forward_x11);
1439 buffer_put_int(&m, options.forward_agent);
1440 buffer_put_int(&m, subsystem_flag);
1441 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1442 0xffffffff : (u_int)options.escape_char);
1443 buffer_put_cstring(&m, term == NULL ? "" : term);
1444 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1446 if (options.num_send_env > 0 && environ != NULL) {
1447 /* Pass environment */
1448 for (i = 0; environ[i] != NULL; i++) {
1449 if (env_permitted(environ[i])) {
1450 buffer_put_cstring(&m, environ[i]);
1455 if (mux_client_write_packet(fd, &m) != 0)
1456 fatal("%s: write packet: %s", __func__, strerror(errno));
1458 /* Send the stdio file descriptors */
1459 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1460 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1461 mm_send_fd(fd, STDERR_FILENO) == -1)
1462 fatal("%s: send fds failed", __func__);
1464 debug3("%s: session request sent", __func__);
1466 /* Read their reply */
1468 if (mux_client_read_packet(fd, &m) != 0) {
1469 error("%s: read from master failed: %s",
1470 __func__, strerror(errno));
1475 type = buffer_get_int(&m);
1476 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1477 fatal("%s: out of sequence reply: my id %u theirs %u",
1478 __func__, muxclient_request_id, rid);
1480 case MUX_S_SESSION_OPENED:
1481 sid = buffer_get_int(&m);
1482 debug("%s: master session id: %u", __func__, sid);
1484 case MUX_S_PERMISSION_DENIED:
1485 e = buffer_get_string(&m, NULL);
1487 error("Master refused forwarding request: %s", e);
1490 e = buffer_get_string(&m, NULL);
1492 error("%s: forwarding request failed: %s", __func__, e);
1496 error("%s: unexpected response from master 0x%08x",
1500 muxclient_request_id++;
1502 signal(SIGHUP, control_client_sighandler);
1503 signal(SIGINT, control_client_sighandler);
1504 signal(SIGTERM, control_client_sighandler);
1505 signal(SIGWINCH, control_client_sigrelay);
1508 enter_raw_mode(force_tty_flag);
1511 * Stick around until the controlee closes the client_fd.
1512 * Before it does, it is expected to write an exit message.
1513 * This process must read the value and wait for the closure of
1514 * the client_fd; if this one closes early, the multiplex master will
1515 * terminate early too (possibly losing data).
1517 for (exitval = 255, exitval_seen = 0;;) {
1519 if (mux_client_read_packet(fd, &m) != 0)
1521 type = buffer_get_int(&m);
1522 if (type != MUX_S_EXIT_MESSAGE) {
1523 e = buffer_get_string(&m, NULL);
1524 fatal("%s: master returned error: %s", __func__, e);
1526 if ((esid = buffer_get_int(&m)) != sid)
1527 fatal("%s: exit on unknown session: my id %u theirs %u",
1528 __func__, sid, esid);
1529 debug("%s: master session id: %u", __func__, sid);
1531 fatal("%s: exitval sent twice", __func__);
1532 exitval = buffer_get_int(&m);
1537 leave_raw_mode(force_tty_flag);
1539 if (muxclient_terminate) {
1540 debug2("Exiting on signal %d", muxclient_terminate);
1542 } else if (!exitval_seen) {
1543 debug2("Control master terminated unexpectedly");
1546 debug2("Received exit status from master %d", exitval);
1548 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1549 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1555 mux_client_request_stdio_fwd(int fd)
1559 u_int type, rid, sid;
1562 debug3("%s: entering", __func__);
1564 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1565 error("%s: master alive request failed", __func__);
1569 signal(SIGPIPE, SIG_IGN);
1571 if (stdin_null_flag) {
1572 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1573 fatal("open(/dev/null): %s", strerror(errno));
1574 if (dup2(devnull, STDIN_FILENO) == -1)
1575 fatal("dup2: %s", strerror(errno));
1576 if (devnull > STDERR_FILENO)
1581 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1582 buffer_put_int(&m, muxclient_request_id);
1583 buffer_put_cstring(&m, ""); /* reserved */
1584 buffer_put_cstring(&m, stdio_forward_host);
1585 buffer_put_int(&m, stdio_forward_port);
1587 if (mux_client_write_packet(fd, &m) != 0)
1588 fatal("%s: write packet: %s", __func__, strerror(errno));
1590 /* Send the stdio file descriptors */
1591 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1592 mm_send_fd(fd, STDOUT_FILENO) == -1)
1593 fatal("%s: send fds failed", __func__);
1595 debug3("%s: stdio forward request sent", __func__);
1597 /* Read their reply */
1600 if (mux_client_read_packet(fd, &m) != 0) {
1601 error("%s: read from master failed: %s",
1602 __func__, strerror(errno));
1607 type = buffer_get_int(&m);
1608 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1609 fatal("%s: out of sequence reply: my id %u theirs %u",
1610 __func__, muxclient_request_id, rid);
1612 case MUX_S_SESSION_OPENED:
1613 sid = buffer_get_int(&m);
1614 debug("%s: master session id: %u", __func__, sid);
1616 case MUX_S_PERMISSION_DENIED:
1617 e = buffer_get_string(&m, NULL);
1619 fatal("Master refused forwarding request: %s", e);
1621 e = buffer_get_string(&m, NULL);
1623 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1626 error("%s: unexpected response from master 0x%08x",
1630 muxclient_request_id++;
1632 signal(SIGHUP, control_client_sighandler);
1633 signal(SIGINT, control_client_sighandler);
1634 signal(SIGTERM, control_client_sighandler);
1635 signal(SIGWINCH, control_client_sigrelay);
1638 * Stick around until the controlee closes the client_fd.
1641 if (mux_client_read_packet(fd, &m) != 0) {
1642 if (errno == EPIPE ||
1643 (errno == EINTR && muxclient_terminate != 0))
1645 fatal("%s: mux_client_read_packet: %s",
1646 __func__, strerror(errno));
1648 fatal("%s: master returned unexpected message %u", __func__, type);
1651 /* Multiplex client main loop. */
1653 muxclient(const char *path)
1655 struct sockaddr_un addr;
1660 if (muxclient_command == 0) {
1661 if (stdio_forward_host != NULL)
1662 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1664 muxclient_command = SSHMUX_COMMAND_OPEN;
1667 switch (options.control_master) {
1668 case SSHCTL_MASTER_AUTO:
1669 case SSHCTL_MASTER_AUTO_ASK:
1670 debug("auto-mux: Trying existing master");
1672 case SSHCTL_MASTER_NO:
1678 memset(&addr, '\0', sizeof(addr));
1679 addr.sun_family = AF_UNIX;
1680 sun_len = offsetof(struct sockaddr_un, sun_path) +
1683 if (strlcpy(addr.sun_path, path,
1684 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1685 fatal("ControlPath too long");
1687 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1688 fatal("%s socket(): %s", __func__, strerror(errno));
1690 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
1691 switch (muxclient_command) {
1692 case SSHMUX_COMMAND_OPEN:
1693 case SSHMUX_COMMAND_STDIO_FWD:
1696 fatal("Control socket connect(%.100s): %s", path,
1699 if (errno == ENOENT)
1700 debug("Control socket \"%.100s\" does not exist", path);
1702 error("Control socket connect(%.100s): %s", path,
1710 if (mux_client_hello_exchange(sock) != 0) {
1711 error("%s: master hello exchange failed", __func__);
1716 switch (muxclient_command) {
1717 case SSHMUX_COMMAND_ALIVE_CHECK:
1718 if ((pid = mux_client_request_alive(sock)) == 0)
1719 fatal("%s: master alive check failed", __func__);
1720 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
1722 case SSHMUX_COMMAND_TERMINATE:
1723 mux_client_request_terminate(sock);
1724 fprintf(stderr, "Exit request sent.\r\n");
1726 case SSHMUX_COMMAND_OPEN:
1727 if (mux_client_request_forwards(sock) != 0) {
1728 error("%s: master forward request failed", __func__);
1731 mux_client_request_session(sock);
1733 case SSHMUX_COMMAND_STDIO_FWD:
1734 mux_client_request_stdio_fwd(sock);
1737 fatal("unrecognised muxclient_command %d", muxclient_command);