1 /* $OpenBSD: mux.c,v 1.69 2017/09/20 05:19:00 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"
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(struct ssh *, int, int, void *);
166 static void mux_stdio_confirm(struct ssh *, int, int, void *);
168 static int process_mux_master_hello(struct ssh *, u_int,
169 Channel *, struct sshbuf *, struct sshbuf *);
170 static int process_mux_new_session(struct ssh *, u_int,
171 Channel *, struct sshbuf *, struct sshbuf *);
172 static int process_mux_alive_check(struct ssh *, u_int,
173 Channel *, struct sshbuf *, struct sshbuf *);
174 static int process_mux_terminate(struct ssh *, u_int,
175 Channel *, struct sshbuf *, struct sshbuf *);
176 static int process_mux_open_fwd(struct ssh *, u_int,
177 Channel *, struct sshbuf *, struct sshbuf *);
178 static int process_mux_close_fwd(struct ssh *, u_int,
179 Channel *, struct sshbuf *, struct sshbuf *);
180 static int process_mux_stdio_fwd(struct ssh *, u_int,
181 Channel *, struct sshbuf *, struct sshbuf *);
182 static int process_mux_stop_listening(struct ssh *, u_int,
183 Channel *, struct sshbuf *, struct sshbuf *);
184 static int process_mux_proxy(struct ssh *, u_int,
185 Channel *, struct sshbuf *, struct sshbuf *);
187 static const struct {
189 int (*handler)(struct ssh *, u_int, Channel *,
190 struct sshbuf *, struct sshbuf *);
191 } mux_master_handlers[] = {
192 { MUX_MSG_HELLO, process_mux_master_hello },
193 { MUX_C_NEW_SESSION, process_mux_new_session },
194 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
195 { MUX_C_TERMINATE, process_mux_terminate },
196 { MUX_C_OPEN_FWD, process_mux_open_fwd },
197 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
198 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
199 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
200 { MUX_C_PROXY, process_mux_proxy },
204 /* Cleanup callback fired on closure of mux slave _session_ channel */
207 mux_master_session_cleanup_cb(struct ssh *ssh, int cid, void *unused)
209 Channel *cc, *c = channel_by_id(ssh, cid);
211 debug3("%s: entering for channel %d", __func__, cid);
213 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
214 if (c->ctl_chan != -1) {
215 if ((cc = channel_by_id(ssh, c->ctl_chan)) == NULL)
216 fatal("%s: channel %d missing control channel %d",
217 __func__, c->self, c->ctl_chan);
220 cc->have_remote_id = 0;
221 chan_rcvd_oclose(ssh, cc);
223 channel_cancel_cleanup(ssh, c->self);
226 /* Cleanup callback fired on closure of mux slave _control_ channel */
229 mux_master_control_cleanup_cb(struct ssh *ssh, int cid, void *unused)
231 Channel *sc, *c = channel_by_id(ssh, cid);
233 debug3("%s: entering for channel %d", __func__, cid);
235 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
236 if (c->have_remote_id) {
237 if ((sc = channel_by_id(ssh, c->remote_id)) == NULL)
238 fatal("%s: channel %d missing session channel %u",
239 __func__, c->self, c->remote_id);
241 c->have_remote_id = 0;
243 if (sc->type != SSH_CHANNEL_OPEN &&
244 sc->type != SSH_CHANNEL_OPENING) {
245 debug2("%s: channel %d: not open", __func__, sc->self);
246 chan_mark_dead(ssh, sc);
248 if (sc->istate == CHAN_INPUT_OPEN)
249 chan_read_failed(ssh, sc);
250 if (sc->ostate == CHAN_OUTPUT_OPEN)
251 chan_write_failed(ssh, sc);
254 channel_cancel_cleanup(ssh, c->self);
257 /* Check mux client environment variables before passing them to mux master. */
259 env_permitted(char *env)
262 char name[1024], *cp;
264 if ((cp = strchr(env, '=')) == NULL || cp == env)
266 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
267 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
268 error("env_permitted: name '%.100s...' too long", env);
272 for (i = 0; i < options.num_send_env; i++)
273 if (match_pattern(name, options.send_env[i]))
279 /* Mux master protocol message handlers */
282 process_mux_master_hello(struct ssh *ssh, u_int rid,
283 Channel *c, Buffer *m, Buffer *r)
286 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
289 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
290 if (state->hello_rcvd) {
291 error("%s: HELLO received twice", __func__);
294 if (buffer_get_int_ret(&ver, m) != 0) {
296 error("%s: malformed message", __func__);
299 if (ver != SSHMUX_VER) {
300 error("Unsupported multiplexing protocol version %d "
301 "(expected %d)", ver, SSHMUX_VER);
304 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
306 /* No extensions are presently defined */
307 while (buffer_len(m) > 0) {
308 char *name = buffer_get_string_ret(m, NULL);
309 char *value = buffer_get_string_ret(m, NULL);
311 if (name == NULL || value == NULL) {
316 debug2("Unrecognised slave extension \"%s\"", name);
320 state->hello_rcvd = 1;
325 process_mux_new_session(struct ssh *ssh, u_int rid,
326 Channel *c, Buffer *m, Buffer *r)
329 struct mux_session_confirm_ctx *cctx;
330 char *reserved, *cmd, *cp;
331 u_int i, j, len, env_len, escape_char, window, packetmax;
334 /* Reply for SSHMUX_COMMAND_OPEN */
335 cctx = xcalloc(1, sizeof(*cctx));
338 cmd = reserved = NULL;
341 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
342 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
343 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
344 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
345 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
346 buffer_get_int_ret(&escape_char, m) != 0 ||
347 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
348 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
352 for (j = 0; j < env_len; j++)
357 error("%s: malformed message", __func__);
363 while (buffer_len(m) > 0) {
364 #define MUX_MAX_ENV_VARS 4096
365 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
367 if (!env_permitted(cp)) {
371 cctx->env = xreallocarray(cctx->env, env_len + 2,
373 cctx->env[env_len++] = cp;
374 cctx->env[env_len] = NULL;
375 if (env_len > MUX_MAX_ENV_VARS) {
376 error(">%d environment variables received, ignoring "
377 "additional", MUX_MAX_ENV_VARS);
382 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
383 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
384 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
385 cctx->want_subsys, cctx->term, cmd, env_len);
387 buffer_init(&cctx->cmd);
388 buffer_append(&cctx->cmd, cmd, strlen(cmd));
392 /* Gather fds from client */
393 for(i = 0; i < 3; i++) {
394 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
395 error("%s: failed to receive fd %d from slave",
397 for (j = 0; j < i; j++)
399 for (j = 0; j < env_len; j++)
403 buffer_free(&cctx->cmd);
407 buffer_put_int(r, MUX_S_FAILURE);
408 buffer_put_int(r, rid);
409 buffer_put_cstring(r,
410 "did not receive file descriptors");
415 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
416 new_fd[0], new_fd[1], new_fd[2]);
418 /* XXX support multiple child sessions in future */
419 if (c->have_remote_id) {
420 debug2("%s: session already open", __func__);
422 buffer_put_int(r, MUX_S_FAILURE);
423 buffer_put_int(r, rid);
424 buffer_put_cstring(r, "Multiple sessions not supported");
431 for (i = 0; i < env_len; i++)
435 buffer_free(&cctx->cmd);
440 if (options.control_master == SSHCTL_MASTER_ASK ||
441 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
442 if (!ask_permission("Allow shared connection to %s? ", host)) {
443 debug2("%s: session refused by user", __func__);
445 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
446 buffer_put_int(r, rid);
447 buffer_put_cstring(r, "Permission denied");
452 /* Try to pick up ttymodes from client before it goes raw */
453 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
454 error("%s: tcgetattr: %s", __func__, strerror(errno));
456 /* enable nonblocking unless tty */
457 if (!isatty(new_fd[0]))
458 set_nonblock(new_fd[0]);
459 if (!isatty(new_fd[1]))
460 set_nonblock(new_fd[1]);
461 if (!isatty(new_fd[2]))
462 set_nonblock(new_fd[2]);
464 window = CHAN_SES_WINDOW_DEFAULT;
465 packetmax = CHAN_SES_PACKET_DEFAULT;
466 if (cctx->want_tty) {
471 nc = channel_new(ssh, "session", SSH_CHANNEL_OPENING,
472 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
473 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
475 nc->ctl_chan = c->self; /* link session -> control channel */
476 c->remote_id = nc->self; /* link control -> session channel */
477 c->have_remote_id = 1;
479 if (cctx->want_tty && escape_char != 0xffffffff) {
480 channel_register_filter(ssh, nc->self,
481 client_simple_escape_filter, NULL,
482 client_filter_cleanup,
483 client_new_escape_filter_ctx((int)escape_char));
486 debug2("%s: channel_new: %d linked to control channel %d",
487 __func__, nc->self, nc->ctl_chan);
489 channel_send_open(ssh, nc->self);
490 channel_register_open_confirm(ssh, nc->self, mux_session_confirm, cctx);
491 c->mux_pause = 1; /* stop handling messages until open_confirm done */
492 channel_register_cleanup(ssh, nc->self,
493 mux_master_session_cleanup_cb, 1);
495 /* reply is deferred, sent by mux_session_confirm */
500 process_mux_alive_check(struct ssh *ssh, u_int rid,
501 Channel *c, Buffer *m, Buffer *r)
503 debug2("%s: channel %d: alive check", __func__, c->self);
506 buffer_put_int(r, MUX_S_ALIVE);
507 buffer_put_int(r, rid);
508 buffer_put_int(r, (u_int)getpid());
514 process_mux_terminate(struct ssh *ssh, u_int rid,
515 Channel *c, Buffer *m, Buffer *r)
517 debug2("%s: channel %d: terminate request", __func__, c->self);
519 if (options.control_master == SSHCTL_MASTER_ASK ||
520 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
521 if (!ask_permission("Terminate shared connection to %s? ",
523 debug2("%s: termination refused by user", __func__);
524 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
525 buffer_put_int(r, rid);
526 buffer_put_cstring(r, "Permission denied");
532 buffer_put_int(r, MUX_S_OK);
533 buffer_put_int(r, rid);
534 /* XXX exit happens too soon - message never makes it to client */
539 format_forward(u_int ftype, struct Forward *fwd)
545 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
546 (fwd->listen_path != NULL) ? fwd->listen_path :
547 (fwd->listen_host == NULL) ?
548 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
549 fwd->listen_host, fwd->listen_port,
550 (fwd->connect_path != NULL) ? fwd->connect_path :
551 fwd->connect_host, fwd->connect_port);
553 case MUX_FWD_DYNAMIC:
554 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
555 (fwd->listen_host == NULL) ?
556 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
557 fwd->listen_host, fwd->listen_port);
560 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
561 (fwd->listen_path != NULL) ? fwd->listen_path :
562 (fwd->listen_host == NULL) ?
563 "LOCALHOST" : fwd->listen_host,
565 (fwd->connect_path != NULL) ? fwd->connect_path :
566 fwd->connect_host, fwd->connect_port);
569 fatal("%s: unknown forward type %u", __func__, ftype);
575 compare_host(const char *a, const char *b)
577 if (a == NULL && b == NULL)
579 if (a == NULL || b == NULL)
581 return strcmp(a, b) == 0;
585 compare_forward(struct Forward *a, struct Forward *b)
587 if (!compare_host(a->listen_host, b->listen_host))
589 if (!compare_host(a->listen_path, b->listen_path))
591 if (a->listen_port != b->listen_port)
593 if (!compare_host(a->connect_host, b->connect_host))
595 if (!compare_host(a->connect_path, b->connect_path))
597 if (a->connect_port != b->connect_port)
604 mux_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
606 struct mux_channel_confirm_ctx *fctx = ctxt;
607 char *failmsg = NULL;
608 struct Forward *rfwd;
612 if ((c = channel_by_id(ssh, fctx->cid)) == NULL) {
613 /* no channel for reply */
614 error("%s: unknown channel", __func__);
618 if (fctx->fid >= options.num_remote_forwards ||
619 (options.remote_forwards[fctx->fid].connect_path == NULL &&
620 options.remote_forwards[fctx->fid].connect_host == NULL)) {
621 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
624 rfwd = &options.remote_forwards[fctx->fid];
625 debug("%s: %s for: listen %d, connect %s:%d", __func__,
626 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
627 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
628 rfwd->connect_host, rfwd->connect_port);
629 if (type == SSH2_MSG_REQUEST_SUCCESS) {
630 if (rfwd->listen_port == 0) {
631 rfwd->allocated_port = packet_get_int();
632 debug("Allocated port %u for mux remote forward"
633 " to %s:%d", rfwd->allocated_port,
634 rfwd->connect_host, rfwd->connect_port);
635 buffer_put_int(&out, MUX_S_REMOTE_PORT);
636 buffer_put_int(&out, fctx->rid);
637 buffer_put_int(&out, rfwd->allocated_port);
638 channel_update_permitted_opens(ssh, rfwd->handle,
639 rfwd->allocated_port);
641 buffer_put_int(&out, MUX_S_OK);
642 buffer_put_int(&out, fctx->rid);
646 if (rfwd->listen_port == 0)
647 channel_update_permitted_opens(ssh, rfwd->handle, -1);
648 if (rfwd->listen_path != NULL)
649 xasprintf(&failmsg, "remote port forwarding failed for "
650 "listen path %s", rfwd->listen_path);
652 xasprintf(&failmsg, "remote port forwarding failed for "
653 "listen port %d", rfwd->listen_port);
655 debug2("%s: clearing registered forwarding for listen %d, "
656 "connect %s:%d", __func__, rfwd->listen_port,
657 rfwd->connect_path ? rfwd->connect_path :
658 rfwd->connect_host, rfwd->connect_port);
660 free(rfwd->listen_host);
661 free(rfwd->listen_path);
662 free(rfwd->connect_host);
663 free(rfwd->connect_path);
664 memset(rfwd, 0, sizeof(*rfwd));
667 error("%s: %s", __func__, failmsg);
668 buffer_put_int(&out, MUX_S_FAILURE);
669 buffer_put_int(&out, fctx->rid);
670 buffer_put_cstring(&out, failmsg);
673 buffer_put_string(c->output, buffer_ptr(&out), buffer_len(&out));
675 if (c->mux_pause <= 0)
676 fatal("%s: mux_pause %d", __func__, c->mux_pause);
677 c->mux_pause = 0; /* start processing messages again */
681 process_mux_open_fwd(struct ssh *ssh, u_int rid,
682 Channel *c, Buffer *m, Buffer *r)
685 char *fwd_desc = NULL;
686 char *listen_addr, *connect_addr;
689 int i, ret = 0, freefwd = 1;
691 memset(&fwd, 0, sizeof(fwd));
693 /* XXX - lport/cport check redundant */
694 if (buffer_get_int_ret(&ftype, m) != 0 ||
695 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
696 buffer_get_int_ret(&lport, m) != 0 ||
697 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
698 buffer_get_int_ret(&cport, m) != 0 ||
699 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
700 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
701 error("%s: malformed message", __func__);
705 if (*listen_addr == '\0') {
709 if (*connect_addr == '\0') {
714 memset(&fwd, 0, sizeof(fwd));
715 fwd.listen_port = lport;
716 if (fwd.listen_port == PORT_STREAMLOCAL)
717 fwd.listen_path = listen_addr;
719 fwd.listen_host = listen_addr;
720 fwd.connect_port = cport;
721 if (fwd.connect_port == PORT_STREAMLOCAL)
722 fwd.connect_path = connect_addr;
724 fwd.connect_host = connect_addr;
726 debug2("%s: channel %d: request %s", __func__, c->self,
727 (fwd_desc = format_forward(ftype, &fwd)));
729 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
730 ftype != MUX_FWD_DYNAMIC) {
731 logit("%s: invalid forwarding type %u", __func__, ftype);
735 buffer_put_int(r, MUX_S_FAILURE);
736 buffer_put_int(r, rid);
737 buffer_put_cstring(r, "Invalid forwarding request");
740 if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
741 logit("%s: streamlocal and dynamic forwards "
742 "are mutually exclusive", __func__);
745 if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
746 logit("%s: invalid listen port %u", __func__,
750 if ((fwd.connect_port != PORT_STREAMLOCAL &&
751 fwd.connect_port >= 65536) ||
752 (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE &&
753 fwd.connect_port == 0)) {
754 logit("%s: invalid connect port %u", __func__,
758 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL &&
759 fwd.connect_path == NULL) {
760 logit("%s: missing connect host", __func__);
764 /* Skip forwards that have already been requested */
767 case MUX_FWD_DYNAMIC:
768 for (i = 0; i < options.num_local_forwards; i++) {
769 if (compare_forward(&fwd,
770 options.local_forwards + i)) {
772 debug2("%s: found existing forwarding",
774 buffer_put_int(r, MUX_S_OK);
775 buffer_put_int(r, rid);
781 for (i = 0; i < options.num_remote_forwards; i++) {
782 if (compare_forward(&fwd,
783 options.remote_forwards + i)) {
784 if (fwd.listen_port != 0)
786 debug2("%s: found allocated port",
788 buffer_put_int(r, MUX_S_REMOTE_PORT);
789 buffer_put_int(r, rid);
791 options.remote_forwards[i].allocated_port);
798 if (options.control_master == SSHCTL_MASTER_ASK ||
799 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
800 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
801 debug2("%s: forwarding refused by user", __func__);
802 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
803 buffer_put_int(r, rid);
804 buffer_put_cstring(r, "Permission denied");
809 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
810 if (!channel_setup_local_fwd_listener(ssh, &fwd,
811 &options.fwd_opts)) {
813 logit("slave-requested %s failed", fwd_desc);
814 buffer_put_int(r, MUX_S_FAILURE);
815 buffer_put_int(r, rid);
816 buffer_put_cstring(r, "Port forwarding failed");
819 add_local_forward(&options, &fwd);
822 struct mux_channel_confirm_ctx *fctx;
824 fwd.handle = channel_request_remote_forwarding(ssh, &fwd);
827 add_remote_forward(&options, &fwd);
828 fctx = xcalloc(1, sizeof(*fctx));
831 fctx->fid = options.num_remote_forwards - 1;
832 client_register_global_confirm(mux_confirm_remote_forward,
835 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
836 /* delayed reply in mux_confirm_remote_forward */
839 buffer_put_int(r, MUX_S_OK);
840 buffer_put_int(r, rid);
844 free(fwd.listen_host);
845 free(fwd.listen_path);
846 free(fwd.connect_host);
847 free(fwd.connect_path);
853 process_mux_close_fwd(struct ssh *ssh, u_int rid,
854 Channel *c, Buffer *m, Buffer *r)
856 struct Forward fwd, *found_fwd;
857 char *fwd_desc = NULL;
858 const char *error_reason = NULL;
859 char *listen_addr = NULL, *connect_addr = NULL;
864 memset(&fwd, 0, sizeof(fwd));
866 if (buffer_get_int_ret(&ftype, m) != 0 ||
867 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
868 buffer_get_int_ret(&lport, m) != 0 ||
869 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
870 buffer_get_int_ret(&cport, m) != 0 ||
871 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
872 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
873 error("%s: malformed message", __func__);
878 if (*listen_addr == '\0') {
882 if (*connect_addr == '\0') {
887 memset(&fwd, 0, sizeof(fwd));
888 fwd.listen_port = lport;
889 if (fwd.listen_port == PORT_STREAMLOCAL)
890 fwd.listen_path = listen_addr;
892 fwd.listen_host = listen_addr;
893 fwd.connect_port = cport;
894 if (fwd.connect_port == PORT_STREAMLOCAL)
895 fwd.connect_path = connect_addr;
897 fwd.connect_host = connect_addr;
899 debug2("%s: channel %d: request cancel %s", __func__, c->self,
900 (fwd_desc = format_forward(ftype, &fwd)));
902 /* make sure this has been requested */
906 case MUX_FWD_DYNAMIC:
907 for (i = 0; i < options.num_local_forwards; i++) {
908 if (compare_forward(&fwd,
909 options.local_forwards + i)) {
910 found_fwd = options.local_forwards + i;
916 for (i = 0; i < options.num_remote_forwards; i++) {
917 if (compare_forward(&fwd,
918 options.remote_forwards + i)) {
919 found_fwd = options.remote_forwards + i;
926 if (found_fwd == NULL)
927 error_reason = "port not forwarded";
928 else if (ftype == MUX_FWD_REMOTE) {
930 * This shouldn't fail unless we confused the host/port
931 * between options.remote_forwards and permitted_opens.
932 * However, for dynamic allocated listen ports we need
933 * to use the actual listen port.
935 if (channel_request_rforward_cancel(ssh, found_fwd) == -1)
936 error_reason = "port not in permitted opens";
937 } else { /* local and dynamic forwards */
939 if (channel_cancel_lport_listener(ssh, &fwd, fwd.connect_port,
940 &options.fwd_opts) == -1)
941 error_reason = "port not found";
944 if (error_reason == NULL) {
945 buffer_put_int(r, MUX_S_OK);
946 buffer_put_int(r, rid);
948 free(found_fwd->listen_host);
949 free(found_fwd->listen_path);
950 free(found_fwd->connect_host);
951 free(found_fwd->connect_path);
952 found_fwd->listen_host = found_fwd->connect_host = NULL;
953 found_fwd->listen_path = found_fwd->connect_path = NULL;
954 found_fwd->listen_port = found_fwd->connect_port = 0;
956 buffer_put_int(r, MUX_S_FAILURE);
957 buffer_put_int(r, rid);
958 buffer_put_cstring(r, error_reason);
969 process_mux_stdio_fwd(struct ssh *ssh, u_int rid,
970 Channel *c, Buffer *m, Buffer *r)
973 char *reserved, *chost;
976 struct mux_stdio_confirm_ctx *cctx;
978 chost = reserved = NULL;
979 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
980 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
981 buffer_get_int_ret(&cport, m) != 0) {
984 error("%s: malformed message", __func__);
989 debug2("%s: channel %d: request stdio fwd to %s:%u",
990 __func__, c->self, chost, cport);
992 /* Gather fds from client */
993 for(i = 0; i < 2; i++) {
994 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
995 error("%s: failed to receive fd %d from slave",
997 for (j = 0; j < i; j++)
1002 buffer_put_int(r, MUX_S_FAILURE);
1003 buffer_put_int(r, rid);
1004 buffer_put_cstring(r,
1005 "did not receive file descriptors");
1010 debug3("%s: got fds stdin %d, stdout %d", __func__,
1011 new_fd[0], new_fd[1]);
1013 /* XXX support multiple child sessions in future */
1014 if (c->have_remote_id) {
1015 debug2("%s: session already open", __func__);
1017 buffer_put_int(r, MUX_S_FAILURE);
1018 buffer_put_int(r, rid);
1019 buffer_put_cstring(r, "Multiple sessions not supported");
1027 if (options.control_master == SSHCTL_MASTER_ASK ||
1028 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1029 if (!ask_permission("Allow forward to %s:%u? ",
1031 debug2("%s: stdio fwd refused by user", __func__);
1033 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1034 buffer_put_int(r, rid);
1035 buffer_put_cstring(r, "Permission denied");
1040 /* enable nonblocking unless tty */
1041 if (!isatty(new_fd[0]))
1042 set_nonblock(new_fd[0]);
1043 if (!isatty(new_fd[1]))
1044 set_nonblock(new_fd[1]);
1046 nc = channel_connect_stdio_fwd(ssh, chost, cport, new_fd[0], new_fd[1]);
1048 nc->ctl_chan = c->self; /* link session -> control channel */
1049 c->remote_id = nc->self; /* link control -> session channel */
1050 c->have_remote_id = 1;
1052 debug2("%s: channel_new: %d linked to control channel %d",
1053 __func__, nc->self, nc->ctl_chan);
1055 channel_register_cleanup(ssh, nc->self,
1056 mux_master_session_cleanup_cb, 1);
1058 cctx = xcalloc(1, sizeof(*cctx));
1060 channel_register_open_confirm(ssh, nc->self, mux_stdio_confirm, cctx);
1061 c->mux_pause = 1; /* stop handling messages until open_confirm done */
1063 /* reply is deferred, sent by mux_session_confirm */
1067 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1069 mux_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1071 struct mux_stdio_confirm_ctx *cctx = arg;
1076 fatal("%s: cctx == NULL", __func__);
1077 if ((c = channel_by_id(ssh, id)) == NULL)
1078 fatal("%s: no channel for id %d", __func__, id);
1079 if ((cc = channel_by_id(ssh, c->ctl_chan)) == NULL)
1080 fatal("%s: channel %d lacks control channel %d", __func__,
1084 debug3("%s: sending failure reply", __func__);
1086 buffer_init(&reply);
1087 buffer_put_int(&reply, MUX_S_FAILURE);
1088 buffer_put_int(&reply, cctx->rid);
1089 buffer_put_cstring(&reply, "Session open refused by peer");
1093 debug3("%s: sending success reply", __func__);
1095 buffer_init(&reply);
1096 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1097 buffer_put_int(&reply, cctx->rid);
1098 buffer_put_int(&reply, c->self);
1102 buffer_put_string(cc->output, buffer_ptr(&reply), buffer_len(&reply));
1103 buffer_free(&reply);
1105 if (cc->mux_pause <= 0)
1106 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1107 cc->mux_pause = 0; /* start processing messages again */
1108 c->open_confirm_ctx = NULL;
1113 process_mux_stop_listening(struct ssh *ssh, u_int rid,
1114 Channel *c, Buffer *m, Buffer *r)
1116 debug("%s: channel %d: stop listening", __func__, c->self);
1118 if (options.control_master == SSHCTL_MASTER_ASK ||
1119 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1120 if (!ask_permission("Disable further multiplexing on shared "
1121 "connection to %s? ", host)) {
1122 debug2("%s: stop listen refused by user", __func__);
1123 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1124 buffer_put_int(r, rid);
1125 buffer_put_cstring(r, "Permission denied");
1130 if (mux_listener_channel != NULL) {
1131 channel_free(ssh, mux_listener_channel);
1133 free(options.control_path);
1134 options.control_path = NULL;
1135 mux_listener_channel = NULL;
1136 muxserver_sock = -1;
1140 buffer_put_int(r, MUX_S_OK);
1141 buffer_put_int(r, rid);
1147 process_mux_proxy(struct ssh *ssh, u_int rid,
1148 Channel *c, Buffer *m, Buffer *r)
1150 debug("%s: channel %d: proxy request", __func__, c->self);
1152 c->mux_rcb = channel_proxy_downstream;
1153 buffer_put_int(r, MUX_S_PROXY);
1154 buffer_put_int(r, rid);
1159 /* Channel callbacks fired on read/write from mux slave fd */
1161 mux_master_read_cb(struct ssh *ssh, Channel *c)
1163 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1166 u_int type, rid, have, i;
1170 if (c->mux_ctx == NULL) {
1171 state = xcalloc(1, sizeof(*state));
1173 channel_register_cleanup(ssh, c->self,
1174 mux_master_control_cleanup_cb, 0);
1178 buffer_put_int(&out, MUX_MSG_HELLO);
1179 buffer_put_int(&out, SSHMUX_VER);
1181 buffer_put_string(c->output, buffer_ptr(&out),
1184 debug3("%s: channel %d: hello sent", __func__, c->self);
1191 /* Channel code ensures that we receive whole packets */
1192 if ((ptr = buffer_get_string_ptr_ret(c->input, &have)) == NULL) {
1194 error("%s: malformed message", __func__);
1197 buffer_append(&in, ptr, have);
1199 if (buffer_get_int_ret(&type, &in) != 0)
1201 debug3("%s: channel %d packet type 0x%08x len %u",
1202 __func__, c->self, type, buffer_len(&in));
1204 if (type == MUX_MSG_HELLO)
1207 if (!state->hello_rcvd) {
1208 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1209 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1212 if (buffer_get_int_ret(&rid, &in) != 0)
1216 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1217 if (type == mux_master_handlers[i].type) {
1218 ret = mux_master_handlers[i].handler(ssh, rid,
1223 if (mux_master_handlers[i].handler == NULL) {
1224 error("%s: unsupported mux message 0x%08x", __func__, type);
1225 buffer_put_int(&out, MUX_S_FAILURE);
1226 buffer_put_int(&out, rid);
1227 buffer_put_cstring(&out, "unsupported request");
1230 /* Enqueue reply packet */
1231 if (buffer_len(&out) != 0) {
1232 buffer_put_string(c->output, buffer_ptr(&out),
1242 mux_exit_message(struct ssh *ssh, Channel *c, int exitval)
1247 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1250 if ((mux_chan = channel_by_id(ssh, c->ctl_chan)) == NULL)
1251 fatal("%s: channel %d missing mux channel %d",
1252 __func__, c->self, c->ctl_chan);
1254 /* Append exit message packet to control socket output queue */
1256 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1257 buffer_put_int(&m, c->self);
1258 buffer_put_int(&m, exitval);
1260 buffer_put_string(mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1265 mux_tty_alloc_failed(struct ssh *ssh, Channel *c)
1270 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1272 if ((mux_chan = channel_by_id(ssh, c->ctl_chan)) == NULL)
1273 fatal("%s: channel %d missing mux channel %d",
1274 __func__, c->self, c->ctl_chan);
1276 /* Append exit message packet to control socket output queue */
1278 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1279 buffer_put_int(&m, c->self);
1281 buffer_put_string(mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1285 /* Prepare a mux master to listen on a Unix domain socket. */
1287 muxserver_listen(struct ssh *ssh)
1290 char *orig_control_path = options.control_path;
1295 if (options.control_path == NULL ||
1296 options.control_master == SSHCTL_MASTER_NO)
1299 debug("setting up multiplex master socket");
1302 * Use a temporary path before listen so we can pseudo-atomically
1303 * establish the listening socket in its final location to avoid
1304 * other processes racing in between bind() and listen() and hitting
1305 * an unready socket.
1307 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1308 r = arc4random_uniform(26+26+10);
1309 rbuf[i] = (r < 26) ? 'a' + r :
1310 (r < 26*2) ? 'A' + r - 26 :
1313 rbuf[sizeof(rbuf) - 1] = '\0';
1314 options.control_path = NULL;
1315 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1316 debug3("%s: temporary control path %s", __func__, options.control_path);
1318 old_umask = umask(0177);
1319 muxserver_sock = unix_listener(options.control_path, 64, 0);
1322 if (muxserver_sock < 0) {
1323 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1324 error("ControlSocket %s already exists, "
1325 "disabling multiplexing", options.control_path);
1327 if (muxserver_sock != -1) {
1328 close(muxserver_sock);
1329 muxserver_sock = -1;
1331 free(orig_control_path);
1332 free(options.control_path);
1333 options.control_path = NULL;
1334 options.control_master = SSHCTL_MASTER_NO;
1337 /* unix_listener() logs the error */
1342 /* Now atomically "move" the mux socket into position */
1343 if (link(options.control_path, orig_control_path) != 0) {
1344 if (errno != EEXIST) {
1345 fatal("%s: link mux listener %s => %s: %s", __func__,
1346 options.control_path, orig_control_path,
1349 error("ControlSocket %s already exists, disabling multiplexing",
1351 unlink(options.control_path);
1352 goto disable_mux_master;
1354 unlink(options.control_path);
1355 free(options.control_path);
1356 options.control_path = orig_control_path;
1358 set_nonblock(muxserver_sock);
1360 mux_listener_channel = channel_new(ssh, "mux listener",
1361 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1362 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1363 0, options.control_path, 1);
1364 mux_listener_channel->mux_rcb = mux_master_read_cb;
1365 debug3("%s: mux listener channel %d fd %d", __func__,
1366 mux_listener_channel->self, mux_listener_channel->sock);
1369 /* Callback on open confirmation in mux master for a mux client session. */
1371 mux_session_confirm(struct ssh *ssh, int id, int success, void *arg)
1373 struct mux_session_confirm_ctx *cctx = arg;
1374 const char *display;
1380 fatal("%s: cctx == NULL", __func__);
1381 if ((c = channel_by_id(ssh, id)) == NULL)
1382 fatal("%s: no channel for id %d", __func__, id);
1383 if ((cc = channel_by_id(ssh, c->ctl_chan)) == NULL)
1384 fatal("%s: channel %d lacks control channel %d", __func__,
1388 debug3("%s: sending failure reply", __func__);
1390 buffer_init(&reply);
1391 buffer_put_int(&reply, MUX_S_FAILURE);
1392 buffer_put_int(&reply, cctx->rid);
1393 buffer_put_cstring(&reply, "Session open refused by peer");
1397 display = getenv("DISPLAY");
1398 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1401 /* Get reasonable local authentication information. */
1402 if (client_x11_get_proto(ssh, display, options.xauth_location,
1403 options.forward_x11_trusted, options.forward_x11_timeout,
1404 &proto, &data) == 0) {
1405 /* Request forwarding with authentication spoofing. */
1406 debug("Requesting X11 forwarding with authentication "
1408 x11_request_forwarding_with_spoofing(ssh, id,
1409 display, proto, data, 1);
1410 /* XXX exit_on_forward_failure */
1411 client_expect_confirm(ssh, id, "X11 forwarding",
1416 if (cctx->want_agent_fwd && options.forward_agent) {
1417 debug("Requesting authentication agent forwarding.");
1418 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1422 client_session2_setup(ssh, id, cctx->want_tty, cctx->want_subsys,
1423 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1425 debug3("%s: sending success reply", __func__);
1427 buffer_init(&reply);
1428 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1429 buffer_put_int(&reply, cctx->rid);
1430 buffer_put_int(&reply, c->self);
1434 buffer_put_string(cc->output, buffer_ptr(&reply), buffer_len(&reply));
1435 buffer_free(&reply);
1437 if (cc->mux_pause <= 0)
1438 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1439 cc->mux_pause = 0; /* start processing messages again */
1440 c->open_confirm_ctx = NULL;
1441 buffer_free(&cctx->cmd);
1443 if (cctx->env != NULL) {
1444 for (i = 0; cctx->env[i] != NULL; i++)
1451 /* ** Multiplexing client support */
1453 /* Exit signal handler */
1455 control_client_sighandler(int signo)
1457 muxclient_terminate = signo;
1461 * Relay signal handler - used to pass some signals from mux client to
1465 control_client_sigrelay(int signo)
1467 int save_errno = errno;
1469 if (muxserver_pid > 1)
1470 kill(muxserver_pid, signo);
1476 mux_client_read(int fd, Buffer *b, u_int need)
1484 pfd.events = POLLIN;
1485 p = buffer_append_space(b, need);
1486 for (have = 0; have < need; ) {
1487 if (muxclient_terminate) {
1491 len = read(fd, p + have, need - have);
1494 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1498 (void)poll(&pfd, 1, -1);
1516 mux_client_write_packet(int fd, Buffer *m)
1525 pfd.events = POLLOUT;
1526 buffer_init(&queue);
1527 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1529 need = buffer_len(&queue);
1530 ptr = buffer_ptr(&queue);
1532 for (have = 0; have < need; ) {
1533 if (muxclient_terminate) {
1534 buffer_free(&queue);
1538 len = write(fd, ptr + have, need - have);
1541 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1545 (void)poll(&pfd, 1, -1);
1551 buffer_free(&queue);
1557 buffer_free(&queue);
1563 buffer_free(&queue);
1568 mux_client_read_packet(int fd, Buffer *m)
1575 buffer_init(&queue);
1576 if (mux_client_read(fd, &queue, 4) != 0) {
1577 if ((oerrno = errno) == EPIPE)
1578 debug3("%s: read header failed: %s", __func__,
1580 buffer_free(&queue);
1584 need = get_u32(buffer_ptr(&queue));
1585 if (mux_client_read(fd, &queue, need) != 0) {
1587 debug3("%s: read body failed: %s", __func__, strerror(errno));
1588 buffer_free(&queue);
1592 ptr = buffer_get_string_ptr(&queue, &have);
1593 buffer_append(m, ptr, have);
1594 buffer_free(&queue);
1599 mux_client_hello_exchange(int fd)
1606 buffer_put_int(&m, MUX_MSG_HELLO);
1607 buffer_put_int(&m, SSHMUX_VER);
1610 if (mux_client_write_packet(fd, &m) != 0) {
1611 debug("%s: write packet: %s", __func__, strerror(errno));
1617 /* Read their HELLO */
1618 if (mux_client_read_packet(fd, &m) != 0) {
1619 debug("%s: read packet failed", __func__);
1623 type = buffer_get_int(&m);
1624 if (type != MUX_MSG_HELLO) {
1625 error("%s: expected HELLO (%u) received %u",
1626 __func__, MUX_MSG_HELLO, type);
1629 ver = buffer_get_int(&m);
1630 if (ver != SSHMUX_VER) {
1631 error("Unsupported multiplexing protocol version %d "
1632 "(expected %d)", ver, SSHMUX_VER);
1635 debug2("%s: master version %u", __func__, ver);
1636 /* No extensions are presently defined */
1637 while (buffer_len(&m) > 0) {
1638 char *name = buffer_get_string(&m, NULL);
1639 char *value = buffer_get_string(&m, NULL);
1641 debug2("Unrecognised master extension \"%s\"", name);
1653 mux_client_request_alive(int fd)
1657 u_int pid, type, rid;
1659 debug3("%s: entering", __func__);
1662 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1663 buffer_put_int(&m, muxclient_request_id);
1665 if (mux_client_write_packet(fd, &m) != 0)
1666 fatal("%s: write packet: %s", __func__, strerror(errno));
1670 /* Read their reply */
1671 if (mux_client_read_packet(fd, &m) != 0) {
1676 type = buffer_get_int(&m);
1677 if (type != MUX_S_ALIVE) {
1678 e = buffer_get_string(&m, NULL);
1679 fatal("%s: master returned error: %s", __func__, e);
1682 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1683 fatal("%s: out of sequence reply: my id %u theirs %u",
1684 __func__, muxclient_request_id, rid);
1685 pid = buffer_get_int(&m);
1688 debug3("%s: done pid = %u", __func__, pid);
1690 muxclient_request_id++;
1696 mux_client_request_terminate(int fd)
1702 debug3("%s: entering", __func__);
1705 buffer_put_int(&m, MUX_C_TERMINATE);
1706 buffer_put_int(&m, muxclient_request_id);
1708 if (mux_client_write_packet(fd, &m) != 0)
1709 fatal("%s: write packet: %s", __func__, strerror(errno));
1713 /* Read their reply */
1714 if (mux_client_read_packet(fd, &m) != 0) {
1715 /* Remote end exited already */
1716 if (errno == EPIPE) {
1720 fatal("%s: read from master failed: %s",
1721 __func__, strerror(errno));
1724 type = buffer_get_int(&m);
1725 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1726 fatal("%s: out of sequence reply: my id %u theirs %u",
1727 __func__, muxclient_request_id, rid);
1731 case MUX_S_PERMISSION_DENIED:
1732 e = buffer_get_string(&m, NULL);
1733 fatal("Master refused termination request: %s", e);
1735 e = buffer_get_string(&m, NULL);
1736 fatal("%s: termination request failed: %s", __func__, e);
1738 fatal("%s: unexpected response from master 0x%08x",
1742 muxclient_request_id++;
1746 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1752 fwd_desc = format_forward(ftype, fwd);
1753 debug("Requesting %s %s",
1754 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1758 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1759 buffer_put_int(&m, muxclient_request_id);
1760 buffer_put_int(&m, ftype);
1761 if (fwd->listen_path != NULL) {
1762 buffer_put_cstring(&m, fwd->listen_path);
1764 buffer_put_cstring(&m,
1765 fwd->listen_host == NULL ? "" :
1766 (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1768 buffer_put_int(&m, fwd->listen_port);
1769 if (fwd->connect_path != NULL) {
1770 buffer_put_cstring(&m, fwd->connect_path);
1772 buffer_put_cstring(&m,
1773 fwd->connect_host == NULL ? "" : fwd->connect_host);
1775 buffer_put_int(&m, fwd->connect_port);
1777 if (mux_client_write_packet(fd, &m) != 0)
1778 fatal("%s: write packet: %s", __func__, strerror(errno));
1782 /* Read their reply */
1783 if (mux_client_read_packet(fd, &m) != 0) {
1788 type = buffer_get_int(&m);
1789 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1790 fatal("%s: out of sequence reply: my id %u theirs %u",
1791 __func__, muxclient_request_id, rid);
1795 case MUX_S_REMOTE_PORT:
1797 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1798 fwd->allocated_port = buffer_get_int(&m);
1799 verbose("Allocated port %u for remote forward to %s:%d",
1800 fwd->allocated_port,
1801 fwd->connect_host ? fwd->connect_host : "",
1803 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1804 fprintf(stdout, "%i\n", fwd->allocated_port);
1806 case MUX_S_PERMISSION_DENIED:
1807 e = buffer_get_string(&m, NULL);
1809 error("Master refused forwarding request: %s", e);
1812 e = buffer_get_string(&m, NULL);
1814 error("%s: forwarding request failed: %s", __func__, e);
1817 fatal("%s: unexpected response from master 0x%08x",
1822 muxclient_request_id++;
1827 mux_client_forwards(int fd, int cancel_flag)
1831 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1832 cancel_flag ? "cancel" : "request",
1833 options.num_local_forwards, options.num_remote_forwards);
1835 /* XXX ExitOnForwardingFailure */
1836 for (i = 0; i < options.num_local_forwards; i++) {
1837 if (mux_client_forward(fd, cancel_flag,
1838 options.local_forwards[i].connect_port == 0 ?
1839 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1840 options.local_forwards + i) != 0)
1843 for (i = 0; i < options.num_remote_forwards; i++) {
1844 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1845 options.remote_forwards + i) != 0)
1852 mux_client_request_session(int fd)
1856 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1857 extern char **environ;
1858 int devnull, rawmode;
1860 debug3("%s: entering", __func__);
1862 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1863 error("%s: master alive request failed", __func__);
1867 signal(SIGPIPE, SIG_IGN);
1869 if (stdin_null_flag) {
1870 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1871 fatal("open(/dev/null): %s", strerror(errno));
1872 if (dup2(devnull, STDIN_FILENO) == -1)
1873 fatal("dup2: %s", strerror(errno));
1874 if (devnull > STDERR_FILENO)
1878 term = getenv("TERM");
1881 buffer_put_int(&m, MUX_C_NEW_SESSION);
1882 buffer_put_int(&m, muxclient_request_id);
1883 buffer_put_cstring(&m, ""); /* reserved */
1884 buffer_put_int(&m, tty_flag);
1885 buffer_put_int(&m, options.forward_x11);
1886 buffer_put_int(&m, options.forward_agent);
1887 buffer_put_int(&m, subsystem_flag);
1888 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1889 0xffffffff : (u_int)options.escape_char);
1890 buffer_put_cstring(&m, term == NULL ? "" : term);
1891 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1893 if (options.num_send_env > 0 && environ != NULL) {
1894 /* Pass environment */
1895 for (i = 0; environ[i] != NULL; i++) {
1896 if (env_permitted(environ[i])) {
1897 buffer_put_cstring(&m, environ[i]);
1902 if (mux_client_write_packet(fd, &m) != 0)
1903 fatal("%s: write packet: %s", __func__, strerror(errno));
1905 /* Send the stdio file descriptors */
1906 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1907 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1908 mm_send_fd(fd, STDERR_FILENO) == -1)
1909 fatal("%s: send fds failed", __func__);
1911 debug3("%s: session request sent", __func__);
1913 /* Read their reply */
1915 if (mux_client_read_packet(fd, &m) != 0) {
1916 error("%s: read from master failed: %s",
1917 __func__, strerror(errno));
1922 type = buffer_get_int(&m);
1923 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1924 fatal("%s: out of sequence reply: my id %u theirs %u",
1925 __func__, muxclient_request_id, rid);
1927 case MUX_S_SESSION_OPENED:
1928 sid = buffer_get_int(&m);
1929 debug("%s: master session id: %u", __func__, sid);
1931 case MUX_S_PERMISSION_DENIED:
1932 e = buffer_get_string(&m, NULL);
1934 error("Master refused session request: %s", e);
1937 e = buffer_get_string(&m, NULL);
1939 error("%s: session request failed: %s", __func__, e);
1943 error("%s: unexpected response from master 0x%08x",
1947 muxclient_request_id++;
1949 if (pledge("stdio proc tty", NULL) == -1)
1950 fatal("%s pledge(): %s", __func__, strerror(errno));
1951 platform_pledge_mux();
1953 signal(SIGHUP, control_client_sighandler);
1954 signal(SIGINT, control_client_sighandler);
1955 signal(SIGTERM, control_client_sighandler);
1956 signal(SIGWINCH, control_client_sigrelay);
1960 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1963 * Stick around until the controlee closes the client_fd.
1964 * Before it does, it is expected to write an exit message.
1965 * This process must read the value and wait for the closure of
1966 * the client_fd; if this one closes early, the multiplex master will
1967 * terminate early too (possibly losing data).
1969 for (exitval = 255, exitval_seen = 0;;) {
1971 if (mux_client_read_packet(fd, &m) != 0)
1973 type = buffer_get_int(&m);
1975 case MUX_S_TTY_ALLOC_FAIL:
1976 if ((esid = buffer_get_int(&m)) != sid)
1977 fatal("%s: tty alloc fail on unknown session: "
1978 "my id %u theirs %u",
1979 __func__, sid, esid);
1980 leave_raw_mode(options.request_tty ==
1984 case MUX_S_EXIT_MESSAGE:
1985 if ((esid = buffer_get_int(&m)) != sid)
1986 fatal("%s: exit on unknown session: "
1987 "my id %u theirs %u",
1988 __func__, sid, esid);
1990 fatal("%s: exitval sent twice", __func__);
1991 exitval = buffer_get_int(&m);
1995 e = buffer_get_string(&m, NULL);
1996 fatal("%s: master returned error: %s", __func__, e);
2002 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2004 if (muxclient_terminate) {
2005 debug2("Exiting on signal: %s", strsignal(muxclient_terminate));
2007 } else if (!exitval_seen) {
2008 debug2("Control master terminated unexpectedly");
2011 debug2("Received exit status from master %d", exitval);
2013 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
2014 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
2020 mux_client_proxy(int fd)
2027 buffer_put_int(&m, MUX_C_PROXY);
2028 buffer_put_int(&m, muxclient_request_id);
2029 if (mux_client_write_packet(fd, &m) != 0)
2030 fatal("%s: write packet: %s", __func__, strerror(errno));
2034 /* Read their reply */
2035 if (mux_client_read_packet(fd, &m) != 0) {
2039 type = buffer_get_int(&m);
2040 if (type != MUX_S_PROXY) {
2041 e = buffer_get_string(&m, NULL);
2042 fatal("%s: master returned error: %s", __func__, e);
2044 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2045 fatal("%s: out of sequence reply: my id %u theirs %u",
2046 __func__, muxclient_request_id, rid);
2049 debug3("%s: done", __func__);
2050 muxclient_request_id++;
2055 mux_client_request_stdio_fwd(int fd)
2059 u_int type, rid, sid;
2062 debug3("%s: entering", __func__);
2064 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
2065 error("%s: master alive request failed", __func__);
2069 signal(SIGPIPE, SIG_IGN);
2071 if (stdin_null_flag) {
2072 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
2073 fatal("open(/dev/null): %s", strerror(errno));
2074 if (dup2(devnull, STDIN_FILENO) == -1)
2075 fatal("dup2: %s", strerror(errno));
2076 if (devnull > STDERR_FILENO)
2081 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
2082 buffer_put_int(&m, muxclient_request_id);
2083 buffer_put_cstring(&m, ""); /* reserved */
2084 buffer_put_cstring(&m, options.stdio_forward_host);
2085 buffer_put_int(&m, options.stdio_forward_port);
2087 if (mux_client_write_packet(fd, &m) != 0)
2088 fatal("%s: write packet: %s", __func__, strerror(errno));
2090 /* Send the stdio file descriptors */
2091 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
2092 mm_send_fd(fd, STDOUT_FILENO) == -1)
2093 fatal("%s: send fds failed", __func__);
2095 if (pledge("stdio proc tty", NULL) == -1)
2096 fatal("%s pledge(): %s", __func__, strerror(errno));
2097 platform_pledge_mux();
2099 debug3("%s: stdio forward request sent", __func__);
2101 /* Read their reply */
2104 if (mux_client_read_packet(fd, &m) != 0) {
2105 error("%s: read from master failed: %s",
2106 __func__, strerror(errno));
2111 type = buffer_get_int(&m);
2112 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2113 fatal("%s: out of sequence reply: my id %u theirs %u",
2114 __func__, muxclient_request_id, rid);
2116 case MUX_S_SESSION_OPENED:
2117 sid = buffer_get_int(&m);
2118 debug("%s: master session id: %u", __func__, sid);
2120 case MUX_S_PERMISSION_DENIED:
2121 e = buffer_get_string(&m, NULL);
2123 fatal("Master refused stdio forwarding request: %s", e);
2125 e = buffer_get_string(&m, NULL);
2127 fatal("Stdio forwarding request failed: %s", e);
2130 error("%s: unexpected response from master 0x%08x",
2134 muxclient_request_id++;
2136 signal(SIGHUP, control_client_sighandler);
2137 signal(SIGINT, control_client_sighandler);
2138 signal(SIGTERM, control_client_sighandler);
2139 signal(SIGWINCH, control_client_sigrelay);
2142 * Stick around until the controlee closes the client_fd.
2145 if (mux_client_read_packet(fd, &m) != 0) {
2146 if (errno == EPIPE ||
2147 (errno == EINTR && muxclient_terminate != 0))
2149 fatal("%s: mux_client_read_packet: %s",
2150 __func__, strerror(errno));
2152 fatal("%s: master returned unexpected message %u", __func__, type);
2156 mux_client_request_stop_listening(int fd)
2162 debug3("%s: entering", __func__);
2165 buffer_put_int(&m, MUX_C_STOP_LISTENING);
2166 buffer_put_int(&m, muxclient_request_id);
2168 if (mux_client_write_packet(fd, &m) != 0)
2169 fatal("%s: write packet: %s", __func__, strerror(errno));
2173 /* Read their reply */
2174 if (mux_client_read_packet(fd, &m) != 0)
2175 fatal("%s: read from master failed: %s",
2176 __func__, strerror(errno));
2178 type = buffer_get_int(&m);
2179 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2180 fatal("%s: out of sequence reply: my id %u theirs %u",
2181 __func__, muxclient_request_id, rid);
2185 case MUX_S_PERMISSION_DENIED:
2186 e = buffer_get_string(&m, NULL);
2187 fatal("Master refused stop listening request: %s", e);
2189 e = buffer_get_string(&m, NULL);
2190 fatal("%s: stop listening request failed: %s", __func__, e);
2192 fatal("%s: unexpected response from master 0x%08x",
2196 muxclient_request_id++;
2199 /* Multiplex client main loop. */
2201 muxclient(const char *path)
2203 struct sockaddr_un addr;
2207 if (muxclient_command == 0) {
2208 if (options.stdio_forward_host != NULL)
2209 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2211 muxclient_command = SSHMUX_COMMAND_OPEN;
2214 switch (options.control_master) {
2215 case SSHCTL_MASTER_AUTO:
2216 case SSHCTL_MASTER_AUTO_ASK:
2217 debug("auto-mux: Trying existing master");
2219 case SSHCTL_MASTER_NO:
2225 memset(&addr, '\0', sizeof(addr));
2226 addr.sun_family = AF_UNIX;
2228 if (strlcpy(addr.sun_path, path,
2229 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2230 fatal("ControlPath too long ('%s' >= %u bytes)", path,
2231 (unsigned int)sizeof(addr.sun_path));
2233 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2234 fatal("%s socket(): %s", __func__, strerror(errno));
2236 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
2237 switch (muxclient_command) {
2238 case SSHMUX_COMMAND_OPEN:
2239 case SSHMUX_COMMAND_STDIO_FWD:
2242 fatal("Control socket connect(%.100s): %s", path,
2245 if (errno == ECONNREFUSED &&
2246 options.control_master != SSHCTL_MASTER_NO) {
2247 debug("Stale control socket %.100s, unlinking", path);
2249 } else if (errno == ENOENT) {
2250 debug("Control socket \"%.100s\" does not exist", path);
2252 error("Control socket connect(%.100s): %s", path,
2260 if (mux_client_hello_exchange(sock) != 0) {
2261 error("%s: master hello exchange failed", __func__);
2266 switch (muxclient_command) {
2267 case SSHMUX_COMMAND_ALIVE_CHECK:
2268 if ((pid = mux_client_request_alive(sock)) == 0)
2269 fatal("%s: master alive check failed", __func__);
2270 fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2272 case SSHMUX_COMMAND_TERMINATE:
2273 mux_client_request_terminate(sock);
2274 if (options.log_level != SYSLOG_LEVEL_QUIET)
2275 fprintf(stderr, "Exit request sent.\r\n");
2277 case SSHMUX_COMMAND_FORWARD:
2278 if (mux_client_forwards(sock, 0) != 0)
2279 fatal("%s: master forward request failed", __func__);
2281 case SSHMUX_COMMAND_OPEN:
2282 if (mux_client_forwards(sock, 0) != 0) {
2283 error("%s: master forward request failed", __func__);
2286 mux_client_request_session(sock);
2288 case SSHMUX_COMMAND_STDIO_FWD:
2289 mux_client_request_stdio_fwd(sock);
2291 case SSHMUX_COMMAND_STOP:
2292 mux_client_request_stop_listening(sock);
2293 if (options.log_level != SYSLOG_LEVEL_QUIET)
2294 fprintf(stderr, "Stop listening request sent.\r\n");
2296 case SSHMUX_COMMAND_CANCEL_FWD:
2297 if (mux_client_forwards(sock, 1) != 0)
2298 error("%s: master cancel forward request failed",
2301 case SSHMUX_COMMAND_PROXY:
2302 mux_client_proxy(sock);
2305 fatal("unrecognised muxclient_command %d", muxclient_command);