1 /* $OpenBSD: mux.c,v 1.64 2017/01/21 11:32:04 guenther 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
36 #include <sys/types.h>
38 #include <sys/socket.h>
57 # ifdef HAVE_SYS_POLL_H
58 # include <sys/poll.h>
66 #include "openbsd-compat/sys-queue.h"
71 #include "pathnames.h"
78 #include "monitor_fdpass.h"
82 #include "clientloop.h"
87 extern Options options;
88 extern int stdin_null_flag;
90 extern int subsystem_flag;
91 extern Buffer command;
92 extern volatile sig_atomic_t quit_pending;
94 /* Context for session open confirmation callback */
95 struct mux_session_confirm_ctx {
107 /* Context for stdio fwd open confirmation callback */
108 struct mux_stdio_confirm_ctx {
112 /* Context for global channel callback */
113 struct mux_channel_confirm_ctx {
114 u_int cid; /* channel id */
115 u_int rid; /* request id */
116 int fid; /* forward id */
119 /* fd to control socket */
120 int muxserver_sock = -1;
122 /* client request id */
123 u_int muxclient_request_id = 0;
125 /* Multiplexing control command */
126 u_int muxclient_command = 0;
128 /* Set when signalled. */
129 static volatile sig_atomic_t muxclient_terminate = 0;
131 /* PID of multiplex server */
132 static u_int muxserver_pid = 0;
134 static Channel *mux_listener_channel = NULL;
136 struct mux_master_state {
140 /* mux protocol messages */
141 #define MUX_MSG_HELLO 0x00000001
142 #define MUX_C_NEW_SESSION 0x10000002
143 #define MUX_C_ALIVE_CHECK 0x10000004
144 #define MUX_C_TERMINATE 0x10000005
145 #define MUX_C_OPEN_FWD 0x10000006
146 #define MUX_C_CLOSE_FWD 0x10000007
147 #define MUX_C_NEW_STDIO_FWD 0x10000008
148 #define MUX_C_STOP_LISTENING 0x10000009
149 #define MUX_C_PROXY 0x1000000f
150 #define MUX_S_OK 0x80000001
151 #define MUX_S_PERMISSION_DENIED 0x80000002
152 #define MUX_S_FAILURE 0x80000003
153 #define MUX_S_EXIT_MESSAGE 0x80000004
154 #define MUX_S_ALIVE 0x80000005
155 #define MUX_S_SESSION_OPENED 0x80000006
156 #define MUX_S_REMOTE_PORT 0x80000007
157 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
158 #define MUX_S_PROXY 0x8000000f
160 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
161 #define MUX_FWD_LOCAL 1
162 #define MUX_FWD_REMOTE 2
163 #define MUX_FWD_DYNAMIC 3
165 static void mux_session_confirm(int, int, void *);
166 static void mux_stdio_confirm(int, int, void *);
168 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
173 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
174 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
175 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
176 static int process_mux_proxy(u_int, Channel *, Buffer *, Buffer *);
178 static const struct {
180 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
181 } mux_master_handlers[] = {
182 { MUX_MSG_HELLO, process_mux_master_hello },
183 { MUX_C_NEW_SESSION, process_mux_new_session },
184 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
185 { MUX_C_TERMINATE, process_mux_terminate },
186 { MUX_C_OPEN_FWD, process_mux_open_fwd },
187 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
188 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
189 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
190 { MUX_C_PROXY, process_mux_proxy },
194 /* Cleanup callback fired on closure of mux slave _session_ channel */
197 mux_master_session_cleanup_cb(int cid, void *unused)
199 Channel *cc, *c = channel_by_id(cid);
201 debug3("%s: entering for channel %d", __func__, cid);
203 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
204 if (c->ctl_chan != -1) {
205 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
206 fatal("%s: channel %d missing control channel %d",
207 __func__, c->self, c->ctl_chan);
210 chan_rcvd_oclose(cc);
212 channel_cancel_cleanup(c->self);
215 /* Cleanup callback fired on closure of mux slave _control_ channel */
218 mux_master_control_cleanup_cb(int cid, void *unused)
220 Channel *sc, *c = channel_by_id(cid);
222 debug3("%s: entering for channel %d", __func__, cid);
224 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
225 if (c->remote_id != -1) {
226 if ((sc = channel_by_id(c->remote_id)) == NULL)
227 fatal("%s: channel %d missing session channel %d",
228 __func__, c->self, c->remote_id);
231 if (sc->type != SSH_CHANNEL_OPEN &&
232 sc->type != SSH_CHANNEL_OPENING) {
233 debug2("%s: channel %d: not open", __func__, sc->self);
236 if (sc->istate == CHAN_INPUT_OPEN)
237 chan_read_failed(sc);
238 if (sc->ostate == CHAN_OUTPUT_OPEN)
239 chan_write_failed(sc);
242 channel_cancel_cleanup(c->self);
245 /* Check mux client environment variables before passing them to mux master. */
247 env_permitted(char *env)
250 char name[1024], *cp;
252 if ((cp = strchr(env, '=')) == NULL || cp == env)
254 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
255 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
256 error("env_permitted: name '%.100s...' too long", env);
260 for (i = 0; i < options.num_send_env; i++)
261 if (match_pattern(name, options.send_env[i]))
267 /* Mux master protocol message handlers */
270 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
273 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
276 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
277 if (state->hello_rcvd) {
278 error("%s: HELLO received twice", __func__);
281 if (buffer_get_int_ret(&ver, m) != 0) {
283 error("%s: malformed message", __func__);
286 if (ver != SSHMUX_VER) {
287 error("Unsupported multiplexing protocol version %d "
288 "(expected %d)", ver, SSHMUX_VER);
291 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
293 /* No extensions are presently defined */
294 while (buffer_len(m) > 0) {
295 char *name = buffer_get_string_ret(m, NULL);
296 char *value = buffer_get_string_ret(m, NULL);
298 if (name == NULL || value == NULL) {
303 debug2("Unrecognised slave extension \"%s\"", name);
307 state->hello_rcvd = 1;
312 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
315 struct mux_session_confirm_ctx *cctx;
316 char *reserved, *cmd, *cp;
317 u_int i, j, len, env_len, escape_char, window, packetmax;
320 /* Reply for SSHMUX_COMMAND_OPEN */
321 cctx = xcalloc(1, sizeof(*cctx));
324 cmd = reserved = NULL;
327 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
328 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
329 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
330 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
331 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
332 buffer_get_int_ret(&escape_char, m) != 0 ||
333 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
334 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
338 for (j = 0; j < env_len; j++)
343 error("%s: malformed message", __func__);
349 while (buffer_len(m) > 0) {
350 #define MUX_MAX_ENV_VARS 4096
351 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
353 if (!env_permitted(cp)) {
357 cctx->env = xreallocarray(cctx->env, env_len + 2,
359 cctx->env[env_len++] = cp;
360 cctx->env[env_len] = NULL;
361 if (env_len > MUX_MAX_ENV_VARS) {
362 error(">%d environment variables received, ignoring "
363 "additional", MUX_MAX_ENV_VARS);
368 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
369 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
370 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
371 cctx->want_subsys, cctx->term, cmd, env_len);
373 buffer_init(&cctx->cmd);
374 buffer_append(&cctx->cmd, cmd, strlen(cmd));
378 /* Gather fds from client */
379 for(i = 0; i < 3; i++) {
380 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
381 error("%s: failed to receive fd %d from slave",
383 for (j = 0; j < i; j++)
385 for (j = 0; j < env_len; j++)
389 buffer_free(&cctx->cmd);
393 buffer_put_int(r, MUX_S_FAILURE);
394 buffer_put_int(r, rid);
395 buffer_put_cstring(r,
396 "did not receive file descriptors");
401 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
402 new_fd[0], new_fd[1], new_fd[2]);
404 /* XXX support multiple child sessions in future */
405 if (c->remote_id != -1) {
406 debug2("%s: session already open", __func__);
408 buffer_put_int(r, MUX_S_FAILURE);
409 buffer_put_int(r, rid);
410 buffer_put_cstring(r, "Multiple sessions not supported");
417 for (i = 0; i < env_len; i++)
421 buffer_free(&cctx->cmd);
426 if (options.control_master == SSHCTL_MASTER_ASK ||
427 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
428 if (!ask_permission("Allow shared connection to %s? ", host)) {
429 debug2("%s: session refused by user", __func__);
431 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
432 buffer_put_int(r, rid);
433 buffer_put_cstring(r, "Permission denied");
438 /* Try to pick up ttymodes from client before it goes raw */
439 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
440 error("%s: tcgetattr: %s", __func__, strerror(errno));
442 /* enable nonblocking unless tty */
443 if (!isatty(new_fd[0]))
444 set_nonblock(new_fd[0]);
445 if (!isatty(new_fd[1]))
446 set_nonblock(new_fd[1]);
447 if (!isatty(new_fd[2]))
448 set_nonblock(new_fd[2]);
450 window = CHAN_SES_WINDOW_DEFAULT;
451 packetmax = CHAN_SES_PACKET_DEFAULT;
452 if (cctx->want_tty) {
457 nc = channel_new("session", SSH_CHANNEL_OPENING,
458 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
459 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
461 nc->ctl_chan = c->self; /* link session -> control channel */
462 c->remote_id = nc->self; /* link control -> session channel */
464 if (cctx->want_tty && escape_char != 0xffffffff) {
465 channel_register_filter(nc->self,
466 client_simple_escape_filter, NULL,
467 client_filter_cleanup,
468 client_new_escape_filter_ctx((int)escape_char));
471 debug2("%s: channel_new: %d linked to control channel %d",
472 __func__, nc->self, nc->ctl_chan);
474 channel_send_open(nc->self);
475 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
476 c->mux_pause = 1; /* stop handling messages until open_confirm done */
477 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
479 /* reply is deferred, sent by mux_session_confirm */
484 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
486 debug2("%s: channel %d: alive check", __func__, c->self);
489 buffer_put_int(r, MUX_S_ALIVE);
490 buffer_put_int(r, rid);
491 buffer_put_int(r, (u_int)getpid());
497 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
499 debug2("%s: channel %d: terminate request", __func__, c->self);
501 if (options.control_master == SSHCTL_MASTER_ASK ||
502 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
503 if (!ask_permission("Terminate shared connection to %s? ",
505 debug2("%s: termination refused by user", __func__);
506 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
507 buffer_put_int(r, rid);
508 buffer_put_cstring(r, "Permission denied");
514 buffer_put_int(r, MUX_S_OK);
515 buffer_put_int(r, rid);
516 /* XXX exit happens too soon - message never makes it to client */
521 format_forward(u_int ftype, struct Forward *fwd)
527 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
528 (fwd->listen_path != NULL) ? fwd->listen_path :
529 (fwd->listen_host == NULL) ?
530 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
531 fwd->listen_host, fwd->listen_port,
532 (fwd->connect_path != NULL) ? fwd->connect_path :
533 fwd->connect_host, fwd->connect_port);
535 case MUX_FWD_DYNAMIC:
536 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
537 (fwd->listen_host == NULL) ?
538 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
539 fwd->listen_host, fwd->listen_port);
542 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
543 (fwd->listen_path != NULL) ? fwd->listen_path :
544 (fwd->listen_host == NULL) ?
545 "LOCALHOST" : fwd->listen_host,
547 (fwd->connect_path != NULL) ? fwd->connect_path :
548 fwd->connect_host, fwd->connect_port);
551 fatal("%s: unknown forward type %u", __func__, ftype);
557 compare_host(const char *a, const char *b)
559 if (a == NULL && b == NULL)
561 if (a == NULL || b == NULL)
563 return strcmp(a, b) == 0;
567 compare_forward(struct Forward *a, struct Forward *b)
569 if (!compare_host(a->listen_host, b->listen_host))
571 if (!compare_host(a->listen_path, b->listen_path))
573 if (a->listen_port != b->listen_port)
575 if (!compare_host(a->connect_host, b->connect_host))
577 if (!compare_host(a->connect_path, b->connect_path))
579 if (a->connect_port != b->connect_port)
586 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
588 struct mux_channel_confirm_ctx *fctx = ctxt;
589 char *failmsg = NULL;
590 struct Forward *rfwd;
594 if ((c = channel_by_id(fctx->cid)) == NULL) {
595 /* no channel for reply */
596 error("%s: unknown channel", __func__);
600 if (fctx->fid >= options.num_remote_forwards ||
601 (options.remote_forwards[fctx->fid].connect_path == NULL &&
602 options.remote_forwards[fctx->fid].connect_host == NULL)) {
603 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
606 rfwd = &options.remote_forwards[fctx->fid];
607 debug("%s: %s for: listen %d, connect %s:%d", __func__,
608 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
609 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
610 rfwd->connect_host, rfwd->connect_port);
611 if (type == SSH2_MSG_REQUEST_SUCCESS) {
612 if (rfwd->listen_port == 0) {
613 rfwd->allocated_port = packet_get_int();
614 debug("Allocated port %u for mux remote forward"
615 " to %s:%d", rfwd->allocated_port,
616 rfwd->connect_host, rfwd->connect_port);
617 buffer_put_int(&out, MUX_S_REMOTE_PORT);
618 buffer_put_int(&out, fctx->rid);
619 buffer_put_int(&out, rfwd->allocated_port);
620 channel_update_permitted_opens(rfwd->handle,
621 rfwd->allocated_port);
623 buffer_put_int(&out, MUX_S_OK);
624 buffer_put_int(&out, fctx->rid);
628 if (rfwd->listen_port == 0)
629 channel_update_permitted_opens(rfwd->handle, -1);
630 if (rfwd->listen_path != NULL)
631 xasprintf(&failmsg, "remote port forwarding failed for "
632 "listen path %s", rfwd->listen_path);
634 xasprintf(&failmsg, "remote port forwarding failed for "
635 "listen port %d", rfwd->listen_port);
637 debug2("%s: clearing registered forwarding for listen %d, "
638 "connect %s:%d", __func__, rfwd->listen_port,
639 rfwd->connect_path ? rfwd->connect_path :
640 rfwd->connect_host, rfwd->connect_port);
642 free(rfwd->listen_host);
643 free(rfwd->listen_path);
644 free(rfwd->connect_host);
645 free(rfwd->connect_path);
646 memset(rfwd, 0, sizeof(*rfwd));
649 error("%s: %s", __func__, failmsg);
650 buffer_put_int(&out, MUX_S_FAILURE);
651 buffer_put_int(&out, fctx->rid);
652 buffer_put_cstring(&out, failmsg);
655 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
657 if (c->mux_pause <= 0)
658 fatal("%s: mux_pause %d", __func__, c->mux_pause);
659 c->mux_pause = 0; /* start processing messages again */
663 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
666 char *fwd_desc = NULL;
667 char *listen_addr, *connect_addr;
670 int i, ret = 0, freefwd = 1;
672 memset(&fwd, 0, sizeof(fwd));
674 /* XXX - lport/cport check redundant */
675 if (buffer_get_int_ret(&ftype, m) != 0 ||
676 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
677 buffer_get_int_ret(&lport, m) != 0 ||
678 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
679 buffer_get_int_ret(&cport, m) != 0 ||
680 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
681 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
682 error("%s: malformed message", __func__);
686 if (*listen_addr == '\0') {
690 if (*connect_addr == '\0') {
695 memset(&fwd, 0, sizeof(fwd));
696 fwd.listen_port = lport;
697 if (fwd.listen_port == PORT_STREAMLOCAL)
698 fwd.listen_path = listen_addr;
700 fwd.listen_host = listen_addr;
701 fwd.connect_port = cport;
702 if (fwd.connect_port == PORT_STREAMLOCAL)
703 fwd.connect_path = connect_addr;
705 fwd.connect_host = connect_addr;
707 debug2("%s: channel %d: request %s", __func__, c->self,
708 (fwd_desc = format_forward(ftype, &fwd)));
710 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
711 ftype != MUX_FWD_DYNAMIC) {
712 logit("%s: invalid forwarding type %u", __func__, ftype);
716 buffer_put_int(r, MUX_S_FAILURE);
717 buffer_put_int(r, rid);
718 buffer_put_cstring(r, "Invalid forwarding request");
721 if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
722 logit("%s: streamlocal and dynamic forwards "
723 "are mutually exclusive", __func__);
726 if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
727 logit("%s: invalid listen port %u", __func__,
731 if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
732 || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
733 logit("%s: invalid connect port %u", __func__,
737 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
738 logit("%s: missing connect host", __func__);
742 /* Skip forwards that have already been requested */
745 case MUX_FWD_DYNAMIC:
746 for (i = 0; i < options.num_local_forwards; i++) {
747 if (compare_forward(&fwd,
748 options.local_forwards + i)) {
750 debug2("%s: found existing forwarding",
752 buffer_put_int(r, MUX_S_OK);
753 buffer_put_int(r, rid);
759 for (i = 0; i < options.num_remote_forwards; i++) {
760 if (compare_forward(&fwd,
761 options.remote_forwards + i)) {
762 if (fwd.listen_port != 0)
764 debug2("%s: found allocated port",
766 buffer_put_int(r, MUX_S_REMOTE_PORT);
767 buffer_put_int(r, rid);
769 options.remote_forwards[i].allocated_port);
776 if (options.control_master == SSHCTL_MASTER_ASK ||
777 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
778 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
779 debug2("%s: forwarding refused by user", __func__);
780 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
781 buffer_put_int(r, rid);
782 buffer_put_cstring(r, "Permission denied");
787 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
788 if (!channel_setup_local_fwd_listener(&fwd,
789 &options.fwd_opts)) {
791 logit("slave-requested %s failed", fwd_desc);
792 buffer_put_int(r, MUX_S_FAILURE);
793 buffer_put_int(r, rid);
794 buffer_put_cstring(r, "Port forwarding failed");
797 add_local_forward(&options, &fwd);
800 struct mux_channel_confirm_ctx *fctx;
802 fwd.handle = channel_request_remote_forwarding(&fwd);
805 add_remote_forward(&options, &fwd);
806 fctx = xcalloc(1, sizeof(*fctx));
809 fctx->fid = options.num_remote_forwards - 1;
810 client_register_global_confirm(mux_confirm_remote_forward,
813 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
814 /* delayed reply in mux_confirm_remote_forward */
817 buffer_put_int(r, MUX_S_OK);
818 buffer_put_int(r, rid);
822 free(fwd.listen_host);
823 free(fwd.listen_path);
824 free(fwd.connect_host);
825 free(fwd.connect_path);
831 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
833 struct Forward fwd, *found_fwd;
834 char *fwd_desc = NULL;
835 const char *error_reason = NULL;
836 char *listen_addr = NULL, *connect_addr = NULL;
841 memset(&fwd, 0, sizeof(fwd));
843 if (buffer_get_int_ret(&ftype, m) != 0 ||
844 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
845 buffer_get_int_ret(&lport, m) != 0 ||
846 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
847 buffer_get_int_ret(&cport, m) != 0 ||
848 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
849 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
850 error("%s: malformed message", __func__);
855 if (*listen_addr == '\0') {
859 if (*connect_addr == '\0') {
864 memset(&fwd, 0, sizeof(fwd));
865 fwd.listen_port = lport;
866 if (fwd.listen_port == PORT_STREAMLOCAL)
867 fwd.listen_path = listen_addr;
869 fwd.listen_host = listen_addr;
870 fwd.connect_port = cport;
871 if (fwd.connect_port == PORT_STREAMLOCAL)
872 fwd.connect_path = connect_addr;
874 fwd.connect_host = connect_addr;
876 debug2("%s: channel %d: request cancel %s", __func__, c->self,
877 (fwd_desc = format_forward(ftype, &fwd)));
879 /* make sure this has been requested */
883 case MUX_FWD_DYNAMIC:
884 for (i = 0; i < options.num_local_forwards; i++) {
885 if (compare_forward(&fwd,
886 options.local_forwards + i)) {
887 found_fwd = options.local_forwards + i;
893 for (i = 0; i < options.num_remote_forwards; i++) {
894 if (compare_forward(&fwd,
895 options.remote_forwards + i)) {
896 found_fwd = options.remote_forwards + i;
903 if (found_fwd == NULL)
904 error_reason = "port not forwarded";
905 else if (ftype == MUX_FWD_REMOTE) {
907 * This shouldn't fail unless we confused the host/port
908 * between options.remote_forwards and permitted_opens.
909 * However, for dynamic allocated listen ports we need
910 * to use the actual listen port.
912 if (channel_request_rforward_cancel(found_fwd) == -1)
913 error_reason = "port not in permitted opens";
914 } else { /* local and dynamic forwards */
916 if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
917 &options.fwd_opts) == -1)
918 error_reason = "port not found";
921 if (error_reason == NULL) {
922 buffer_put_int(r, MUX_S_OK);
923 buffer_put_int(r, rid);
925 free(found_fwd->listen_host);
926 free(found_fwd->listen_path);
927 free(found_fwd->connect_host);
928 free(found_fwd->connect_path);
929 found_fwd->listen_host = found_fwd->connect_host = NULL;
930 found_fwd->listen_path = found_fwd->connect_path = NULL;
931 found_fwd->listen_port = found_fwd->connect_port = 0;
933 buffer_put_int(r, MUX_S_FAILURE);
934 buffer_put_int(r, rid);
935 buffer_put_cstring(r, error_reason);
946 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
949 char *reserved, *chost;
952 struct mux_stdio_confirm_ctx *cctx;
954 chost = reserved = NULL;
955 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
956 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
957 buffer_get_int_ret(&cport, m) != 0) {
960 error("%s: malformed message", __func__);
965 debug2("%s: channel %d: request stdio fwd to %s:%u",
966 __func__, c->self, chost, cport);
968 /* Gather fds from client */
969 for(i = 0; i < 2; i++) {
970 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
971 error("%s: failed to receive fd %d from slave",
973 for (j = 0; j < i; j++)
978 buffer_put_int(r, MUX_S_FAILURE);
979 buffer_put_int(r, rid);
980 buffer_put_cstring(r,
981 "did not receive file descriptors");
986 debug3("%s: got fds stdin %d, stdout %d", __func__,
987 new_fd[0], new_fd[1]);
989 /* XXX support multiple child sessions in future */
990 if (c->remote_id != -1) {
991 debug2("%s: session already open", __func__);
993 buffer_put_int(r, MUX_S_FAILURE);
994 buffer_put_int(r, rid);
995 buffer_put_cstring(r, "Multiple sessions not supported");
1003 if (options.control_master == SSHCTL_MASTER_ASK ||
1004 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1005 if (!ask_permission("Allow forward to %s:%u? ",
1007 debug2("%s: stdio fwd refused by user", __func__);
1009 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1010 buffer_put_int(r, rid);
1011 buffer_put_cstring(r, "Permission denied");
1016 /* enable nonblocking unless tty */
1017 if (!isatty(new_fd[0]))
1018 set_nonblock(new_fd[0]);
1019 if (!isatty(new_fd[1]))
1020 set_nonblock(new_fd[1]);
1022 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1024 nc->ctl_chan = c->self; /* link session -> control channel */
1025 c->remote_id = nc->self; /* link control -> session channel */
1027 debug2("%s: channel_new: %d linked to control channel %d",
1028 __func__, nc->self, nc->ctl_chan);
1030 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1032 cctx = xcalloc(1, sizeof(*cctx));
1034 channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1035 c->mux_pause = 1; /* stop handling messages until open_confirm done */
1037 /* reply is deferred, sent by mux_session_confirm */
1041 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1043 mux_stdio_confirm(int id, int success, void *arg)
1045 struct mux_stdio_confirm_ctx *cctx = arg;
1050 fatal("%s: cctx == NULL", __func__);
1051 if ((c = channel_by_id(id)) == NULL)
1052 fatal("%s: no channel for id %d", __func__, id);
1053 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1054 fatal("%s: channel %d lacks control channel %d", __func__,
1058 debug3("%s: sending failure reply", __func__);
1060 buffer_init(&reply);
1061 buffer_put_int(&reply, MUX_S_FAILURE);
1062 buffer_put_int(&reply, cctx->rid);
1063 buffer_put_cstring(&reply, "Session open refused by peer");
1067 debug3("%s: sending success reply", __func__);
1069 buffer_init(&reply);
1070 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1071 buffer_put_int(&reply, cctx->rid);
1072 buffer_put_int(&reply, c->self);
1076 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1077 buffer_free(&reply);
1079 if (cc->mux_pause <= 0)
1080 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1081 cc->mux_pause = 0; /* start processing messages again */
1082 c->open_confirm_ctx = NULL;
1087 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1089 debug("%s: channel %d: stop listening", __func__, c->self);
1091 if (options.control_master == SSHCTL_MASTER_ASK ||
1092 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1093 if (!ask_permission("Disable further multiplexing on shared "
1094 "connection to %s? ", host)) {
1095 debug2("%s: stop listen refused by user", __func__);
1096 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1097 buffer_put_int(r, rid);
1098 buffer_put_cstring(r, "Permission denied");
1103 if (mux_listener_channel != NULL) {
1104 channel_free(mux_listener_channel);
1106 free(options.control_path);
1107 options.control_path = NULL;
1108 mux_listener_channel = NULL;
1109 muxserver_sock = -1;
1113 buffer_put_int(r, MUX_S_OK);
1114 buffer_put_int(r, rid);
1120 process_mux_proxy(u_int rid, Channel *c, Buffer *m, Buffer *r)
1122 debug("%s: channel %d: proxy request", __func__, c->self);
1124 c->mux_rcb = channel_proxy_downstream;
1125 buffer_put_int(r, MUX_S_PROXY);
1126 buffer_put_int(r, rid);
1131 /* Channel callbacks fired on read/write from mux slave fd */
1133 mux_master_read_cb(Channel *c)
1135 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1138 u_int type, rid, have, i;
1142 if (c->mux_ctx == NULL) {
1143 state = xcalloc(1, sizeof(*state));
1145 channel_register_cleanup(c->self,
1146 mux_master_control_cleanup_cb, 0);
1150 buffer_put_int(&out, MUX_MSG_HELLO);
1151 buffer_put_int(&out, SSHMUX_VER);
1153 buffer_put_string(&c->output, buffer_ptr(&out),
1156 debug3("%s: channel %d: hello sent", __func__, c->self);
1163 /* Channel code ensures that we receive whole packets */
1164 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1166 error("%s: malformed message", __func__);
1169 buffer_append(&in, ptr, have);
1171 if (buffer_get_int_ret(&type, &in) != 0)
1173 debug3("%s: channel %d packet type 0x%08x len %u",
1174 __func__, c->self, type, buffer_len(&in));
1176 if (type == MUX_MSG_HELLO)
1179 if (!state->hello_rcvd) {
1180 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1181 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1184 if (buffer_get_int_ret(&rid, &in) != 0)
1188 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1189 if (type == mux_master_handlers[i].type) {
1190 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1194 if (mux_master_handlers[i].handler == NULL) {
1195 error("%s: unsupported mux message 0x%08x", __func__, type);
1196 buffer_put_int(&out, MUX_S_FAILURE);
1197 buffer_put_int(&out, rid);
1198 buffer_put_cstring(&out, "unsupported request");
1201 /* Enqueue reply packet */
1202 if (buffer_len(&out) != 0) {
1203 buffer_put_string(&c->output, buffer_ptr(&out),
1213 mux_exit_message(Channel *c, int exitval)
1218 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1221 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1222 fatal("%s: channel %d missing mux channel %d",
1223 __func__, c->self, c->ctl_chan);
1225 /* Append exit message packet to control socket output queue */
1227 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1228 buffer_put_int(&m, c->self);
1229 buffer_put_int(&m, exitval);
1231 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1236 mux_tty_alloc_failed(Channel *c)
1241 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1243 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1244 fatal("%s: channel %d missing mux channel %d",
1245 __func__, c->self, c->ctl_chan);
1247 /* Append exit message packet to control socket output queue */
1249 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1250 buffer_put_int(&m, c->self);
1252 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1256 /* Prepare a mux master to listen on a Unix domain socket. */
1258 muxserver_listen(void)
1261 char *orig_control_path = options.control_path;
1266 if (options.control_path == NULL ||
1267 options.control_master == SSHCTL_MASTER_NO)
1270 debug("setting up multiplex master socket");
1273 * Use a temporary path before listen so we can pseudo-atomically
1274 * establish the listening socket in its final location to avoid
1275 * other processes racing in between bind() and listen() and hitting
1276 * an unready socket.
1278 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1279 r = arc4random_uniform(26+26+10);
1280 rbuf[i] = (r < 26) ? 'a' + r :
1281 (r < 26*2) ? 'A' + r - 26 :
1284 rbuf[sizeof(rbuf) - 1] = '\0';
1285 options.control_path = NULL;
1286 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1287 debug3("%s: temporary control path %s", __func__, options.control_path);
1289 old_umask = umask(0177);
1290 muxserver_sock = unix_listener(options.control_path, 64, 0);
1293 if (muxserver_sock < 0) {
1294 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1295 error("ControlSocket %s already exists, "
1296 "disabling multiplexing", options.control_path);
1298 if (muxserver_sock != -1) {
1299 close(muxserver_sock);
1300 muxserver_sock = -1;
1302 free(orig_control_path);
1303 free(options.control_path);
1304 options.control_path = NULL;
1305 options.control_master = SSHCTL_MASTER_NO;
1308 /* unix_listener() logs the error */
1313 /* Now atomically "move" the mux socket into position */
1314 if (link(options.control_path, orig_control_path) != 0) {
1315 if (errno != EEXIST) {
1316 fatal("%s: link mux listener %s => %s: %s", __func__,
1317 options.control_path, orig_control_path,
1320 error("ControlSocket %s already exists, disabling multiplexing",
1322 unlink(options.control_path);
1323 goto disable_mux_master;
1325 unlink(options.control_path);
1326 free(options.control_path);
1327 options.control_path = orig_control_path;
1329 set_nonblock(muxserver_sock);
1331 mux_listener_channel = channel_new("mux listener",
1332 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1333 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1334 0, options.control_path, 1);
1335 mux_listener_channel->mux_rcb = mux_master_read_cb;
1336 debug3("%s: mux listener channel %d fd %d", __func__,
1337 mux_listener_channel->self, mux_listener_channel->sock);
1340 /* Callback on open confirmation in mux master for a mux client session. */
1342 mux_session_confirm(int id, int success, void *arg)
1344 struct mux_session_confirm_ctx *cctx = arg;
1345 const char *display;
1351 fatal("%s: cctx == NULL", __func__);
1352 if ((c = channel_by_id(id)) == NULL)
1353 fatal("%s: no channel for id %d", __func__, id);
1354 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1355 fatal("%s: channel %d lacks control channel %d", __func__,
1359 debug3("%s: sending failure reply", __func__);
1361 buffer_init(&reply);
1362 buffer_put_int(&reply, MUX_S_FAILURE);
1363 buffer_put_int(&reply, cctx->rid);
1364 buffer_put_cstring(&reply, "Session open refused by peer");
1368 display = getenv("DISPLAY");
1369 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1372 /* Get reasonable local authentication information. */
1373 if (client_x11_get_proto(display, options.xauth_location,
1374 options.forward_x11_trusted, options.forward_x11_timeout,
1375 &proto, &data) == 0) {
1376 /* Request forwarding with authentication spoofing. */
1377 debug("Requesting X11 forwarding with authentication "
1379 x11_request_forwarding_with_spoofing(id, display, proto,
1381 /* XXX exit_on_forward_failure */
1382 client_expect_confirm(id, "X11 forwarding",
1387 if (cctx->want_agent_fwd && options.forward_agent) {
1388 debug("Requesting authentication agent forwarding.");
1389 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1393 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1394 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1396 debug3("%s: sending success reply", __func__);
1398 buffer_init(&reply);
1399 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1400 buffer_put_int(&reply, cctx->rid);
1401 buffer_put_int(&reply, c->self);
1405 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1406 buffer_free(&reply);
1408 if (cc->mux_pause <= 0)
1409 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1410 cc->mux_pause = 0; /* start processing messages again */
1411 c->open_confirm_ctx = NULL;
1412 buffer_free(&cctx->cmd);
1414 if (cctx->env != NULL) {
1415 for (i = 0; cctx->env[i] != NULL; i++)
1422 /* ** Multiplexing client support */
1424 /* Exit signal handler */
1426 control_client_sighandler(int signo)
1428 muxclient_terminate = signo;
1432 * Relay signal handler - used to pass some signals from mux client to
1436 control_client_sigrelay(int signo)
1438 int save_errno = errno;
1440 if (muxserver_pid > 1)
1441 kill(muxserver_pid, signo);
1447 mux_client_read(int fd, Buffer *b, u_int need)
1455 pfd.events = POLLIN;
1456 p = buffer_append_space(b, need);
1457 for (have = 0; have < need; ) {
1458 if (muxclient_terminate) {
1462 len = read(fd, p + have, need - have);
1465 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1469 (void)poll(&pfd, 1, -1);
1487 mux_client_write_packet(int fd, Buffer *m)
1496 pfd.events = POLLOUT;
1497 buffer_init(&queue);
1498 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1500 need = buffer_len(&queue);
1501 ptr = buffer_ptr(&queue);
1503 for (have = 0; have < need; ) {
1504 if (muxclient_terminate) {
1505 buffer_free(&queue);
1509 len = write(fd, ptr + have, need - have);
1512 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1516 (void)poll(&pfd, 1, -1);
1522 buffer_free(&queue);
1528 buffer_free(&queue);
1534 buffer_free(&queue);
1539 mux_client_read_packet(int fd, Buffer *m)
1546 buffer_init(&queue);
1547 if (mux_client_read(fd, &queue, 4) != 0) {
1548 if ((oerrno = errno) == EPIPE)
1549 debug3("%s: read header failed: %s", __func__,
1551 buffer_free(&queue);
1555 need = get_u32(buffer_ptr(&queue));
1556 if (mux_client_read(fd, &queue, need) != 0) {
1558 debug3("%s: read body failed: %s", __func__, strerror(errno));
1559 buffer_free(&queue);
1563 ptr = buffer_get_string_ptr(&queue, &have);
1564 buffer_append(m, ptr, have);
1565 buffer_free(&queue);
1570 mux_client_hello_exchange(int fd)
1576 buffer_put_int(&m, MUX_MSG_HELLO);
1577 buffer_put_int(&m, SSHMUX_VER);
1580 if (mux_client_write_packet(fd, &m) != 0)
1581 fatal("%s: write packet: %s", __func__, strerror(errno));
1585 /* Read their HELLO */
1586 if (mux_client_read_packet(fd, &m) != 0) {
1591 type = buffer_get_int(&m);
1592 if (type != MUX_MSG_HELLO)
1593 fatal("%s: expected HELLO (%u) received %u",
1594 __func__, MUX_MSG_HELLO, type);
1595 ver = buffer_get_int(&m);
1596 if (ver != SSHMUX_VER)
1597 fatal("Unsupported multiplexing protocol version %d "
1598 "(expected %d)", ver, SSHMUX_VER);
1599 debug2("%s: master version %u", __func__, ver);
1600 /* No extensions are presently defined */
1601 while (buffer_len(&m) > 0) {
1602 char *name = buffer_get_string(&m, NULL);
1603 char *value = buffer_get_string(&m, NULL);
1605 debug2("Unrecognised master extension \"%s\"", name);
1614 mux_client_request_alive(int fd)
1618 u_int pid, type, rid;
1620 debug3("%s: entering", __func__);
1623 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1624 buffer_put_int(&m, muxclient_request_id);
1626 if (mux_client_write_packet(fd, &m) != 0)
1627 fatal("%s: write packet: %s", __func__, strerror(errno));
1631 /* Read their reply */
1632 if (mux_client_read_packet(fd, &m) != 0) {
1637 type = buffer_get_int(&m);
1638 if (type != MUX_S_ALIVE) {
1639 e = buffer_get_string(&m, NULL);
1640 fatal("%s: master returned error: %s", __func__, e);
1643 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1644 fatal("%s: out of sequence reply: my id %u theirs %u",
1645 __func__, muxclient_request_id, rid);
1646 pid = buffer_get_int(&m);
1649 debug3("%s: done pid = %u", __func__, pid);
1651 muxclient_request_id++;
1657 mux_client_request_terminate(int fd)
1663 debug3("%s: entering", __func__);
1666 buffer_put_int(&m, MUX_C_TERMINATE);
1667 buffer_put_int(&m, muxclient_request_id);
1669 if (mux_client_write_packet(fd, &m) != 0)
1670 fatal("%s: write packet: %s", __func__, strerror(errno));
1674 /* Read their reply */
1675 if (mux_client_read_packet(fd, &m) != 0) {
1676 /* Remote end exited already */
1677 if (errno == EPIPE) {
1681 fatal("%s: read from master failed: %s",
1682 __func__, strerror(errno));
1685 type = buffer_get_int(&m);
1686 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1687 fatal("%s: out of sequence reply: my id %u theirs %u",
1688 __func__, muxclient_request_id, rid);
1692 case MUX_S_PERMISSION_DENIED:
1693 e = buffer_get_string(&m, NULL);
1694 fatal("Master refused termination request: %s", e);
1696 e = buffer_get_string(&m, NULL);
1697 fatal("%s: termination request failed: %s", __func__, e);
1699 fatal("%s: unexpected response from master 0x%08x",
1703 muxclient_request_id++;
1707 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1713 fwd_desc = format_forward(ftype, fwd);
1714 debug("Requesting %s %s",
1715 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1719 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1720 buffer_put_int(&m, muxclient_request_id);
1721 buffer_put_int(&m, ftype);
1722 if (fwd->listen_path != NULL) {
1723 buffer_put_cstring(&m, fwd->listen_path);
1725 buffer_put_cstring(&m,
1726 fwd->listen_host == NULL ? "" :
1727 (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1729 buffer_put_int(&m, fwd->listen_port);
1730 if (fwd->connect_path != NULL) {
1731 buffer_put_cstring(&m, fwd->connect_path);
1733 buffer_put_cstring(&m,
1734 fwd->connect_host == NULL ? "" : fwd->connect_host);
1736 buffer_put_int(&m, fwd->connect_port);
1738 if (mux_client_write_packet(fd, &m) != 0)
1739 fatal("%s: write packet: %s", __func__, strerror(errno));
1743 /* Read their reply */
1744 if (mux_client_read_packet(fd, &m) != 0) {
1749 type = buffer_get_int(&m);
1750 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1751 fatal("%s: out of sequence reply: my id %u theirs %u",
1752 __func__, muxclient_request_id, rid);
1756 case MUX_S_REMOTE_PORT:
1758 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1759 fwd->allocated_port = buffer_get_int(&m);
1760 verbose("Allocated port %u for remote forward to %s:%d",
1761 fwd->allocated_port,
1762 fwd->connect_host ? fwd->connect_host : "",
1764 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1765 fprintf(stdout, "%i\n", fwd->allocated_port);
1767 case MUX_S_PERMISSION_DENIED:
1768 e = buffer_get_string(&m, NULL);
1770 error("Master refused forwarding request: %s", e);
1773 e = buffer_get_string(&m, NULL);
1775 error("%s: forwarding request failed: %s", __func__, e);
1778 fatal("%s: unexpected response from master 0x%08x",
1783 muxclient_request_id++;
1788 mux_client_forwards(int fd, int cancel_flag)
1792 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1793 cancel_flag ? "cancel" : "request",
1794 options.num_local_forwards, options.num_remote_forwards);
1796 /* XXX ExitOnForwardingFailure */
1797 for (i = 0; i < options.num_local_forwards; i++) {
1798 if (mux_client_forward(fd, cancel_flag,
1799 options.local_forwards[i].connect_port == 0 ?
1800 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1801 options.local_forwards + i) != 0)
1804 for (i = 0; i < options.num_remote_forwards; i++) {
1805 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1806 options.remote_forwards + i) != 0)
1813 mux_client_request_session(int fd)
1817 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1818 extern char **environ;
1819 int devnull, rawmode;
1821 debug3("%s: entering", __func__);
1823 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1824 error("%s: master alive request failed", __func__);
1828 signal(SIGPIPE, SIG_IGN);
1830 if (stdin_null_flag) {
1831 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1832 fatal("open(/dev/null): %s", strerror(errno));
1833 if (dup2(devnull, STDIN_FILENO) == -1)
1834 fatal("dup2: %s", strerror(errno));
1835 if (devnull > STDERR_FILENO)
1839 term = getenv("TERM");
1842 buffer_put_int(&m, MUX_C_NEW_SESSION);
1843 buffer_put_int(&m, muxclient_request_id);
1844 buffer_put_cstring(&m, ""); /* reserved */
1845 buffer_put_int(&m, tty_flag);
1846 buffer_put_int(&m, options.forward_x11);
1847 buffer_put_int(&m, options.forward_agent);
1848 buffer_put_int(&m, subsystem_flag);
1849 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1850 0xffffffff : (u_int)options.escape_char);
1851 buffer_put_cstring(&m, term == NULL ? "" : term);
1852 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1854 if (options.num_send_env > 0 && environ != NULL) {
1855 /* Pass environment */
1856 for (i = 0; environ[i] != NULL; i++) {
1857 if (env_permitted(environ[i])) {
1858 buffer_put_cstring(&m, environ[i]);
1863 if (mux_client_write_packet(fd, &m) != 0)
1864 fatal("%s: write packet: %s", __func__, strerror(errno));
1866 /* Send the stdio file descriptors */
1867 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1868 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1869 mm_send_fd(fd, STDERR_FILENO) == -1)
1870 fatal("%s: send fds failed", __func__);
1872 debug3("%s: session request sent", __func__);
1874 /* Read their reply */
1876 if (mux_client_read_packet(fd, &m) != 0) {
1877 error("%s: read from master failed: %s",
1878 __func__, strerror(errno));
1883 type = buffer_get_int(&m);
1884 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1885 fatal("%s: out of sequence reply: my id %u theirs %u",
1886 __func__, muxclient_request_id, rid);
1888 case MUX_S_SESSION_OPENED:
1889 sid = buffer_get_int(&m);
1890 debug("%s: master session id: %u", __func__, sid);
1892 case MUX_S_PERMISSION_DENIED:
1893 e = buffer_get_string(&m, NULL);
1895 error("Master refused session request: %s", e);
1898 e = buffer_get_string(&m, NULL);
1900 error("%s: session request failed: %s", __func__, e);
1904 error("%s: unexpected response from master 0x%08x",
1908 muxclient_request_id++;
1910 if (pledge("stdio proc tty", NULL) == -1)
1911 fatal("%s pledge(): %s", __func__, strerror(errno));
1912 platform_pledge_mux();
1914 signal(SIGHUP, control_client_sighandler);
1915 signal(SIGINT, control_client_sighandler);
1916 signal(SIGTERM, control_client_sighandler);
1917 signal(SIGWINCH, control_client_sigrelay);
1921 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1924 * Stick around until the controlee closes the client_fd.
1925 * Before it does, it is expected to write an exit message.
1926 * This process must read the value and wait for the closure of
1927 * the client_fd; if this one closes early, the multiplex master will
1928 * terminate early too (possibly losing data).
1930 for (exitval = 255, exitval_seen = 0;;) {
1932 if (mux_client_read_packet(fd, &m) != 0)
1934 type = buffer_get_int(&m);
1936 case MUX_S_TTY_ALLOC_FAIL:
1937 if ((esid = buffer_get_int(&m)) != sid)
1938 fatal("%s: tty alloc fail on unknown session: "
1939 "my id %u theirs %u",
1940 __func__, sid, esid);
1941 leave_raw_mode(options.request_tty ==
1945 case MUX_S_EXIT_MESSAGE:
1946 if ((esid = buffer_get_int(&m)) != sid)
1947 fatal("%s: exit on unknown session: "
1948 "my id %u theirs %u",
1949 __func__, sid, esid);
1951 fatal("%s: exitval sent twice", __func__);
1952 exitval = buffer_get_int(&m);
1956 e = buffer_get_string(&m, NULL);
1957 fatal("%s: master returned error: %s", __func__, e);
1963 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1965 if (muxclient_terminate) {
1966 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1968 } else if (!exitval_seen) {
1969 debug2("Control master terminated unexpectedly");
1972 debug2("Received exit status from master %d", exitval);
1974 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1975 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1981 mux_client_proxy(int fd)
1988 buffer_put_int(&m, MUX_C_PROXY);
1989 buffer_put_int(&m, muxclient_request_id);
1990 if (mux_client_write_packet(fd, &m) != 0)
1991 fatal("%s: write packet: %s", __func__, strerror(errno));
1995 /* Read their reply */
1996 if (mux_client_read_packet(fd, &m) != 0) {
2000 type = buffer_get_int(&m);
2001 if (type != MUX_S_PROXY) {
2002 e = buffer_get_string(&m, NULL);
2003 fatal("%s: master returned error: %s", __func__, e);
2005 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2006 fatal("%s: out of sequence reply: my id %u theirs %u",
2007 __func__, muxclient_request_id, rid);
2010 debug3("%s: done", __func__);
2011 muxclient_request_id++;
2016 mux_client_request_stdio_fwd(int fd)
2020 u_int type, rid, sid;
2023 debug3("%s: entering", __func__);
2025 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
2026 error("%s: master alive request failed", __func__);
2030 signal(SIGPIPE, SIG_IGN);
2032 if (stdin_null_flag) {
2033 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
2034 fatal("open(/dev/null): %s", strerror(errno));
2035 if (dup2(devnull, STDIN_FILENO) == -1)
2036 fatal("dup2: %s", strerror(errno));
2037 if (devnull > STDERR_FILENO)
2042 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
2043 buffer_put_int(&m, muxclient_request_id);
2044 buffer_put_cstring(&m, ""); /* reserved */
2045 buffer_put_cstring(&m, options.stdio_forward_host);
2046 buffer_put_int(&m, options.stdio_forward_port);
2048 if (mux_client_write_packet(fd, &m) != 0)
2049 fatal("%s: write packet: %s", __func__, strerror(errno));
2051 /* Send the stdio file descriptors */
2052 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
2053 mm_send_fd(fd, STDOUT_FILENO) == -1)
2054 fatal("%s: send fds failed", __func__);
2056 if (pledge("stdio proc tty", NULL) == -1)
2057 fatal("%s pledge(): %s", __func__, strerror(errno));
2058 platform_pledge_mux();
2060 debug3("%s: stdio forward request sent", __func__);
2062 /* Read their reply */
2065 if (mux_client_read_packet(fd, &m) != 0) {
2066 error("%s: read from master failed: %s",
2067 __func__, strerror(errno));
2072 type = buffer_get_int(&m);
2073 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2074 fatal("%s: out of sequence reply: my id %u theirs %u",
2075 __func__, muxclient_request_id, rid);
2077 case MUX_S_SESSION_OPENED:
2078 sid = buffer_get_int(&m);
2079 debug("%s: master session id: %u", __func__, sid);
2081 case MUX_S_PERMISSION_DENIED:
2082 e = buffer_get_string(&m, NULL);
2084 fatal("Master refused stdio forwarding request: %s", e);
2086 e = buffer_get_string(&m, NULL);
2088 fatal("Stdio forwarding request failed: %s", e);
2091 error("%s: unexpected response from master 0x%08x",
2095 muxclient_request_id++;
2097 signal(SIGHUP, control_client_sighandler);
2098 signal(SIGINT, control_client_sighandler);
2099 signal(SIGTERM, control_client_sighandler);
2100 signal(SIGWINCH, control_client_sigrelay);
2103 * Stick around until the controlee closes the client_fd.
2106 if (mux_client_read_packet(fd, &m) != 0) {
2107 if (errno == EPIPE ||
2108 (errno == EINTR && muxclient_terminate != 0))
2110 fatal("%s: mux_client_read_packet: %s",
2111 __func__, strerror(errno));
2113 fatal("%s: master returned unexpected message %u", __func__, type);
2117 mux_client_request_stop_listening(int fd)
2123 debug3("%s: entering", __func__);
2126 buffer_put_int(&m, MUX_C_STOP_LISTENING);
2127 buffer_put_int(&m, muxclient_request_id);
2129 if (mux_client_write_packet(fd, &m) != 0)
2130 fatal("%s: write packet: %s", __func__, strerror(errno));
2134 /* Read their reply */
2135 if (mux_client_read_packet(fd, &m) != 0)
2136 fatal("%s: read from master failed: %s",
2137 __func__, strerror(errno));
2139 type = buffer_get_int(&m);
2140 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2141 fatal("%s: out of sequence reply: my id %u theirs %u",
2142 __func__, muxclient_request_id, rid);
2146 case MUX_S_PERMISSION_DENIED:
2147 e = buffer_get_string(&m, NULL);
2148 fatal("Master refused stop listening request: %s", e);
2150 e = buffer_get_string(&m, NULL);
2151 fatal("%s: stop listening request failed: %s", __func__, e);
2153 fatal("%s: unexpected response from master 0x%08x",
2157 muxclient_request_id++;
2160 /* Multiplex client main loop. */
2162 muxclient(const char *path)
2164 struct sockaddr_un addr;
2168 if (muxclient_command == 0) {
2169 if (options.stdio_forward_host != NULL)
2170 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2172 muxclient_command = SSHMUX_COMMAND_OPEN;
2175 switch (options.control_master) {
2176 case SSHCTL_MASTER_AUTO:
2177 case SSHCTL_MASTER_AUTO_ASK:
2178 debug("auto-mux: Trying existing master");
2180 case SSHCTL_MASTER_NO:
2186 memset(&addr, '\0', sizeof(addr));
2187 addr.sun_family = AF_UNIX;
2189 if (strlcpy(addr.sun_path, path,
2190 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2191 fatal("ControlPath too long ('%s' >= %u bytes)", path,
2192 (unsigned int)sizeof(addr.sun_path));
2194 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2195 fatal("%s socket(): %s", __func__, strerror(errno));
2197 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
2198 switch (muxclient_command) {
2199 case SSHMUX_COMMAND_OPEN:
2200 case SSHMUX_COMMAND_STDIO_FWD:
2203 fatal("Control socket connect(%.100s): %s", path,
2206 if (errno == ECONNREFUSED &&
2207 options.control_master != SSHCTL_MASTER_NO) {
2208 debug("Stale control socket %.100s, unlinking", path);
2210 } else if (errno == ENOENT) {
2211 debug("Control socket \"%.100s\" does not exist", path);
2213 error("Control socket connect(%.100s): %s", path,
2221 if (mux_client_hello_exchange(sock) != 0) {
2222 error("%s: master hello exchange failed", __func__);
2227 switch (muxclient_command) {
2228 case SSHMUX_COMMAND_ALIVE_CHECK:
2229 if ((pid = mux_client_request_alive(sock)) == 0)
2230 fatal("%s: master alive check failed", __func__);
2231 fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2233 case SSHMUX_COMMAND_TERMINATE:
2234 mux_client_request_terminate(sock);
2235 if (options.log_level != SYSLOG_LEVEL_QUIET)
2236 fprintf(stderr, "Exit request sent.\r\n");
2238 case SSHMUX_COMMAND_FORWARD:
2239 if (mux_client_forwards(sock, 0) != 0)
2240 fatal("%s: master forward request failed", __func__);
2242 case SSHMUX_COMMAND_OPEN:
2243 if (mux_client_forwards(sock, 0) != 0) {
2244 error("%s: master forward request failed", __func__);
2247 mux_client_request_session(sock);
2249 case SSHMUX_COMMAND_STDIO_FWD:
2250 mux_client_request_stdio_fwd(sock);
2252 case SSHMUX_COMMAND_STOP:
2253 mux_client_request_stop_listening(sock);
2254 if (options.log_level != SYSLOG_LEVEL_QUIET)
2255 fprintf(stderr, "Stop listening request sent.\r\n");
2257 case SSHMUX_COMMAND_CANCEL_FWD:
2258 if (mux_client_forwards(sock, 1) != 0)
2259 error("%s: master cancel forward request failed",
2262 case SSHMUX_COMMAND_PROXY:
2263 mux_client_proxy(sock);
2266 fatal("unrecognised muxclient_command %d", muxclient_command);