1 /* $OpenBSD: mux.c,v 1.60 2016/06/03 03:14:41 dtucker 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>
37 #include <sys/socket.h>
56 # ifdef HAVE_SYS_POLL_H
57 # include <sys/poll.h>
65 #include "openbsd-compat/sys-queue.h"
70 #include "pathnames.h"
77 #include "monitor_fdpass.h"
81 #include "clientloop.h"
85 extern Options options;
86 extern int stdin_null_flag;
88 extern int subsystem_flag;
89 extern Buffer command;
90 extern volatile sig_atomic_t quit_pending;
92 /* Context for session open confirmation callback */
93 struct mux_session_confirm_ctx {
105 /* Context for stdio fwd open confirmation callback */
106 struct mux_stdio_confirm_ctx {
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 *);
162 static void mux_stdio_confirm(int, int, void *);
164 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
165 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
173 static const struct {
175 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
176 } mux_master_handlers[] = {
177 { MUX_MSG_HELLO, process_mux_master_hello },
178 { MUX_C_NEW_SESSION, process_mux_new_session },
179 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
180 { MUX_C_TERMINATE, process_mux_terminate },
181 { MUX_C_OPEN_FWD, process_mux_open_fwd },
182 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
183 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
184 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
188 /* Cleanup callback fired on closure of mux slave _session_ channel */
191 mux_master_session_cleanup_cb(int cid, void *unused)
193 Channel *cc, *c = channel_by_id(cid);
195 debug3("%s: entering for channel %d", __func__, cid);
197 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
198 if (c->ctl_chan != -1) {
199 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
200 fatal("%s: channel %d missing control channel %d",
201 __func__, c->self, c->ctl_chan);
204 chan_rcvd_oclose(cc);
206 channel_cancel_cleanup(c->self);
209 /* Cleanup callback fired on closure of mux slave _control_ channel */
212 mux_master_control_cleanup_cb(int cid, void *unused)
214 Channel *sc, *c = channel_by_id(cid);
216 debug3("%s: entering for channel %d", __func__, cid);
218 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
219 if (c->remote_id != -1) {
220 if ((sc = channel_by_id(c->remote_id)) == NULL)
221 fatal("%s: channel %d missing session channel %d",
222 __func__, c->self, c->remote_id);
225 if (sc->type != SSH_CHANNEL_OPEN &&
226 sc->type != SSH_CHANNEL_OPENING) {
227 debug2("%s: channel %d: not open", __func__, sc->self);
230 if (sc->istate == CHAN_INPUT_OPEN)
231 chan_read_failed(sc);
232 if (sc->ostate == CHAN_OUTPUT_OPEN)
233 chan_write_failed(sc);
236 channel_cancel_cleanup(c->self);
239 /* Check mux client environment variables before passing them to mux master. */
241 env_permitted(char *env)
244 char name[1024], *cp;
246 if ((cp = strchr(env, '=')) == NULL || cp == env)
248 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
249 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
250 error("env_permitted: name '%.100s...' too long", env);
254 for (i = 0; i < options.num_send_env; i++)
255 if (match_pattern(name, options.send_env[i]))
261 /* Mux master protocol message handlers */
264 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
267 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
270 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
271 if (state->hello_rcvd) {
272 error("%s: HELLO received twice", __func__);
275 if (buffer_get_int_ret(&ver, m) != 0) {
277 error("%s: malformed message", __func__);
280 if (ver != SSHMUX_VER) {
281 error("Unsupported multiplexing protocol version %d "
282 "(expected %d)", ver, SSHMUX_VER);
285 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
287 /* No extensions are presently defined */
288 while (buffer_len(m) > 0) {
289 char *name = buffer_get_string_ret(m, NULL);
290 char *value = buffer_get_string_ret(m, NULL);
292 if (name == NULL || value == NULL) {
297 debug2("Unrecognised slave extension \"%s\"", name);
301 state->hello_rcvd = 1;
306 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
309 struct mux_session_confirm_ctx *cctx;
310 char *reserved, *cmd, *cp;
311 u_int i, j, len, env_len, escape_char, window, packetmax;
314 /* Reply for SSHMUX_COMMAND_OPEN */
315 cctx = xcalloc(1, sizeof(*cctx));
318 cmd = reserved = NULL;
321 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
322 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
323 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
324 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
325 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
326 buffer_get_int_ret(&escape_char, m) != 0 ||
327 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
328 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
332 for (j = 0; j < env_len; j++)
337 error("%s: malformed message", __func__);
343 while (buffer_len(m) > 0) {
344 #define MUX_MAX_ENV_VARS 4096
345 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
347 if (!env_permitted(cp)) {
351 cctx->env = xreallocarray(cctx->env, env_len + 2,
353 cctx->env[env_len++] = cp;
354 cctx->env[env_len] = NULL;
355 if (env_len > MUX_MAX_ENV_VARS) {
356 error(">%d environment variables received, ignoring "
357 "additional", MUX_MAX_ENV_VARS);
362 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
363 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
364 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
365 cctx->want_subsys, cctx->term, cmd, env_len);
367 buffer_init(&cctx->cmd);
368 buffer_append(&cctx->cmd, cmd, strlen(cmd));
372 /* Gather fds from client */
373 for(i = 0; i < 3; i++) {
374 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
375 error("%s: failed to receive fd %d from slave",
377 for (j = 0; j < i; j++)
379 for (j = 0; j < env_len; j++)
383 buffer_free(&cctx->cmd);
387 buffer_put_int(r, MUX_S_FAILURE);
388 buffer_put_int(r, rid);
389 buffer_put_cstring(r,
390 "did not receive file descriptors");
395 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
396 new_fd[0], new_fd[1], new_fd[2]);
398 /* XXX support multiple child sessions in future */
399 if (c->remote_id != -1) {
400 debug2("%s: session already open", __func__);
402 buffer_put_int(r, MUX_S_FAILURE);
403 buffer_put_int(r, rid);
404 buffer_put_cstring(r, "Multiple sessions not supported");
411 for (i = 0; i < env_len; i++)
415 buffer_free(&cctx->cmd);
420 if (options.control_master == SSHCTL_MASTER_ASK ||
421 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
422 if (!ask_permission("Allow shared connection to %s? ", host)) {
423 debug2("%s: session refused by user", __func__);
425 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
426 buffer_put_int(r, rid);
427 buffer_put_cstring(r, "Permission denied");
432 /* Try to pick up ttymodes from client before it goes raw */
433 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
434 error("%s: tcgetattr: %s", __func__, strerror(errno));
436 /* enable nonblocking unless tty */
437 if (!isatty(new_fd[0]))
438 set_nonblock(new_fd[0]);
439 if (!isatty(new_fd[1]))
440 set_nonblock(new_fd[1]);
441 if (!isatty(new_fd[2]))
442 set_nonblock(new_fd[2]);
444 window = CHAN_SES_WINDOW_DEFAULT;
445 packetmax = CHAN_SES_PACKET_DEFAULT;
446 if (cctx->want_tty) {
451 nc = channel_new("session", SSH_CHANNEL_OPENING,
452 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
453 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
455 nc->ctl_chan = c->self; /* link session -> control channel */
456 c->remote_id = nc->self; /* link control -> session channel */
458 if (cctx->want_tty && escape_char != 0xffffffff) {
459 channel_register_filter(nc->self,
460 client_simple_escape_filter, NULL,
461 client_filter_cleanup,
462 client_new_escape_filter_ctx((int)escape_char));
465 debug2("%s: channel_new: %d linked to control channel %d",
466 __func__, nc->self, nc->ctl_chan);
468 channel_send_open(nc->self);
469 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
470 c->mux_pause = 1; /* stop handling messages until open_confirm done */
471 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
473 /* reply is deferred, sent by mux_session_confirm */
478 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
480 debug2("%s: channel %d: alive check", __func__, c->self);
483 buffer_put_int(r, MUX_S_ALIVE);
484 buffer_put_int(r, rid);
485 buffer_put_int(r, (u_int)getpid());
491 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
493 debug2("%s: channel %d: terminate request", __func__, c->self);
495 if (options.control_master == SSHCTL_MASTER_ASK ||
496 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
497 if (!ask_permission("Terminate shared connection to %s? ",
499 debug2("%s: termination refused by user", __func__);
500 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
501 buffer_put_int(r, rid);
502 buffer_put_cstring(r, "Permission denied");
508 buffer_put_int(r, MUX_S_OK);
509 buffer_put_int(r, rid);
510 /* XXX exit happens too soon - message never makes it to client */
515 format_forward(u_int ftype, struct Forward *fwd)
521 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
522 (fwd->listen_path != NULL) ? fwd->listen_path :
523 (fwd->listen_host == NULL) ?
524 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
525 fwd->listen_host, fwd->listen_port,
526 (fwd->connect_path != NULL) ? fwd->connect_path :
527 fwd->connect_host, fwd->connect_port);
529 case MUX_FWD_DYNAMIC:
530 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
531 (fwd->listen_host == NULL) ?
532 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
533 fwd->listen_host, fwd->listen_port);
536 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
537 (fwd->listen_path != NULL) ? fwd->listen_path :
538 (fwd->listen_host == NULL) ?
539 "LOCALHOST" : fwd->listen_host,
541 (fwd->connect_path != NULL) ? fwd->connect_path :
542 fwd->connect_host, fwd->connect_port);
545 fatal("%s: unknown forward type %u", __func__, ftype);
551 compare_host(const char *a, const char *b)
553 if (a == NULL && b == NULL)
555 if (a == NULL || b == NULL)
557 return strcmp(a, b) == 0;
561 compare_forward(struct Forward *a, struct Forward *b)
563 if (!compare_host(a->listen_host, b->listen_host))
565 if (!compare_host(a->listen_path, b->listen_path))
567 if (a->listen_port != b->listen_port)
569 if (!compare_host(a->connect_host, b->connect_host))
571 if (!compare_host(a->connect_path, b->connect_path))
573 if (a->connect_port != b->connect_port)
580 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
582 struct mux_channel_confirm_ctx *fctx = ctxt;
583 char *failmsg = NULL;
584 struct Forward *rfwd;
588 if ((c = channel_by_id(fctx->cid)) == NULL) {
589 /* no channel for reply */
590 error("%s: unknown channel", __func__);
594 if (fctx->fid >= options.num_remote_forwards ||
595 (options.remote_forwards[fctx->fid].connect_path == NULL &&
596 options.remote_forwards[fctx->fid].connect_host == NULL)) {
597 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
600 rfwd = &options.remote_forwards[fctx->fid];
601 debug("%s: %s for: listen %d, connect %s:%d", __func__,
602 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
603 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
604 rfwd->connect_host, rfwd->connect_port);
605 if (type == SSH2_MSG_REQUEST_SUCCESS) {
606 if (rfwd->listen_port == 0) {
607 rfwd->allocated_port = packet_get_int();
608 debug("Allocated port %u for mux remote forward"
609 " to %s:%d", rfwd->allocated_port,
610 rfwd->connect_host, rfwd->connect_port);
611 buffer_put_int(&out, MUX_S_REMOTE_PORT);
612 buffer_put_int(&out, fctx->rid);
613 buffer_put_int(&out, rfwd->allocated_port);
614 channel_update_permitted_opens(rfwd->handle,
615 rfwd->allocated_port);
617 buffer_put_int(&out, MUX_S_OK);
618 buffer_put_int(&out, fctx->rid);
622 if (rfwd->listen_port == 0)
623 channel_update_permitted_opens(rfwd->handle, -1);
624 if (rfwd->listen_path != NULL)
625 xasprintf(&failmsg, "remote port forwarding failed for "
626 "listen path %s", rfwd->listen_path);
628 xasprintf(&failmsg, "remote port forwarding failed for "
629 "listen port %d", rfwd->listen_port);
631 debug2("%s: clearing registered forwarding for listen %d, "
632 "connect %s:%d", __func__, rfwd->listen_port,
633 rfwd->connect_path ? rfwd->connect_path :
634 rfwd->connect_host, rfwd->connect_port);
636 free(rfwd->listen_host);
637 free(rfwd->listen_path);
638 free(rfwd->connect_host);
639 free(rfwd->connect_path);
640 memset(rfwd, 0, sizeof(*rfwd));
643 error("%s: %s", __func__, failmsg);
644 buffer_put_int(&out, MUX_S_FAILURE);
645 buffer_put_int(&out, fctx->rid);
646 buffer_put_cstring(&out, failmsg);
649 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
651 if (c->mux_pause <= 0)
652 fatal("%s: mux_pause %d", __func__, c->mux_pause);
653 c->mux_pause = 0; /* start processing messages again */
657 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
660 char *fwd_desc = NULL;
661 char *listen_addr, *connect_addr;
664 int i, ret = 0, freefwd = 1;
666 memset(&fwd, 0, sizeof(fwd));
668 /* XXX - lport/cport check redundant */
669 if (buffer_get_int_ret(&ftype, m) != 0 ||
670 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
671 buffer_get_int_ret(&lport, m) != 0 ||
672 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
673 buffer_get_int_ret(&cport, m) != 0 ||
674 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
675 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
676 error("%s: malformed message", __func__);
680 if (*listen_addr == '\0') {
684 if (*connect_addr == '\0') {
689 memset(&fwd, 0, sizeof(fwd));
690 fwd.listen_port = lport;
691 if (fwd.listen_port == PORT_STREAMLOCAL)
692 fwd.listen_path = listen_addr;
694 fwd.listen_host = listen_addr;
695 fwd.connect_port = cport;
696 if (fwd.connect_port == PORT_STREAMLOCAL)
697 fwd.connect_path = connect_addr;
699 fwd.connect_host = connect_addr;
701 debug2("%s: channel %d: request %s", __func__, c->self,
702 (fwd_desc = format_forward(ftype, &fwd)));
704 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
705 ftype != MUX_FWD_DYNAMIC) {
706 logit("%s: invalid forwarding type %u", __func__, ftype);
710 buffer_put_int(r, MUX_S_FAILURE);
711 buffer_put_int(r, rid);
712 buffer_put_cstring(r, "Invalid forwarding request");
715 if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
716 logit("%s: streamlocal and dynamic forwards "
717 "are mutually exclusive", __func__);
720 if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
721 logit("%s: invalid listen port %u", __func__,
725 if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
726 || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
727 logit("%s: invalid connect port %u", __func__,
731 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
732 logit("%s: missing connect host", __func__);
736 /* Skip forwards that have already been requested */
739 case MUX_FWD_DYNAMIC:
740 for (i = 0; i < options.num_local_forwards; i++) {
741 if (compare_forward(&fwd,
742 options.local_forwards + i)) {
744 debug2("%s: found existing forwarding",
746 buffer_put_int(r, MUX_S_OK);
747 buffer_put_int(r, rid);
753 for (i = 0; i < options.num_remote_forwards; i++) {
754 if (compare_forward(&fwd,
755 options.remote_forwards + i)) {
756 if (fwd.listen_port != 0)
758 debug2("%s: found allocated port",
760 buffer_put_int(r, MUX_S_REMOTE_PORT);
761 buffer_put_int(r, rid);
763 options.remote_forwards[i].allocated_port);
770 if (options.control_master == SSHCTL_MASTER_ASK ||
771 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
772 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
773 debug2("%s: forwarding refused by user", __func__);
774 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
775 buffer_put_int(r, rid);
776 buffer_put_cstring(r, "Permission denied");
781 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
782 if (!channel_setup_local_fwd_listener(&fwd,
783 &options.fwd_opts)) {
785 logit("slave-requested %s failed", fwd_desc);
786 buffer_put_int(r, MUX_S_FAILURE);
787 buffer_put_int(r, rid);
788 buffer_put_cstring(r, "Port forwarding failed");
791 add_local_forward(&options, &fwd);
794 struct mux_channel_confirm_ctx *fctx;
796 fwd.handle = channel_request_remote_forwarding(&fwd);
799 add_remote_forward(&options, &fwd);
800 fctx = xcalloc(1, sizeof(*fctx));
803 fctx->fid = options.num_remote_forwards - 1;
804 client_register_global_confirm(mux_confirm_remote_forward,
807 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
808 /* delayed reply in mux_confirm_remote_forward */
811 buffer_put_int(r, MUX_S_OK);
812 buffer_put_int(r, rid);
816 free(fwd.listen_host);
817 free(fwd.listen_path);
818 free(fwd.connect_host);
819 free(fwd.connect_path);
825 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
827 struct Forward fwd, *found_fwd;
828 char *fwd_desc = NULL;
829 const char *error_reason = NULL;
830 char *listen_addr = NULL, *connect_addr = NULL;
835 memset(&fwd, 0, sizeof(fwd));
837 if (buffer_get_int_ret(&ftype, m) != 0 ||
838 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
839 buffer_get_int_ret(&lport, m) != 0 ||
840 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
841 buffer_get_int_ret(&cport, m) != 0 ||
842 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
843 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
844 error("%s: malformed message", __func__);
849 if (*listen_addr == '\0') {
853 if (*connect_addr == '\0') {
858 memset(&fwd, 0, sizeof(fwd));
859 fwd.listen_port = lport;
860 if (fwd.listen_port == PORT_STREAMLOCAL)
861 fwd.listen_path = listen_addr;
863 fwd.listen_host = listen_addr;
864 fwd.connect_port = cport;
865 if (fwd.connect_port == PORT_STREAMLOCAL)
866 fwd.connect_path = connect_addr;
868 fwd.connect_host = connect_addr;
870 debug2("%s: channel %d: request cancel %s", __func__, c->self,
871 (fwd_desc = format_forward(ftype, &fwd)));
873 /* make sure this has been requested */
877 case MUX_FWD_DYNAMIC:
878 for (i = 0; i < options.num_local_forwards; i++) {
879 if (compare_forward(&fwd,
880 options.local_forwards + i)) {
881 found_fwd = options.local_forwards + i;
887 for (i = 0; i < options.num_remote_forwards; i++) {
888 if (compare_forward(&fwd,
889 options.remote_forwards + i)) {
890 found_fwd = options.remote_forwards + i;
897 if (found_fwd == NULL)
898 error_reason = "port not forwarded";
899 else if (ftype == MUX_FWD_REMOTE) {
901 * This shouldn't fail unless we confused the host/port
902 * between options.remote_forwards and permitted_opens.
903 * However, for dynamic allocated listen ports we need
904 * to use the actual listen port.
906 if (channel_request_rforward_cancel(found_fwd) == -1)
907 error_reason = "port not in permitted opens";
908 } else { /* local and dynamic forwards */
910 if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
911 &options.fwd_opts) == -1)
912 error_reason = "port not found";
915 if (error_reason == NULL) {
916 buffer_put_int(r, MUX_S_OK);
917 buffer_put_int(r, rid);
919 free(found_fwd->listen_host);
920 free(found_fwd->listen_path);
921 free(found_fwd->connect_host);
922 free(found_fwd->connect_path);
923 found_fwd->listen_host = found_fwd->connect_host = NULL;
924 found_fwd->listen_path = found_fwd->connect_path = NULL;
925 found_fwd->listen_port = found_fwd->connect_port = 0;
927 buffer_put_int(r, MUX_S_FAILURE);
928 buffer_put_int(r, rid);
929 buffer_put_cstring(r, error_reason);
940 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
943 char *reserved, *chost;
946 struct mux_stdio_confirm_ctx *cctx;
948 chost = reserved = NULL;
949 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
950 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
951 buffer_get_int_ret(&cport, m) != 0) {
954 error("%s: malformed message", __func__);
959 debug2("%s: channel %d: request stdio fwd to %s:%u",
960 __func__, c->self, chost, cport);
962 /* Gather fds from client */
963 for(i = 0; i < 2; i++) {
964 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
965 error("%s: failed to receive fd %d from slave",
967 for (j = 0; j < i; j++)
972 buffer_put_int(r, MUX_S_FAILURE);
973 buffer_put_int(r, rid);
974 buffer_put_cstring(r,
975 "did not receive file descriptors");
980 debug3("%s: got fds stdin %d, stdout %d", __func__,
981 new_fd[0], new_fd[1]);
983 /* XXX support multiple child sessions in future */
984 if (c->remote_id != -1) {
985 debug2("%s: session already open", __func__);
987 buffer_put_int(r, MUX_S_FAILURE);
988 buffer_put_int(r, rid);
989 buffer_put_cstring(r, "Multiple sessions not supported");
997 if (options.control_master == SSHCTL_MASTER_ASK ||
998 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
999 if (!ask_permission("Allow forward to %s:%u? ",
1001 debug2("%s: stdio fwd refused by user", __func__);
1003 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1004 buffer_put_int(r, rid);
1005 buffer_put_cstring(r, "Permission denied");
1010 /* enable nonblocking unless tty */
1011 if (!isatty(new_fd[0]))
1012 set_nonblock(new_fd[0]);
1013 if (!isatty(new_fd[1]))
1014 set_nonblock(new_fd[1]);
1016 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1018 nc->ctl_chan = c->self; /* link session -> control channel */
1019 c->remote_id = nc->self; /* link control -> session channel */
1021 debug2("%s: channel_new: %d linked to control channel %d",
1022 __func__, nc->self, nc->ctl_chan);
1024 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1026 cctx = xcalloc(1, sizeof(*cctx));
1028 channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1029 c->mux_pause = 1; /* stop handling messages until open_confirm done */
1031 /* reply is deferred, sent by mux_session_confirm */
1035 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1037 mux_stdio_confirm(int id, int success, void *arg)
1039 struct mux_stdio_confirm_ctx *cctx = arg;
1044 fatal("%s: cctx == NULL", __func__);
1045 if ((c = channel_by_id(id)) == NULL)
1046 fatal("%s: no channel for id %d", __func__, id);
1047 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1048 fatal("%s: channel %d lacks control channel %d", __func__,
1052 debug3("%s: sending failure reply", __func__);
1054 buffer_init(&reply);
1055 buffer_put_int(&reply, MUX_S_FAILURE);
1056 buffer_put_int(&reply, cctx->rid);
1057 buffer_put_cstring(&reply, "Session open refused by peer");
1061 debug3("%s: sending success reply", __func__);
1063 buffer_init(&reply);
1064 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1065 buffer_put_int(&reply, cctx->rid);
1066 buffer_put_int(&reply, c->self);
1070 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1071 buffer_free(&reply);
1073 if (cc->mux_pause <= 0)
1074 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1075 cc->mux_pause = 0; /* start processing messages again */
1076 c->open_confirm_ctx = NULL;
1081 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1083 debug("%s: channel %d: stop listening", __func__, c->self);
1085 if (options.control_master == SSHCTL_MASTER_ASK ||
1086 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1087 if (!ask_permission("Disable further multiplexing on shared "
1088 "connection to %s? ", host)) {
1089 debug2("%s: stop listen refused by user", __func__);
1090 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1091 buffer_put_int(r, rid);
1092 buffer_put_cstring(r, "Permission denied");
1097 if (mux_listener_channel != NULL) {
1098 channel_free(mux_listener_channel);
1100 free(options.control_path);
1101 options.control_path = NULL;
1102 mux_listener_channel = NULL;
1103 muxserver_sock = -1;
1107 buffer_put_int(r, MUX_S_OK);
1108 buffer_put_int(r, rid);
1113 /* Channel callbacks fired on read/write from mux slave fd */
1115 mux_master_read_cb(Channel *c)
1117 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1120 u_int type, rid, have, i;
1124 if (c->mux_ctx == NULL) {
1125 state = xcalloc(1, sizeof(*state));
1127 channel_register_cleanup(c->self,
1128 mux_master_control_cleanup_cb, 0);
1132 buffer_put_int(&out, MUX_MSG_HELLO);
1133 buffer_put_int(&out, SSHMUX_VER);
1135 buffer_put_string(&c->output, buffer_ptr(&out),
1138 debug3("%s: channel %d: hello sent", __func__, c->self);
1145 /* Channel code ensures that we receive whole packets */
1146 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1148 error("%s: malformed message", __func__);
1151 buffer_append(&in, ptr, have);
1153 if (buffer_get_int_ret(&type, &in) != 0)
1155 debug3("%s: channel %d packet type 0x%08x len %u",
1156 __func__, c->self, type, buffer_len(&in));
1158 if (type == MUX_MSG_HELLO)
1161 if (!state->hello_rcvd) {
1162 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1163 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1166 if (buffer_get_int_ret(&rid, &in) != 0)
1170 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1171 if (type == mux_master_handlers[i].type) {
1172 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1176 if (mux_master_handlers[i].handler == NULL) {
1177 error("%s: unsupported mux message 0x%08x", __func__, type);
1178 buffer_put_int(&out, MUX_S_FAILURE);
1179 buffer_put_int(&out, rid);
1180 buffer_put_cstring(&out, "unsupported request");
1183 /* Enqueue reply packet */
1184 if (buffer_len(&out) != 0) {
1185 buffer_put_string(&c->output, buffer_ptr(&out),
1195 mux_exit_message(Channel *c, int exitval)
1200 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1203 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1204 fatal("%s: channel %d missing mux channel %d",
1205 __func__, c->self, c->ctl_chan);
1207 /* Append exit message packet to control socket output queue */
1209 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1210 buffer_put_int(&m, c->self);
1211 buffer_put_int(&m, exitval);
1213 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1218 mux_tty_alloc_failed(Channel *c)
1223 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1225 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1226 fatal("%s: channel %d missing mux channel %d",
1227 __func__, c->self, c->ctl_chan);
1229 /* Append exit message packet to control socket output queue */
1231 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1232 buffer_put_int(&m, c->self);
1234 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1238 /* Prepare a mux master to listen on a Unix domain socket. */
1240 muxserver_listen(void)
1243 char *orig_control_path = options.control_path;
1248 if (options.control_path == NULL ||
1249 options.control_master == SSHCTL_MASTER_NO)
1252 debug("setting up multiplex master socket");
1255 * Use a temporary path before listen so we can pseudo-atomically
1256 * establish the listening socket in its final location to avoid
1257 * other processes racing in between bind() and listen() and hitting
1258 * an unready socket.
1260 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1261 r = arc4random_uniform(26+26+10);
1262 rbuf[i] = (r < 26) ? 'a' + r :
1263 (r < 26*2) ? 'A' + r - 26 :
1266 rbuf[sizeof(rbuf) - 1] = '\0';
1267 options.control_path = NULL;
1268 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1269 debug3("%s: temporary control path %s", __func__, options.control_path);
1271 old_umask = umask(0177);
1272 muxserver_sock = unix_listener(options.control_path, 64, 0);
1275 if (muxserver_sock < 0) {
1276 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1277 error("ControlSocket %s already exists, "
1278 "disabling multiplexing", options.control_path);
1280 if (muxserver_sock != -1) {
1281 close(muxserver_sock);
1282 muxserver_sock = -1;
1284 free(orig_control_path);
1285 free(options.control_path);
1286 options.control_path = NULL;
1287 options.control_master = SSHCTL_MASTER_NO;
1290 /* unix_listener() logs the error */
1295 /* Now atomically "move" the mux socket into position */
1296 if (link(options.control_path, orig_control_path) != 0) {
1297 if (errno != EEXIST) {
1298 fatal("%s: link mux listener %s => %s: %s", __func__,
1299 options.control_path, orig_control_path,
1302 error("ControlSocket %s already exists, disabling multiplexing",
1304 unlink(options.control_path);
1305 goto disable_mux_master;
1307 unlink(options.control_path);
1308 free(options.control_path);
1309 options.control_path = orig_control_path;
1311 set_nonblock(muxserver_sock);
1313 mux_listener_channel = channel_new("mux listener",
1314 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1315 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1316 0, options.control_path, 1);
1317 mux_listener_channel->mux_rcb = mux_master_read_cb;
1318 debug3("%s: mux listener channel %d fd %d", __func__,
1319 mux_listener_channel->self, mux_listener_channel->sock);
1322 /* Callback on open confirmation in mux master for a mux client session. */
1324 mux_session_confirm(int id, int success, void *arg)
1326 struct mux_session_confirm_ctx *cctx = arg;
1327 const char *display;
1333 fatal("%s: cctx == NULL", __func__);
1334 if ((c = channel_by_id(id)) == NULL)
1335 fatal("%s: no channel for id %d", __func__, id);
1336 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1337 fatal("%s: channel %d lacks control channel %d", __func__,
1341 debug3("%s: sending failure reply", __func__);
1343 buffer_init(&reply);
1344 buffer_put_int(&reply, MUX_S_FAILURE);
1345 buffer_put_int(&reply, cctx->rid);
1346 buffer_put_cstring(&reply, "Session open refused by peer");
1350 display = getenv("DISPLAY");
1351 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1354 /* Get reasonable local authentication information. */
1355 if (client_x11_get_proto(display, options.xauth_location,
1356 options.forward_x11_trusted, options.forward_x11_timeout,
1357 &proto, &data) == 0) {
1358 /* Request forwarding with authentication spoofing. */
1359 debug("Requesting X11 forwarding with authentication "
1361 x11_request_forwarding_with_spoofing(id, display, proto,
1363 /* XXX exit_on_forward_failure */
1364 client_expect_confirm(id, "X11 forwarding",
1369 if (cctx->want_agent_fwd && options.forward_agent) {
1370 debug("Requesting authentication agent forwarding.");
1371 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1375 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1376 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1378 debug3("%s: sending success reply", __func__);
1380 buffer_init(&reply);
1381 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1382 buffer_put_int(&reply, cctx->rid);
1383 buffer_put_int(&reply, c->self);
1387 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1388 buffer_free(&reply);
1390 if (cc->mux_pause <= 0)
1391 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1392 cc->mux_pause = 0; /* start processing messages again */
1393 c->open_confirm_ctx = NULL;
1394 buffer_free(&cctx->cmd);
1396 if (cctx->env != NULL) {
1397 for (i = 0; cctx->env[i] != NULL; i++)
1404 /* ** Multiplexing client support */
1406 /* Exit signal handler */
1408 control_client_sighandler(int signo)
1410 muxclient_terminate = signo;
1414 * Relay signal handler - used to pass some signals from mux client to
1418 control_client_sigrelay(int signo)
1420 int save_errno = errno;
1422 if (muxserver_pid > 1)
1423 kill(muxserver_pid, signo);
1429 mux_client_read(int fd, Buffer *b, u_int need)
1437 pfd.events = POLLIN;
1438 p = buffer_append_space(b, need);
1439 for (have = 0; have < need; ) {
1440 if (muxclient_terminate) {
1444 len = read(fd, p + have, need - have);
1447 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1451 (void)poll(&pfd, 1, -1);
1469 mux_client_write_packet(int fd, Buffer *m)
1478 pfd.events = POLLOUT;
1479 buffer_init(&queue);
1480 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1482 need = buffer_len(&queue);
1483 ptr = buffer_ptr(&queue);
1485 for (have = 0; have < need; ) {
1486 if (muxclient_terminate) {
1487 buffer_free(&queue);
1491 len = write(fd, ptr + have, need - have);
1494 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1498 (void)poll(&pfd, 1, -1);
1504 buffer_free(&queue);
1510 buffer_free(&queue);
1516 buffer_free(&queue);
1521 mux_client_read_packet(int fd, Buffer *m)
1528 buffer_init(&queue);
1529 if (mux_client_read(fd, &queue, 4) != 0) {
1530 if ((oerrno = errno) == EPIPE)
1531 debug3("%s: read header failed: %s", __func__,
1533 buffer_free(&queue);
1537 need = get_u32(buffer_ptr(&queue));
1538 if (mux_client_read(fd, &queue, need) != 0) {
1540 debug3("%s: read body failed: %s", __func__, strerror(errno));
1541 buffer_free(&queue);
1545 ptr = buffer_get_string_ptr(&queue, &have);
1546 buffer_append(m, ptr, have);
1547 buffer_free(&queue);
1552 mux_client_hello_exchange(int fd)
1558 buffer_put_int(&m, MUX_MSG_HELLO);
1559 buffer_put_int(&m, SSHMUX_VER);
1562 if (mux_client_write_packet(fd, &m) != 0)
1563 fatal("%s: write packet: %s", __func__, strerror(errno));
1567 /* Read their HELLO */
1568 if (mux_client_read_packet(fd, &m) != 0) {
1573 type = buffer_get_int(&m);
1574 if (type != MUX_MSG_HELLO)
1575 fatal("%s: expected HELLO (%u) received %u",
1576 __func__, MUX_MSG_HELLO, type);
1577 ver = buffer_get_int(&m);
1578 if (ver != SSHMUX_VER)
1579 fatal("Unsupported multiplexing protocol version %d "
1580 "(expected %d)", ver, SSHMUX_VER);
1581 debug2("%s: master version %u", __func__, ver);
1582 /* No extensions are presently defined */
1583 while (buffer_len(&m) > 0) {
1584 char *name = buffer_get_string(&m, NULL);
1585 char *value = buffer_get_string(&m, NULL);
1587 debug2("Unrecognised master extension \"%s\"", name);
1596 mux_client_request_alive(int fd)
1600 u_int pid, type, rid;
1602 debug3("%s: entering", __func__);
1605 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1606 buffer_put_int(&m, muxclient_request_id);
1608 if (mux_client_write_packet(fd, &m) != 0)
1609 fatal("%s: write packet: %s", __func__, strerror(errno));
1613 /* Read their reply */
1614 if (mux_client_read_packet(fd, &m) != 0) {
1619 type = buffer_get_int(&m);
1620 if (type != MUX_S_ALIVE) {
1621 e = buffer_get_string(&m, NULL);
1622 fatal("%s: master returned error: %s", __func__, e);
1625 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1626 fatal("%s: out of sequence reply: my id %u theirs %u",
1627 __func__, muxclient_request_id, rid);
1628 pid = buffer_get_int(&m);
1631 debug3("%s: done pid = %u", __func__, pid);
1633 muxclient_request_id++;
1639 mux_client_request_terminate(int fd)
1645 debug3("%s: entering", __func__);
1648 buffer_put_int(&m, MUX_C_TERMINATE);
1649 buffer_put_int(&m, muxclient_request_id);
1651 if (mux_client_write_packet(fd, &m) != 0)
1652 fatal("%s: write packet: %s", __func__, strerror(errno));
1656 /* Read their reply */
1657 if (mux_client_read_packet(fd, &m) != 0) {
1658 /* Remote end exited already */
1659 if (errno == EPIPE) {
1663 fatal("%s: read from master failed: %s",
1664 __func__, strerror(errno));
1667 type = buffer_get_int(&m);
1668 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1669 fatal("%s: out of sequence reply: my id %u theirs %u",
1670 __func__, muxclient_request_id, rid);
1674 case MUX_S_PERMISSION_DENIED:
1675 e = buffer_get_string(&m, NULL);
1676 fatal("Master refused termination request: %s", e);
1678 e = buffer_get_string(&m, NULL);
1679 fatal("%s: termination request failed: %s", __func__, e);
1681 fatal("%s: unexpected response from master 0x%08x",
1685 muxclient_request_id++;
1689 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1695 fwd_desc = format_forward(ftype, fwd);
1696 debug("Requesting %s %s",
1697 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1701 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1702 buffer_put_int(&m, muxclient_request_id);
1703 buffer_put_int(&m, ftype);
1704 if (fwd->listen_path != NULL) {
1705 buffer_put_cstring(&m, fwd->listen_path);
1707 buffer_put_cstring(&m,
1708 fwd->listen_host == NULL ? "" :
1709 (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1711 buffer_put_int(&m, fwd->listen_port);
1712 if (fwd->connect_path != NULL) {
1713 buffer_put_cstring(&m, fwd->connect_path);
1715 buffer_put_cstring(&m,
1716 fwd->connect_host == NULL ? "" : fwd->connect_host);
1718 buffer_put_int(&m, fwd->connect_port);
1720 if (mux_client_write_packet(fd, &m) != 0)
1721 fatal("%s: write packet: %s", __func__, strerror(errno));
1725 /* Read their reply */
1726 if (mux_client_read_packet(fd, &m) != 0) {
1731 type = buffer_get_int(&m);
1732 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1733 fatal("%s: out of sequence reply: my id %u theirs %u",
1734 __func__, muxclient_request_id, rid);
1738 case MUX_S_REMOTE_PORT:
1740 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1741 fwd->allocated_port = buffer_get_int(&m);
1742 verbose("Allocated port %u for remote forward to %s:%d",
1743 fwd->allocated_port,
1744 fwd->connect_host ? fwd->connect_host : "",
1746 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1747 fprintf(stdout, "%i\n", fwd->allocated_port);
1749 case MUX_S_PERMISSION_DENIED:
1750 e = buffer_get_string(&m, NULL);
1752 error("Master refused forwarding request: %s", e);
1755 e = buffer_get_string(&m, NULL);
1757 error("%s: forwarding request failed: %s", __func__, e);
1760 fatal("%s: unexpected response from master 0x%08x",
1765 muxclient_request_id++;
1770 mux_client_forwards(int fd, int cancel_flag)
1774 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1775 cancel_flag ? "cancel" : "request",
1776 options.num_local_forwards, options.num_remote_forwards);
1778 /* XXX ExitOnForwardingFailure */
1779 for (i = 0; i < options.num_local_forwards; i++) {
1780 if (mux_client_forward(fd, cancel_flag,
1781 options.local_forwards[i].connect_port == 0 ?
1782 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1783 options.local_forwards + i) != 0)
1786 for (i = 0; i < options.num_remote_forwards; i++) {
1787 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1788 options.remote_forwards + i) != 0)
1795 mux_client_request_session(int fd)
1799 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1800 extern char **environ;
1801 int devnull, rawmode;
1803 debug3("%s: entering", __func__);
1805 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1806 error("%s: master alive request failed", __func__);
1810 signal(SIGPIPE, SIG_IGN);
1812 if (stdin_null_flag) {
1813 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1814 fatal("open(/dev/null): %s", strerror(errno));
1815 if (dup2(devnull, STDIN_FILENO) == -1)
1816 fatal("dup2: %s", strerror(errno));
1817 if (devnull > STDERR_FILENO)
1821 term = getenv("TERM");
1824 buffer_put_int(&m, MUX_C_NEW_SESSION);
1825 buffer_put_int(&m, muxclient_request_id);
1826 buffer_put_cstring(&m, ""); /* reserved */
1827 buffer_put_int(&m, tty_flag);
1828 buffer_put_int(&m, options.forward_x11);
1829 buffer_put_int(&m, options.forward_agent);
1830 buffer_put_int(&m, subsystem_flag);
1831 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1832 0xffffffff : (u_int)options.escape_char);
1833 buffer_put_cstring(&m, term == NULL ? "" : term);
1834 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1836 if (options.num_send_env > 0 && environ != NULL) {
1837 /* Pass environment */
1838 for (i = 0; environ[i] != NULL; i++) {
1839 if (env_permitted(environ[i])) {
1840 buffer_put_cstring(&m, environ[i]);
1845 if (mux_client_write_packet(fd, &m) != 0)
1846 fatal("%s: write packet: %s", __func__, strerror(errno));
1848 /* Send the stdio file descriptors */
1849 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1850 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1851 mm_send_fd(fd, STDERR_FILENO) == -1)
1852 fatal("%s: send fds failed", __func__);
1854 debug3("%s: session request sent", __func__);
1856 /* Read their reply */
1858 if (mux_client_read_packet(fd, &m) != 0) {
1859 error("%s: read from master failed: %s",
1860 __func__, strerror(errno));
1865 type = buffer_get_int(&m);
1866 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1867 fatal("%s: out of sequence reply: my id %u theirs %u",
1868 __func__, muxclient_request_id, rid);
1870 case MUX_S_SESSION_OPENED:
1871 sid = buffer_get_int(&m);
1872 debug("%s: master session id: %u", __func__, sid);
1874 case MUX_S_PERMISSION_DENIED:
1875 e = buffer_get_string(&m, NULL);
1877 error("Master refused session request: %s", e);
1880 e = buffer_get_string(&m, NULL);
1882 error("%s: session request failed: %s", __func__, e);
1886 error("%s: unexpected response from master 0x%08x",
1890 muxclient_request_id++;
1892 if (pledge("stdio proc tty", NULL) == -1)
1893 fatal("%s pledge(): %s", __func__, strerror(errno));
1894 platform_pledge_mux();
1896 signal(SIGHUP, control_client_sighandler);
1897 signal(SIGINT, control_client_sighandler);
1898 signal(SIGTERM, control_client_sighandler);
1899 signal(SIGWINCH, control_client_sigrelay);
1903 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1906 * Stick around until the controlee closes the client_fd.
1907 * Before it does, it is expected to write an exit message.
1908 * This process must read the value and wait for the closure of
1909 * the client_fd; if this one closes early, the multiplex master will
1910 * terminate early too (possibly losing data).
1912 for (exitval = 255, exitval_seen = 0;;) {
1914 if (mux_client_read_packet(fd, &m) != 0)
1916 type = buffer_get_int(&m);
1918 case MUX_S_TTY_ALLOC_FAIL:
1919 if ((esid = buffer_get_int(&m)) != sid)
1920 fatal("%s: tty alloc fail on unknown session: "
1921 "my id %u theirs %u",
1922 __func__, sid, esid);
1923 leave_raw_mode(options.request_tty ==
1927 case MUX_S_EXIT_MESSAGE:
1928 if ((esid = buffer_get_int(&m)) != sid)
1929 fatal("%s: exit on unknown session: "
1930 "my id %u theirs %u",
1931 __func__, sid, esid);
1933 fatal("%s: exitval sent twice", __func__);
1934 exitval = buffer_get_int(&m);
1938 e = buffer_get_string(&m, NULL);
1939 fatal("%s: master returned error: %s", __func__, e);
1945 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1947 if (muxclient_terminate) {
1948 debug2("Exiting on signal %d", muxclient_terminate);
1950 } else if (!exitval_seen) {
1951 debug2("Control master terminated unexpectedly");
1954 debug2("Received exit status from master %d", exitval);
1956 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1957 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1963 mux_client_request_stdio_fwd(int fd)
1967 u_int type, rid, sid;
1970 debug3("%s: entering", __func__);
1972 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1973 error("%s: master alive request failed", __func__);
1977 signal(SIGPIPE, SIG_IGN);
1979 if (stdin_null_flag) {
1980 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1981 fatal("open(/dev/null): %s", strerror(errno));
1982 if (dup2(devnull, STDIN_FILENO) == -1)
1983 fatal("dup2: %s", strerror(errno));
1984 if (devnull > STDERR_FILENO)
1989 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1990 buffer_put_int(&m, muxclient_request_id);
1991 buffer_put_cstring(&m, ""); /* reserved */
1992 buffer_put_cstring(&m, options.stdio_forward_host);
1993 buffer_put_int(&m, options.stdio_forward_port);
1995 if (mux_client_write_packet(fd, &m) != 0)
1996 fatal("%s: write packet: %s", __func__, strerror(errno));
1998 /* Send the stdio file descriptors */
1999 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
2000 mm_send_fd(fd, STDOUT_FILENO) == -1)
2001 fatal("%s: send fds failed", __func__);
2003 if (pledge("stdio proc tty", NULL) == -1)
2004 fatal("%s pledge(): %s", __func__, strerror(errno));
2005 platform_pledge_mux();
2007 debug3("%s: stdio forward request sent", __func__);
2009 /* Read their reply */
2012 if (mux_client_read_packet(fd, &m) != 0) {
2013 error("%s: read from master failed: %s",
2014 __func__, strerror(errno));
2019 type = buffer_get_int(&m);
2020 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2021 fatal("%s: out of sequence reply: my id %u theirs %u",
2022 __func__, muxclient_request_id, rid);
2024 case MUX_S_SESSION_OPENED:
2025 sid = buffer_get_int(&m);
2026 debug("%s: master session id: %u", __func__, sid);
2028 case MUX_S_PERMISSION_DENIED:
2029 e = buffer_get_string(&m, NULL);
2031 fatal("Master refused stdio forwarding request: %s", e);
2033 e = buffer_get_string(&m, NULL);
2035 fatal("Stdio forwarding request failed: %s", e);
2038 error("%s: unexpected response from master 0x%08x",
2042 muxclient_request_id++;
2044 signal(SIGHUP, control_client_sighandler);
2045 signal(SIGINT, control_client_sighandler);
2046 signal(SIGTERM, control_client_sighandler);
2047 signal(SIGWINCH, control_client_sigrelay);
2050 * Stick around until the controlee closes the client_fd.
2053 if (mux_client_read_packet(fd, &m) != 0) {
2054 if (errno == EPIPE ||
2055 (errno == EINTR && muxclient_terminate != 0))
2057 fatal("%s: mux_client_read_packet: %s",
2058 __func__, strerror(errno));
2060 fatal("%s: master returned unexpected message %u", __func__, type);
2064 mux_client_request_stop_listening(int fd)
2070 debug3("%s: entering", __func__);
2073 buffer_put_int(&m, MUX_C_STOP_LISTENING);
2074 buffer_put_int(&m, muxclient_request_id);
2076 if (mux_client_write_packet(fd, &m) != 0)
2077 fatal("%s: write packet: %s", __func__, strerror(errno));
2081 /* Read their reply */
2082 if (mux_client_read_packet(fd, &m) != 0)
2083 fatal("%s: read from master failed: %s",
2084 __func__, strerror(errno));
2086 type = buffer_get_int(&m);
2087 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2088 fatal("%s: out of sequence reply: my id %u theirs %u",
2089 __func__, muxclient_request_id, rid);
2093 case MUX_S_PERMISSION_DENIED:
2094 e = buffer_get_string(&m, NULL);
2095 fatal("Master refused stop listening request: %s", e);
2097 e = buffer_get_string(&m, NULL);
2098 fatal("%s: stop listening request failed: %s", __func__, e);
2100 fatal("%s: unexpected response from master 0x%08x",
2104 muxclient_request_id++;
2107 /* Multiplex client main loop. */
2109 muxclient(const char *path)
2111 struct sockaddr_un addr;
2116 if (muxclient_command == 0) {
2117 if (options.stdio_forward_host != NULL)
2118 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2120 muxclient_command = SSHMUX_COMMAND_OPEN;
2123 switch (options.control_master) {
2124 case SSHCTL_MASTER_AUTO:
2125 case SSHCTL_MASTER_AUTO_ASK:
2126 debug("auto-mux: Trying existing master");
2128 case SSHCTL_MASTER_NO:
2134 memset(&addr, '\0', sizeof(addr));
2135 addr.sun_family = AF_UNIX;
2136 sun_len = offsetof(struct sockaddr_un, sun_path) +
2139 if (strlcpy(addr.sun_path, path,
2140 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2141 fatal("ControlPath too long");
2143 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2144 fatal("%s socket(): %s", __func__, strerror(errno));
2146 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2147 switch (muxclient_command) {
2148 case SSHMUX_COMMAND_OPEN:
2149 case SSHMUX_COMMAND_STDIO_FWD:
2152 fatal("Control socket connect(%.100s): %s", path,
2155 if (errno == ECONNREFUSED &&
2156 options.control_master != SSHCTL_MASTER_NO) {
2157 debug("Stale control socket %.100s, unlinking", path);
2159 } else if (errno == ENOENT) {
2160 debug("Control socket \"%.100s\" does not exist", path);
2162 error("Control socket connect(%.100s): %s", path,
2170 if (mux_client_hello_exchange(sock) != 0) {
2171 error("%s: master hello exchange failed", __func__);
2176 switch (muxclient_command) {
2177 case SSHMUX_COMMAND_ALIVE_CHECK:
2178 if ((pid = mux_client_request_alive(sock)) == 0)
2179 fatal("%s: master alive check failed", __func__);
2180 fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2182 case SSHMUX_COMMAND_TERMINATE:
2183 mux_client_request_terminate(sock);
2184 fprintf(stderr, "Exit request sent.\r\n");
2186 case SSHMUX_COMMAND_FORWARD:
2187 if (mux_client_forwards(sock, 0) != 0)
2188 fatal("%s: master forward request failed", __func__);
2190 case SSHMUX_COMMAND_OPEN:
2191 if (mux_client_forwards(sock, 0) != 0) {
2192 error("%s: master forward request failed", __func__);
2195 mux_client_request_session(sock);
2197 case SSHMUX_COMMAND_STDIO_FWD:
2198 mux_client_request_stdio_fwd(sock);
2200 case SSHMUX_COMMAND_STOP:
2201 mux_client_request_stop_listening(sock);
2202 fprintf(stderr, "Stop listening request sent.\r\n");
2204 case SSHMUX_COMMAND_CANCEL_FWD:
2205 if (mux_client_forwards(sock, 1) != 0)
2206 error("%s: master cancel forward request failed",
2210 fatal("unrecognised muxclient_command %d", muxclient_command);