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
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"
86 extern Options options;
87 extern int stdin_null_flag;
89 extern int subsystem_flag;
90 extern Buffer command;
91 extern volatile sig_atomic_t quit_pending;
93 /* Context for session open confirmation callback */
94 struct mux_session_confirm_ctx {
106 /* Context for stdio fwd open confirmation callback */
107 struct mux_stdio_confirm_ctx {
111 /* Context for global channel callback */
112 struct mux_channel_confirm_ctx {
113 u_int cid; /* channel id */
114 u_int rid; /* request id */
115 int fid; /* forward id */
118 /* fd to control socket */
119 int muxserver_sock = -1;
121 /* client request id */
122 u_int muxclient_request_id = 0;
124 /* Multiplexing control command */
125 u_int muxclient_command = 0;
127 /* Set when signalled. */
128 static volatile sig_atomic_t muxclient_terminate = 0;
130 /* PID of multiplex server */
131 static u_int muxserver_pid = 0;
133 static Channel *mux_listener_channel = NULL;
135 struct mux_master_state {
139 /* mux protocol messages */
140 #define MUX_MSG_HELLO 0x00000001
141 #define MUX_C_NEW_SESSION 0x10000002
142 #define MUX_C_ALIVE_CHECK 0x10000004
143 #define MUX_C_TERMINATE 0x10000005
144 #define MUX_C_OPEN_FWD 0x10000006
145 #define MUX_C_CLOSE_FWD 0x10000007
146 #define MUX_C_NEW_STDIO_FWD 0x10000008
147 #define MUX_C_STOP_LISTENING 0x10000009
148 #define MUX_S_OK 0x80000001
149 #define MUX_S_PERMISSION_DENIED 0x80000002
150 #define MUX_S_FAILURE 0x80000003
151 #define MUX_S_EXIT_MESSAGE 0x80000004
152 #define MUX_S_ALIVE 0x80000005
153 #define MUX_S_SESSION_OPENED 0x80000006
154 #define MUX_S_REMOTE_PORT 0x80000007
155 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
157 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
158 #define MUX_FWD_LOCAL 1
159 #define MUX_FWD_REMOTE 2
160 #define MUX_FWD_DYNAMIC 3
162 static void mux_session_confirm(int, int, void *);
163 static void mux_stdio_confirm(int, int, void *);
165 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
174 static const struct {
176 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
177 } mux_master_handlers[] = {
178 { MUX_MSG_HELLO, process_mux_master_hello },
179 { MUX_C_NEW_SESSION, process_mux_new_session },
180 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
181 { MUX_C_TERMINATE, process_mux_terminate },
182 { MUX_C_OPEN_FWD, process_mux_open_fwd },
183 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
184 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
185 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
189 /* Cleanup callback fired on closure of mux slave _session_ channel */
192 mux_master_session_cleanup_cb(int cid, void *unused)
194 Channel *cc, *c = channel_by_id(cid);
196 debug3("%s: entering for channel %d", __func__, cid);
198 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
199 if (c->ctl_chan != -1) {
200 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
201 fatal("%s: channel %d missing control channel %d",
202 __func__, c->self, c->ctl_chan);
205 chan_rcvd_oclose(cc);
207 channel_cancel_cleanup(c->self);
210 /* Cleanup callback fired on closure of mux slave _control_ channel */
213 mux_master_control_cleanup_cb(int cid, void *unused)
215 Channel *sc, *c = channel_by_id(cid);
217 debug3("%s: entering for channel %d", __func__, cid);
219 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
220 if (c->remote_id != -1) {
221 if ((sc = channel_by_id(c->remote_id)) == NULL)
222 fatal("%s: channel %d missing session channel %d",
223 __func__, c->self, c->remote_id);
226 if (sc->type != SSH_CHANNEL_OPEN &&
227 sc->type != SSH_CHANNEL_OPENING) {
228 debug2("%s: channel %d: not open", __func__, sc->self);
231 if (sc->istate == CHAN_INPUT_OPEN)
232 chan_read_failed(sc);
233 if (sc->ostate == CHAN_OUTPUT_OPEN)
234 chan_write_failed(sc);
237 channel_cancel_cleanup(c->self);
240 /* Check mux client environment variables before passing them to mux master. */
242 env_permitted(char *env)
245 char name[1024], *cp;
247 if ((cp = strchr(env, '=')) == NULL || cp == env)
249 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
250 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
251 error("env_permitted: name '%.100s...' too long", env);
255 for (i = 0; i < options.num_send_env; i++)
256 if (match_pattern(name, options.send_env[i]))
262 /* Mux master protocol message handlers */
265 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
268 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
271 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
272 if (state->hello_rcvd) {
273 error("%s: HELLO received twice", __func__);
276 if (buffer_get_int_ret(&ver, m) != 0) {
278 error("%s: malformed message", __func__);
281 if (ver != SSHMUX_VER) {
282 error("Unsupported multiplexing protocol version %d "
283 "(expected %d)", ver, SSHMUX_VER);
286 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
288 /* No extensions are presently defined */
289 while (buffer_len(m) > 0) {
290 char *name = buffer_get_string_ret(m, NULL);
291 char *value = buffer_get_string_ret(m, NULL);
293 if (name == NULL || value == NULL) {
298 debug2("Unrecognised slave extension \"%s\"", name);
302 state->hello_rcvd = 1;
307 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
310 struct mux_session_confirm_ctx *cctx;
311 char *reserved, *cmd, *cp;
312 u_int i, j, len, env_len, escape_char, window, packetmax;
315 /* Reply for SSHMUX_COMMAND_OPEN */
316 cctx = xcalloc(1, sizeof(*cctx));
319 cmd = reserved = NULL;
322 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
323 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
324 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
325 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
326 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
327 buffer_get_int_ret(&escape_char, m) != 0 ||
328 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
329 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
333 for (j = 0; j < env_len; j++)
338 error("%s: malformed message", __func__);
344 while (buffer_len(m) > 0) {
345 #define MUX_MAX_ENV_VARS 4096
346 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
348 if (!env_permitted(cp)) {
352 cctx->env = xreallocarray(cctx->env, env_len + 2,
354 cctx->env[env_len++] = cp;
355 cctx->env[env_len] = NULL;
356 if (env_len > MUX_MAX_ENV_VARS) {
357 error(">%d environment variables received, ignoring "
358 "additional", MUX_MAX_ENV_VARS);
363 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
364 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
365 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
366 cctx->want_subsys, cctx->term, cmd, env_len);
368 buffer_init(&cctx->cmd);
369 buffer_append(&cctx->cmd, cmd, strlen(cmd));
373 /* Gather fds from client */
374 for(i = 0; i < 3; i++) {
375 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
376 error("%s: failed to receive fd %d from slave",
378 for (j = 0; j < i; j++)
380 for (j = 0; j < env_len; j++)
384 buffer_free(&cctx->cmd);
388 buffer_put_int(r, MUX_S_FAILURE);
389 buffer_put_int(r, rid);
390 buffer_put_cstring(r,
391 "did not receive file descriptors");
396 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
397 new_fd[0], new_fd[1], new_fd[2]);
399 /* XXX support multiple child sessions in future */
400 if (c->remote_id != -1) {
401 debug2("%s: session already open", __func__);
403 buffer_put_int(r, MUX_S_FAILURE);
404 buffer_put_int(r, rid);
405 buffer_put_cstring(r, "Multiple sessions not supported");
412 for (i = 0; i < env_len; i++)
416 buffer_free(&cctx->cmd);
421 if (options.control_master == SSHCTL_MASTER_ASK ||
422 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
423 if (!ask_permission("Allow shared connection to %s? ", host)) {
424 debug2("%s: session refused by user", __func__);
426 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
427 buffer_put_int(r, rid);
428 buffer_put_cstring(r, "Permission denied");
433 /* Try to pick up ttymodes from client before it goes raw */
434 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
435 error("%s: tcgetattr: %s", __func__, strerror(errno));
437 /* enable nonblocking unless tty */
438 if (!isatty(new_fd[0]))
439 set_nonblock(new_fd[0]);
440 if (!isatty(new_fd[1]))
441 set_nonblock(new_fd[1]);
442 if (!isatty(new_fd[2]))
443 set_nonblock(new_fd[2]);
445 window = CHAN_SES_WINDOW_DEFAULT;
446 packetmax = CHAN_SES_PACKET_DEFAULT;
447 if (cctx->want_tty) {
452 nc = channel_new("session", SSH_CHANNEL_OPENING,
453 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
454 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
456 nc->ctl_chan = c->self; /* link session -> control channel */
457 c->remote_id = nc->self; /* link control -> session channel */
459 if (cctx->want_tty && escape_char != 0xffffffff) {
460 channel_register_filter(nc->self,
461 client_simple_escape_filter, NULL,
462 client_filter_cleanup,
463 client_new_escape_filter_ctx((int)escape_char));
466 debug2("%s: channel_new: %d linked to control channel %d",
467 __func__, nc->self, nc->ctl_chan);
469 channel_send_open(nc->self);
470 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
471 c->mux_pause = 1; /* stop handling messages until open_confirm done */
472 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
474 /* reply is deferred, sent by mux_session_confirm */
479 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
481 debug2("%s: channel %d: alive check", __func__, c->self);
484 buffer_put_int(r, MUX_S_ALIVE);
485 buffer_put_int(r, rid);
486 buffer_put_int(r, (u_int)getpid());
492 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
494 debug2("%s: channel %d: terminate request", __func__, c->self);
496 if (options.control_master == SSHCTL_MASTER_ASK ||
497 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
498 if (!ask_permission("Terminate shared connection to %s? ",
500 debug2("%s: termination refused by user", __func__);
501 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
502 buffer_put_int(r, rid);
503 buffer_put_cstring(r, "Permission denied");
509 buffer_put_int(r, MUX_S_OK);
510 buffer_put_int(r, rid);
511 /* XXX exit happens too soon - message never makes it to client */
516 format_forward(u_int ftype, struct Forward *fwd)
522 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
523 (fwd->listen_path != NULL) ? fwd->listen_path :
524 (fwd->listen_host == NULL) ?
525 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
526 fwd->listen_host, fwd->listen_port,
527 (fwd->connect_path != NULL) ? fwd->connect_path :
528 fwd->connect_host, fwd->connect_port);
530 case MUX_FWD_DYNAMIC:
531 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
532 (fwd->listen_host == NULL) ?
533 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
534 fwd->listen_host, fwd->listen_port);
537 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
538 (fwd->listen_path != NULL) ? fwd->listen_path :
539 (fwd->listen_host == NULL) ?
540 "LOCALHOST" : fwd->listen_host,
542 (fwd->connect_path != NULL) ? fwd->connect_path :
543 fwd->connect_host, fwd->connect_port);
546 fatal("%s: unknown forward type %u", __func__, ftype);
552 compare_host(const char *a, const char *b)
554 if (a == NULL && b == NULL)
556 if (a == NULL || b == NULL)
558 return strcmp(a, b) == 0;
562 compare_forward(struct Forward *a, struct Forward *b)
564 if (!compare_host(a->listen_host, b->listen_host))
566 if (!compare_host(a->listen_path, b->listen_path))
568 if (a->listen_port != b->listen_port)
570 if (!compare_host(a->connect_host, b->connect_host))
572 if (!compare_host(a->connect_path, b->connect_path))
574 if (a->connect_port != b->connect_port)
581 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
583 struct mux_channel_confirm_ctx *fctx = ctxt;
584 char *failmsg = NULL;
585 struct Forward *rfwd;
589 if ((c = channel_by_id(fctx->cid)) == NULL) {
590 /* no channel for reply */
591 error("%s: unknown channel", __func__);
595 if (fctx->fid >= options.num_remote_forwards ||
596 (options.remote_forwards[fctx->fid].connect_path == NULL &&
597 options.remote_forwards[fctx->fid].connect_host == NULL)) {
598 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
601 rfwd = &options.remote_forwards[fctx->fid];
602 debug("%s: %s for: listen %d, connect %s:%d", __func__,
603 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
604 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
605 rfwd->connect_host, rfwd->connect_port);
606 if (type == SSH2_MSG_REQUEST_SUCCESS) {
607 if (rfwd->listen_port == 0) {
608 rfwd->allocated_port = packet_get_int();
609 debug("Allocated port %u for mux remote forward"
610 " to %s:%d", rfwd->allocated_port,
611 rfwd->connect_host, rfwd->connect_port);
612 buffer_put_int(&out, MUX_S_REMOTE_PORT);
613 buffer_put_int(&out, fctx->rid);
614 buffer_put_int(&out, rfwd->allocated_port);
615 channel_update_permitted_opens(rfwd->handle,
616 rfwd->allocated_port);
618 buffer_put_int(&out, MUX_S_OK);
619 buffer_put_int(&out, fctx->rid);
623 if (rfwd->listen_port == 0)
624 channel_update_permitted_opens(rfwd->handle, -1);
625 if (rfwd->listen_path != NULL)
626 xasprintf(&failmsg, "remote port forwarding failed for "
627 "listen path %s", rfwd->listen_path);
629 xasprintf(&failmsg, "remote port forwarding failed for "
630 "listen port %d", rfwd->listen_port);
632 debug2("%s: clearing registered forwarding for listen %d, "
633 "connect %s:%d", __func__, rfwd->listen_port,
634 rfwd->connect_path ? rfwd->connect_path :
635 rfwd->connect_host, rfwd->connect_port);
637 free(rfwd->listen_host);
638 free(rfwd->listen_path);
639 free(rfwd->connect_host);
640 free(rfwd->connect_path);
641 memset(rfwd, 0, sizeof(*rfwd));
644 error("%s: %s", __func__, failmsg);
645 buffer_put_int(&out, MUX_S_FAILURE);
646 buffer_put_int(&out, fctx->rid);
647 buffer_put_cstring(&out, failmsg);
650 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
652 if (c->mux_pause <= 0)
653 fatal("%s: mux_pause %d", __func__, c->mux_pause);
654 c->mux_pause = 0; /* start processing messages again */
658 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
661 char *fwd_desc = NULL;
662 char *listen_addr, *connect_addr;
665 int i, ret = 0, freefwd = 1;
667 memset(&fwd, 0, sizeof(fwd));
669 /* XXX - lport/cport check redundant */
670 if (buffer_get_int_ret(&ftype, m) != 0 ||
671 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
672 buffer_get_int_ret(&lport, m) != 0 ||
673 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
674 buffer_get_int_ret(&cport, m) != 0 ||
675 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
676 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
677 error("%s: malformed message", __func__);
681 if (*listen_addr == '\0') {
685 if (*connect_addr == '\0') {
690 memset(&fwd, 0, sizeof(fwd));
691 fwd.listen_port = lport;
692 if (fwd.listen_port == PORT_STREAMLOCAL)
693 fwd.listen_path = listen_addr;
695 fwd.listen_host = listen_addr;
696 fwd.connect_port = cport;
697 if (fwd.connect_port == PORT_STREAMLOCAL)
698 fwd.connect_path = connect_addr;
700 fwd.connect_host = connect_addr;
702 debug2("%s: channel %d: request %s", __func__, c->self,
703 (fwd_desc = format_forward(ftype, &fwd)));
705 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
706 ftype != MUX_FWD_DYNAMIC) {
707 logit("%s: invalid forwarding type %u", __func__, ftype);
711 buffer_put_int(r, MUX_S_FAILURE);
712 buffer_put_int(r, rid);
713 buffer_put_cstring(r, "Invalid forwarding request");
716 if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
717 logit("%s: streamlocal and dynamic forwards "
718 "are mutually exclusive", __func__);
721 if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
722 logit("%s: invalid listen port %u", __func__,
726 if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
727 || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
728 logit("%s: invalid connect port %u", __func__,
732 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
733 logit("%s: missing connect host", __func__);
737 /* Skip forwards that have already been requested */
740 case MUX_FWD_DYNAMIC:
741 for (i = 0; i < options.num_local_forwards; i++) {
742 if (compare_forward(&fwd,
743 options.local_forwards + i)) {
745 debug2("%s: found existing forwarding",
747 buffer_put_int(r, MUX_S_OK);
748 buffer_put_int(r, rid);
754 for (i = 0; i < options.num_remote_forwards; i++) {
755 if (compare_forward(&fwd,
756 options.remote_forwards + i)) {
757 if (fwd.listen_port != 0)
759 debug2("%s: found allocated port",
761 buffer_put_int(r, MUX_S_REMOTE_PORT);
762 buffer_put_int(r, rid);
764 options.remote_forwards[i].allocated_port);
771 if (options.control_master == SSHCTL_MASTER_ASK ||
772 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
773 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
774 debug2("%s: forwarding refused by user", __func__);
775 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
776 buffer_put_int(r, rid);
777 buffer_put_cstring(r, "Permission denied");
782 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
783 if (!channel_setup_local_fwd_listener(&fwd,
784 &options.fwd_opts)) {
786 logit("slave-requested %s failed", fwd_desc);
787 buffer_put_int(r, MUX_S_FAILURE);
788 buffer_put_int(r, rid);
789 buffer_put_cstring(r, "Port forwarding failed");
792 add_local_forward(&options, &fwd);
795 struct mux_channel_confirm_ctx *fctx;
797 fwd.handle = channel_request_remote_forwarding(&fwd);
800 add_remote_forward(&options, &fwd);
801 fctx = xcalloc(1, sizeof(*fctx));
804 fctx->fid = options.num_remote_forwards - 1;
805 client_register_global_confirm(mux_confirm_remote_forward,
808 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
809 /* delayed reply in mux_confirm_remote_forward */
812 buffer_put_int(r, MUX_S_OK);
813 buffer_put_int(r, rid);
817 free(fwd.listen_host);
818 free(fwd.listen_path);
819 free(fwd.connect_host);
820 free(fwd.connect_path);
826 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
828 struct Forward fwd, *found_fwd;
829 char *fwd_desc = NULL;
830 const char *error_reason = NULL;
831 char *listen_addr = NULL, *connect_addr = NULL;
836 memset(&fwd, 0, sizeof(fwd));
838 if (buffer_get_int_ret(&ftype, m) != 0 ||
839 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
840 buffer_get_int_ret(&lport, m) != 0 ||
841 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
842 buffer_get_int_ret(&cport, m) != 0 ||
843 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
844 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
845 error("%s: malformed message", __func__);
850 if (*listen_addr == '\0') {
854 if (*connect_addr == '\0') {
859 memset(&fwd, 0, sizeof(fwd));
860 fwd.listen_port = lport;
861 if (fwd.listen_port == PORT_STREAMLOCAL)
862 fwd.listen_path = listen_addr;
864 fwd.listen_host = listen_addr;
865 fwd.connect_port = cport;
866 if (fwd.connect_port == PORT_STREAMLOCAL)
867 fwd.connect_path = connect_addr;
869 fwd.connect_host = connect_addr;
871 debug2("%s: channel %d: request cancel %s", __func__, c->self,
872 (fwd_desc = format_forward(ftype, &fwd)));
874 /* make sure this has been requested */
878 case MUX_FWD_DYNAMIC:
879 for (i = 0; i < options.num_local_forwards; i++) {
880 if (compare_forward(&fwd,
881 options.local_forwards + i)) {
882 found_fwd = options.local_forwards + i;
888 for (i = 0; i < options.num_remote_forwards; i++) {
889 if (compare_forward(&fwd,
890 options.remote_forwards + i)) {
891 found_fwd = options.remote_forwards + i;
898 if (found_fwd == NULL)
899 error_reason = "port not forwarded";
900 else if (ftype == MUX_FWD_REMOTE) {
902 * This shouldn't fail unless we confused the host/port
903 * between options.remote_forwards and permitted_opens.
904 * However, for dynamic allocated listen ports we need
905 * to use the actual listen port.
907 if (channel_request_rforward_cancel(found_fwd) == -1)
908 error_reason = "port not in permitted opens";
909 } else { /* local and dynamic forwards */
911 if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
912 &options.fwd_opts) == -1)
913 error_reason = "port not found";
916 if (error_reason == NULL) {
917 buffer_put_int(r, MUX_S_OK);
918 buffer_put_int(r, rid);
920 free(found_fwd->listen_host);
921 free(found_fwd->listen_path);
922 free(found_fwd->connect_host);
923 free(found_fwd->connect_path);
924 found_fwd->listen_host = found_fwd->connect_host = NULL;
925 found_fwd->listen_path = found_fwd->connect_path = NULL;
926 found_fwd->listen_port = found_fwd->connect_port = 0;
928 buffer_put_int(r, MUX_S_FAILURE);
929 buffer_put_int(r, rid);
930 buffer_put_cstring(r, error_reason);
941 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
944 char *reserved, *chost;
947 struct mux_stdio_confirm_ctx *cctx;
949 chost = reserved = NULL;
950 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
951 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
952 buffer_get_int_ret(&cport, m) != 0) {
955 error("%s: malformed message", __func__);
960 debug2("%s: channel %d: request stdio fwd to %s:%u",
961 __func__, c->self, chost, cport);
963 /* Gather fds from client */
964 for(i = 0; i < 2; i++) {
965 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
966 error("%s: failed to receive fd %d from slave",
968 for (j = 0; j < i; j++)
973 buffer_put_int(r, MUX_S_FAILURE);
974 buffer_put_int(r, rid);
975 buffer_put_cstring(r,
976 "did not receive file descriptors");
981 debug3("%s: got fds stdin %d, stdout %d", __func__,
982 new_fd[0], new_fd[1]);
984 /* XXX support multiple child sessions in future */
985 if (c->remote_id != -1) {
986 debug2("%s: session already open", __func__);
988 buffer_put_int(r, MUX_S_FAILURE);
989 buffer_put_int(r, rid);
990 buffer_put_cstring(r, "Multiple sessions not supported");
998 if (options.control_master == SSHCTL_MASTER_ASK ||
999 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1000 if (!ask_permission("Allow forward to %s:%u? ",
1002 debug2("%s: stdio fwd refused by user", __func__);
1004 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1005 buffer_put_int(r, rid);
1006 buffer_put_cstring(r, "Permission denied");
1011 /* enable nonblocking unless tty */
1012 if (!isatty(new_fd[0]))
1013 set_nonblock(new_fd[0]);
1014 if (!isatty(new_fd[1]))
1015 set_nonblock(new_fd[1]);
1017 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1019 nc->ctl_chan = c->self; /* link session -> control channel */
1020 c->remote_id = nc->self; /* link control -> session channel */
1022 debug2("%s: channel_new: %d linked to control channel %d",
1023 __func__, nc->self, nc->ctl_chan);
1025 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1027 cctx = xcalloc(1, sizeof(*cctx));
1029 channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1030 c->mux_pause = 1; /* stop handling messages until open_confirm done */
1032 /* reply is deferred, sent by mux_session_confirm */
1036 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1038 mux_stdio_confirm(int id, int success, void *arg)
1040 struct mux_stdio_confirm_ctx *cctx = arg;
1045 fatal("%s: cctx == NULL", __func__);
1046 if ((c = channel_by_id(id)) == NULL)
1047 fatal("%s: no channel for id %d", __func__, id);
1048 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1049 fatal("%s: channel %d lacks control channel %d", __func__,
1053 debug3("%s: sending failure reply", __func__);
1055 buffer_init(&reply);
1056 buffer_put_int(&reply, MUX_S_FAILURE);
1057 buffer_put_int(&reply, cctx->rid);
1058 buffer_put_cstring(&reply, "Session open refused by peer");
1062 debug3("%s: sending success reply", __func__);
1064 buffer_init(&reply);
1065 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1066 buffer_put_int(&reply, cctx->rid);
1067 buffer_put_int(&reply, c->self);
1071 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1072 buffer_free(&reply);
1074 if (cc->mux_pause <= 0)
1075 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1076 cc->mux_pause = 0; /* start processing messages again */
1077 c->open_confirm_ctx = NULL;
1082 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1084 debug("%s: channel %d: stop listening", __func__, c->self);
1086 if (options.control_master == SSHCTL_MASTER_ASK ||
1087 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1088 if (!ask_permission("Disable further multiplexing on shared "
1089 "connection to %s? ", host)) {
1090 debug2("%s: stop listen refused by user", __func__);
1091 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1092 buffer_put_int(r, rid);
1093 buffer_put_cstring(r, "Permission denied");
1098 if (mux_listener_channel != NULL) {
1099 channel_free(mux_listener_channel);
1101 free(options.control_path);
1102 options.control_path = NULL;
1103 mux_listener_channel = NULL;
1104 muxserver_sock = -1;
1108 buffer_put_int(r, MUX_S_OK);
1109 buffer_put_int(r, rid);
1114 /* Channel callbacks fired on read/write from mux slave fd */
1116 mux_master_read_cb(Channel *c)
1118 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1121 u_int type, rid, have, i;
1125 if (c->mux_ctx == NULL) {
1126 state = xcalloc(1, sizeof(*state));
1128 channel_register_cleanup(c->self,
1129 mux_master_control_cleanup_cb, 0);
1133 buffer_put_int(&out, MUX_MSG_HELLO);
1134 buffer_put_int(&out, SSHMUX_VER);
1136 buffer_put_string(&c->output, buffer_ptr(&out),
1139 debug3("%s: channel %d: hello sent", __func__, c->self);
1146 /* Channel code ensures that we receive whole packets */
1147 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1149 error("%s: malformed message", __func__);
1152 buffer_append(&in, ptr, have);
1154 if (buffer_get_int_ret(&type, &in) != 0)
1156 debug3("%s: channel %d packet type 0x%08x len %u",
1157 __func__, c->self, type, buffer_len(&in));
1159 if (type == MUX_MSG_HELLO)
1162 if (!state->hello_rcvd) {
1163 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1164 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1167 if (buffer_get_int_ret(&rid, &in) != 0)
1171 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1172 if (type == mux_master_handlers[i].type) {
1173 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1177 if (mux_master_handlers[i].handler == NULL) {
1178 error("%s: unsupported mux message 0x%08x", __func__, type);
1179 buffer_put_int(&out, MUX_S_FAILURE);
1180 buffer_put_int(&out, rid);
1181 buffer_put_cstring(&out, "unsupported request");
1184 /* Enqueue reply packet */
1185 if (buffer_len(&out) != 0) {
1186 buffer_put_string(&c->output, buffer_ptr(&out),
1196 mux_exit_message(Channel *c, int exitval)
1201 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1204 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1205 fatal("%s: channel %d missing mux channel %d",
1206 __func__, c->self, c->ctl_chan);
1208 /* Append exit message packet to control socket output queue */
1210 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1211 buffer_put_int(&m, c->self);
1212 buffer_put_int(&m, exitval);
1214 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1219 mux_tty_alloc_failed(Channel *c)
1224 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1226 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1227 fatal("%s: channel %d missing mux channel %d",
1228 __func__, c->self, c->ctl_chan);
1230 /* Append exit message packet to control socket output queue */
1232 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1233 buffer_put_int(&m, c->self);
1235 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1239 /* Prepare a mux master to listen on a Unix domain socket. */
1241 muxserver_listen(void)
1244 char *orig_control_path = options.control_path;
1249 if (options.control_path == NULL ||
1250 options.control_master == SSHCTL_MASTER_NO)
1253 debug("setting up multiplex master socket");
1256 * Use a temporary path before listen so we can pseudo-atomically
1257 * establish the listening socket in its final location to avoid
1258 * other processes racing in between bind() and listen() and hitting
1259 * an unready socket.
1261 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1262 r = arc4random_uniform(26+26+10);
1263 rbuf[i] = (r < 26) ? 'a' + r :
1264 (r < 26*2) ? 'A' + r - 26 :
1267 rbuf[sizeof(rbuf) - 1] = '\0';
1268 options.control_path = NULL;
1269 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1270 debug3("%s: temporary control path %s", __func__, options.control_path);
1272 old_umask = umask(0177);
1273 muxserver_sock = unix_listener(options.control_path, 64, 0);
1276 if (muxserver_sock < 0) {
1277 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1278 error("ControlSocket %s already exists, "
1279 "disabling multiplexing", options.control_path);
1281 if (muxserver_sock != -1) {
1282 close(muxserver_sock);
1283 muxserver_sock = -1;
1285 free(orig_control_path);
1286 free(options.control_path);
1287 options.control_path = NULL;
1288 options.control_master = SSHCTL_MASTER_NO;
1291 /* unix_listener() logs the error */
1296 /* Now atomically "move" the mux socket into position */
1297 if (link(options.control_path, orig_control_path) != 0) {
1298 if (errno != EEXIST) {
1299 fatal("%s: link mux listener %s => %s: %s", __func__,
1300 options.control_path, orig_control_path,
1303 error("ControlSocket %s already exists, disabling multiplexing",
1305 unlink(options.control_path);
1306 goto disable_mux_master;
1308 unlink(options.control_path);
1309 free(options.control_path);
1310 options.control_path = orig_control_path;
1312 set_nonblock(muxserver_sock);
1314 mux_listener_channel = channel_new("mux listener",
1315 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1316 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1317 0, options.control_path, 1);
1318 mux_listener_channel->mux_rcb = mux_master_read_cb;
1319 debug3("%s: mux listener channel %d fd %d", __func__,
1320 mux_listener_channel->self, mux_listener_channel->sock);
1323 /* Callback on open confirmation in mux master for a mux client session. */
1325 mux_session_confirm(int id, int success, void *arg)
1327 struct mux_session_confirm_ctx *cctx = arg;
1328 const char *display;
1334 fatal("%s: cctx == NULL", __func__);
1335 if ((c = channel_by_id(id)) == NULL)
1336 fatal("%s: no channel for id %d", __func__, id);
1337 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1338 fatal("%s: channel %d lacks control channel %d", __func__,
1342 debug3("%s: sending failure reply", __func__);
1344 buffer_init(&reply);
1345 buffer_put_int(&reply, MUX_S_FAILURE);
1346 buffer_put_int(&reply, cctx->rid);
1347 buffer_put_cstring(&reply, "Session open refused by peer");
1351 display = getenv("DISPLAY");
1352 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1355 /* Get reasonable local authentication information. */
1356 if (client_x11_get_proto(display, options.xauth_location,
1357 options.forward_x11_trusted, options.forward_x11_timeout,
1358 &proto, &data) == 0) {
1359 /* Request forwarding with authentication spoofing. */
1360 debug("Requesting X11 forwarding with authentication "
1362 x11_request_forwarding_with_spoofing(id, display, proto,
1364 /* XXX exit_on_forward_failure */
1365 client_expect_confirm(id, "X11 forwarding",
1370 if (cctx->want_agent_fwd && options.forward_agent) {
1371 debug("Requesting authentication agent forwarding.");
1372 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1376 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1377 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1379 debug3("%s: sending success reply", __func__);
1381 buffer_init(&reply);
1382 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1383 buffer_put_int(&reply, cctx->rid);
1384 buffer_put_int(&reply, c->self);
1388 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1389 buffer_free(&reply);
1391 if (cc->mux_pause <= 0)
1392 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1393 cc->mux_pause = 0; /* start processing messages again */
1394 c->open_confirm_ctx = NULL;
1395 buffer_free(&cctx->cmd);
1397 if (cctx->env != NULL) {
1398 for (i = 0; cctx->env[i] != NULL; i++)
1405 /* ** Multiplexing client support */
1407 /* Exit signal handler */
1409 control_client_sighandler(int signo)
1411 muxclient_terminate = signo;
1415 * Relay signal handler - used to pass some signals from mux client to
1419 control_client_sigrelay(int signo)
1421 int save_errno = errno;
1423 if (muxserver_pid > 1)
1424 kill(muxserver_pid, signo);
1430 mux_client_read(int fd, Buffer *b, u_int need)
1438 pfd.events = POLLIN;
1439 p = buffer_append_space(b, need);
1440 for (have = 0; have < need; ) {
1441 if (muxclient_terminate) {
1445 len = read(fd, p + have, need - have);
1448 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1452 (void)poll(&pfd, 1, -1);
1470 mux_client_write_packet(int fd, Buffer *m)
1479 pfd.events = POLLOUT;
1480 buffer_init(&queue);
1481 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1483 need = buffer_len(&queue);
1484 ptr = buffer_ptr(&queue);
1486 for (have = 0; have < need; ) {
1487 if (muxclient_terminate) {
1488 buffer_free(&queue);
1492 len = write(fd, ptr + have, need - have);
1495 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1499 (void)poll(&pfd, 1, -1);
1505 buffer_free(&queue);
1511 buffer_free(&queue);
1517 buffer_free(&queue);
1522 mux_client_read_packet(int fd, Buffer *m)
1529 buffer_init(&queue);
1530 if (mux_client_read(fd, &queue, 4) != 0) {
1531 if ((oerrno = errno) == EPIPE)
1532 debug3("%s: read header failed: %s", __func__,
1534 buffer_free(&queue);
1538 need = get_u32(buffer_ptr(&queue));
1539 if (mux_client_read(fd, &queue, need) != 0) {
1541 debug3("%s: read body failed: %s", __func__, strerror(errno));
1542 buffer_free(&queue);
1546 ptr = buffer_get_string_ptr(&queue, &have);
1547 buffer_append(m, ptr, have);
1548 buffer_free(&queue);
1553 mux_client_hello_exchange(int fd)
1559 buffer_put_int(&m, MUX_MSG_HELLO);
1560 buffer_put_int(&m, SSHMUX_VER);
1563 if (mux_client_write_packet(fd, &m) != 0)
1564 fatal("%s: write packet: %s", __func__, strerror(errno));
1568 /* Read their HELLO */
1569 if (mux_client_read_packet(fd, &m) != 0) {
1574 type = buffer_get_int(&m);
1575 if (type != MUX_MSG_HELLO)
1576 fatal("%s: expected HELLO (%u) received %u",
1577 __func__, MUX_MSG_HELLO, type);
1578 ver = buffer_get_int(&m);
1579 if (ver != SSHMUX_VER)
1580 fatal("Unsupported multiplexing protocol version %d "
1581 "(expected %d)", ver, SSHMUX_VER);
1582 debug2("%s: master version %u", __func__, ver);
1583 /* No extensions are presently defined */
1584 while (buffer_len(&m) > 0) {
1585 char *name = buffer_get_string(&m, NULL);
1586 char *value = buffer_get_string(&m, NULL);
1588 debug2("Unrecognised master extension \"%s\"", name);
1597 mux_client_request_alive(int fd)
1601 u_int pid, type, rid;
1603 debug3("%s: entering", __func__);
1606 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1607 buffer_put_int(&m, muxclient_request_id);
1609 if (mux_client_write_packet(fd, &m) != 0)
1610 fatal("%s: write packet: %s", __func__, strerror(errno));
1614 /* Read their reply */
1615 if (mux_client_read_packet(fd, &m) != 0) {
1620 type = buffer_get_int(&m);
1621 if (type != MUX_S_ALIVE) {
1622 e = buffer_get_string(&m, NULL);
1623 fatal("%s: master returned error: %s", __func__, e);
1626 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1627 fatal("%s: out of sequence reply: my id %u theirs %u",
1628 __func__, muxclient_request_id, rid);
1629 pid = buffer_get_int(&m);
1632 debug3("%s: done pid = %u", __func__, pid);
1634 muxclient_request_id++;
1640 mux_client_request_terminate(int fd)
1646 debug3("%s: entering", __func__);
1649 buffer_put_int(&m, MUX_C_TERMINATE);
1650 buffer_put_int(&m, muxclient_request_id);
1652 if (mux_client_write_packet(fd, &m) != 0)
1653 fatal("%s: write packet: %s", __func__, strerror(errno));
1657 /* Read their reply */
1658 if (mux_client_read_packet(fd, &m) != 0) {
1659 /* Remote end exited already */
1660 if (errno == EPIPE) {
1664 fatal("%s: read from master failed: %s",
1665 __func__, strerror(errno));
1668 type = buffer_get_int(&m);
1669 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1670 fatal("%s: out of sequence reply: my id %u theirs %u",
1671 __func__, muxclient_request_id, rid);
1675 case MUX_S_PERMISSION_DENIED:
1676 e = buffer_get_string(&m, NULL);
1677 fatal("Master refused termination request: %s", e);
1679 e = buffer_get_string(&m, NULL);
1680 fatal("%s: termination request failed: %s", __func__, e);
1682 fatal("%s: unexpected response from master 0x%08x",
1686 muxclient_request_id++;
1690 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1696 fwd_desc = format_forward(ftype, fwd);
1697 debug("Requesting %s %s",
1698 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1702 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1703 buffer_put_int(&m, muxclient_request_id);
1704 buffer_put_int(&m, ftype);
1705 if (fwd->listen_path != NULL) {
1706 buffer_put_cstring(&m, fwd->listen_path);
1708 buffer_put_cstring(&m,
1709 fwd->listen_host == NULL ? "" :
1710 (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1712 buffer_put_int(&m, fwd->listen_port);
1713 if (fwd->connect_path != NULL) {
1714 buffer_put_cstring(&m, fwd->connect_path);
1716 buffer_put_cstring(&m,
1717 fwd->connect_host == NULL ? "" : fwd->connect_host);
1719 buffer_put_int(&m, fwd->connect_port);
1721 if (mux_client_write_packet(fd, &m) != 0)
1722 fatal("%s: write packet: %s", __func__, strerror(errno));
1726 /* Read their reply */
1727 if (mux_client_read_packet(fd, &m) != 0) {
1732 type = buffer_get_int(&m);
1733 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1734 fatal("%s: out of sequence reply: my id %u theirs %u",
1735 __func__, muxclient_request_id, rid);
1739 case MUX_S_REMOTE_PORT:
1741 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1742 fwd->allocated_port = buffer_get_int(&m);
1743 verbose("Allocated port %u for remote forward to %s:%d",
1744 fwd->allocated_port,
1745 fwd->connect_host ? fwd->connect_host : "",
1747 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1748 fprintf(stdout, "%i\n", fwd->allocated_port);
1750 case MUX_S_PERMISSION_DENIED:
1751 e = buffer_get_string(&m, NULL);
1753 error("Master refused forwarding request: %s", e);
1756 e = buffer_get_string(&m, NULL);
1758 error("%s: forwarding request failed: %s", __func__, e);
1761 fatal("%s: unexpected response from master 0x%08x",
1766 muxclient_request_id++;
1771 mux_client_forwards(int fd, int cancel_flag)
1775 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1776 cancel_flag ? "cancel" : "request",
1777 options.num_local_forwards, options.num_remote_forwards);
1779 /* XXX ExitOnForwardingFailure */
1780 for (i = 0; i < options.num_local_forwards; i++) {
1781 if (mux_client_forward(fd, cancel_flag,
1782 options.local_forwards[i].connect_port == 0 ?
1783 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1784 options.local_forwards + i) != 0)
1787 for (i = 0; i < options.num_remote_forwards; i++) {
1788 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1789 options.remote_forwards + i) != 0)
1796 mux_client_request_session(int fd)
1800 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1801 extern char **environ;
1802 int devnull, rawmode;
1804 debug3("%s: entering", __func__);
1806 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1807 error("%s: master alive request failed", __func__);
1811 signal(SIGPIPE, SIG_IGN);
1813 if (stdin_null_flag) {
1814 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1815 fatal("open(/dev/null): %s", strerror(errno));
1816 if (dup2(devnull, STDIN_FILENO) == -1)
1817 fatal("dup2: %s", strerror(errno));
1818 if (devnull > STDERR_FILENO)
1822 term = getenv("TERM");
1825 buffer_put_int(&m, MUX_C_NEW_SESSION);
1826 buffer_put_int(&m, muxclient_request_id);
1827 buffer_put_cstring(&m, ""); /* reserved */
1828 buffer_put_int(&m, tty_flag);
1829 buffer_put_int(&m, options.forward_x11);
1830 buffer_put_int(&m, options.forward_agent);
1831 buffer_put_int(&m, subsystem_flag);
1832 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1833 0xffffffff : (u_int)options.escape_char);
1834 buffer_put_cstring(&m, term == NULL ? "" : term);
1835 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1837 if (options.num_send_env > 0 && environ != NULL) {
1838 /* Pass environment */
1839 for (i = 0; environ[i] != NULL; i++) {
1840 if (env_permitted(environ[i])) {
1841 buffer_put_cstring(&m, environ[i]);
1846 if (mux_client_write_packet(fd, &m) != 0)
1847 fatal("%s: write packet: %s", __func__, strerror(errno));
1849 /* Send the stdio file descriptors */
1850 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1851 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1852 mm_send_fd(fd, STDERR_FILENO) == -1)
1853 fatal("%s: send fds failed", __func__);
1855 debug3("%s: session request sent", __func__);
1857 /* Read their reply */
1859 if (mux_client_read_packet(fd, &m) != 0) {
1860 error("%s: read from master failed: %s",
1861 __func__, strerror(errno));
1866 type = buffer_get_int(&m);
1867 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1868 fatal("%s: out of sequence reply: my id %u theirs %u",
1869 __func__, muxclient_request_id, rid);
1871 case MUX_S_SESSION_OPENED:
1872 sid = buffer_get_int(&m);
1873 debug("%s: master session id: %u", __func__, sid);
1875 case MUX_S_PERMISSION_DENIED:
1876 e = buffer_get_string(&m, NULL);
1878 error("Master refused session request: %s", e);
1881 e = buffer_get_string(&m, NULL);
1883 error("%s: session request failed: %s", __func__, e);
1887 error("%s: unexpected response from master 0x%08x",
1891 muxclient_request_id++;
1893 if (pledge("stdio proc tty", NULL) == -1)
1894 fatal("%s pledge(): %s", __func__, strerror(errno));
1895 platform_pledge_mux();
1897 signal(SIGHUP, control_client_sighandler);
1898 signal(SIGINT, control_client_sighandler);
1899 signal(SIGTERM, control_client_sighandler);
1900 signal(SIGWINCH, control_client_sigrelay);
1904 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1907 * Stick around until the controlee closes the client_fd.
1908 * Before it does, it is expected to write an exit message.
1909 * This process must read the value and wait for the closure of
1910 * the client_fd; if this one closes early, the multiplex master will
1911 * terminate early too (possibly losing data).
1913 for (exitval = 255, exitval_seen = 0;;) {
1915 if (mux_client_read_packet(fd, &m) != 0)
1917 type = buffer_get_int(&m);
1919 case MUX_S_TTY_ALLOC_FAIL:
1920 if ((esid = buffer_get_int(&m)) != sid)
1921 fatal("%s: tty alloc fail on unknown session: "
1922 "my id %u theirs %u",
1923 __func__, sid, esid);
1924 leave_raw_mode(options.request_tty ==
1928 case MUX_S_EXIT_MESSAGE:
1929 if ((esid = buffer_get_int(&m)) != sid)
1930 fatal("%s: exit on unknown session: "
1931 "my id %u theirs %u",
1932 __func__, sid, esid);
1934 fatal("%s: exitval sent twice", __func__);
1935 exitval = buffer_get_int(&m);
1939 e = buffer_get_string(&m, NULL);
1940 fatal("%s: master returned error: %s", __func__, e);
1946 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1948 if (muxclient_terminate) {
1949 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1951 } else if (!exitval_seen) {
1952 debug2("Control master terminated unexpectedly");
1955 debug2("Received exit status from master %d", exitval);
1957 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1958 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1964 mux_client_request_stdio_fwd(int fd)
1968 u_int type, rid, sid;
1971 debug3("%s: entering", __func__);
1973 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1974 error("%s: master alive request failed", __func__);
1978 signal(SIGPIPE, SIG_IGN);
1980 if (stdin_null_flag) {
1981 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1982 fatal("open(/dev/null): %s", strerror(errno));
1983 if (dup2(devnull, STDIN_FILENO) == -1)
1984 fatal("dup2: %s", strerror(errno));
1985 if (devnull > STDERR_FILENO)
1990 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1991 buffer_put_int(&m, muxclient_request_id);
1992 buffer_put_cstring(&m, ""); /* reserved */
1993 buffer_put_cstring(&m, options.stdio_forward_host);
1994 buffer_put_int(&m, options.stdio_forward_port);
1996 if (mux_client_write_packet(fd, &m) != 0)
1997 fatal("%s: write packet: %s", __func__, strerror(errno));
1999 /* Send the stdio file descriptors */
2000 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
2001 mm_send_fd(fd, STDOUT_FILENO) == -1)
2002 fatal("%s: send fds failed", __func__);
2004 if (pledge("stdio proc tty", NULL) == -1)
2005 fatal("%s pledge(): %s", __func__, strerror(errno));
2006 platform_pledge_mux();
2008 debug3("%s: stdio forward request sent", __func__);
2010 /* Read their reply */
2013 if (mux_client_read_packet(fd, &m) != 0) {
2014 error("%s: read from master failed: %s",
2015 __func__, strerror(errno));
2020 type = buffer_get_int(&m);
2021 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2022 fatal("%s: out of sequence reply: my id %u theirs %u",
2023 __func__, muxclient_request_id, rid);
2025 case MUX_S_SESSION_OPENED:
2026 sid = buffer_get_int(&m);
2027 debug("%s: master session id: %u", __func__, sid);
2029 case MUX_S_PERMISSION_DENIED:
2030 e = buffer_get_string(&m, NULL);
2032 fatal("Master refused stdio forwarding request: %s", e);
2034 e = buffer_get_string(&m, NULL);
2036 fatal("Stdio forwarding request failed: %s", e);
2039 error("%s: unexpected response from master 0x%08x",
2043 muxclient_request_id++;
2045 signal(SIGHUP, control_client_sighandler);
2046 signal(SIGINT, control_client_sighandler);
2047 signal(SIGTERM, control_client_sighandler);
2048 signal(SIGWINCH, control_client_sigrelay);
2051 * Stick around until the controlee closes the client_fd.
2054 if (mux_client_read_packet(fd, &m) != 0) {
2055 if (errno == EPIPE ||
2056 (errno == EINTR && muxclient_terminate != 0))
2058 fatal("%s: mux_client_read_packet: %s",
2059 __func__, strerror(errno));
2061 fatal("%s: master returned unexpected message %u", __func__, type);
2065 mux_client_request_stop_listening(int fd)
2071 debug3("%s: entering", __func__);
2074 buffer_put_int(&m, MUX_C_STOP_LISTENING);
2075 buffer_put_int(&m, muxclient_request_id);
2077 if (mux_client_write_packet(fd, &m) != 0)
2078 fatal("%s: write packet: %s", __func__, strerror(errno));
2082 /* Read their reply */
2083 if (mux_client_read_packet(fd, &m) != 0)
2084 fatal("%s: read from master failed: %s",
2085 __func__, strerror(errno));
2087 type = buffer_get_int(&m);
2088 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2089 fatal("%s: out of sequence reply: my id %u theirs %u",
2090 __func__, muxclient_request_id, rid);
2094 case MUX_S_PERMISSION_DENIED:
2095 e = buffer_get_string(&m, NULL);
2096 fatal("Master refused stop listening request: %s", e);
2098 e = buffer_get_string(&m, NULL);
2099 fatal("%s: stop listening request failed: %s", __func__, e);
2101 fatal("%s: unexpected response from master 0x%08x",
2105 muxclient_request_id++;
2108 /* Multiplex client main loop. */
2110 muxclient(const char *path)
2112 struct sockaddr_un addr;
2117 if (muxclient_command == 0) {
2118 if (options.stdio_forward_host != NULL)
2119 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2121 muxclient_command = SSHMUX_COMMAND_OPEN;
2124 switch (options.control_master) {
2125 case SSHCTL_MASTER_AUTO:
2126 case SSHCTL_MASTER_AUTO_ASK:
2127 debug("auto-mux: Trying existing master");
2129 case SSHCTL_MASTER_NO:
2135 memset(&addr, '\0', sizeof(addr));
2136 addr.sun_family = AF_UNIX;
2137 sun_len = offsetof(struct sockaddr_un, sun_path) +
2140 if (strlcpy(addr.sun_path, path,
2141 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2142 fatal("ControlPath too long");
2144 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2145 fatal("%s socket(): %s", __func__, strerror(errno));
2147 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2148 switch (muxclient_command) {
2149 case SSHMUX_COMMAND_OPEN:
2150 case SSHMUX_COMMAND_STDIO_FWD:
2153 fatal("Control socket connect(%.100s): %s", path,
2156 if (errno == ECONNREFUSED &&
2157 options.control_master != SSHCTL_MASTER_NO) {
2158 debug("Stale control socket %.100s, unlinking", path);
2160 } else if (errno == ENOENT) {
2161 debug("Control socket \"%.100s\" does not exist", path);
2163 error("Control socket connect(%.100s): %s", path,
2171 if (mux_client_hello_exchange(sock) != 0) {
2172 error("%s: master hello exchange failed", __func__);
2177 switch (muxclient_command) {
2178 case SSHMUX_COMMAND_ALIVE_CHECK:
2179 if ((pid = mux_client_request_alive(sock)) == 0)
2180 fatal("%s: master alive check failed", __func__);
2181 fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2183 case SSHMUX_COMMAND_TERMINATE:
2184 mux_client_request_terminate(sock);
2185 fprintf(stderr, "Exit request sent.\r\n");
2187 case SSHMUX_COMMAND_FORWARD:
2188 if (mux_client_forwards(sock, 0) != 0)
2189 fatal("%s: master forward request failed", __func__);
2191 case SSHMUX_COMMAND_OPEN:
2192 if (mux_client_forwards(sock, 0) != 0) {
2193 error("%s: master forward request failed", __func__);
2196 mux_client_request_session(sock);
2198 case SSHMUX_COMMAND_STDIO_FWD:
2199 mux_client_request_stdio_fwd(sock);
2201 case SSHMUX_COMMAND_STOP:
2202 mux_client_request_stop_listening(sock);
2203 fprintf(stderr, "Stop listening request sent.\r\n");
2205 case SSHMUX_COMMAND_CANCEL_FWD:
2206 if (mux_client_forwards(sock, 1) != 0)
2207 error("%s: master cancel forward request failed",
2211 fatal("unrecognised muxclient_command %d", muxclient_command);