1 /* $OpenBSD: mux.c,v 1.9 2010/01/09 05:04:24 djm Exp $ */
3 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 /* ssh session multiplexing support */
24 * 1. partial reads in muxserver_accept_control (maybe make channels
25 * from accepted connections)
26 * 2. Better signalling from master to slave, especially passing of
28 * 3. Better fall-back from mux slave error to new connection.
29 * 3. Add/delete forwardings via slave
30 * 4. ExitOnForwardingFailure (after #3 obviously)
31 * 5. Maybe extension mechanisms for multi-X11/multi-agent forwarding
32 * 6. Document the mux mini-protocol somewhere.
33 * 7. Support ~^Z in mux slaves.
34 * 8. Inspect or control sessions in master.
35 * 9. If we ever support the "signal" channel request, send signals on
39 #include <sys/types.h>
40 #include <sys/param.h>
42 #include <sys/socket.h>
66 #include "openbsd-compat/sys-queue.h"
70 #include "pathnames.h"
77 #include "monitor_fdpass.h"
81 #include "clientloop.h"
85 extern int force_tty_flag;
86 extern Options options;
87 extern int stdin_null_flag;
89 extern int subsystem_flag;
90 extern Buffer command;
92 /* Context for session open confirmation callback */
93 struct mux_session_confirm_ctx {
104 /* fd to control socket */
105 int muxserver_sock = -1;
107 /* Multiplexing control command */
108 u_int muxclient_command = 0;
110 /* Set when signalled. */
111 static volatile sig_atomic_t muxclient_terminate = 0;
113 /* PID of multiplex server */
114 static u_int muxserver_pid = 0;
117 /* ** Multiplexing master support */
119 /* Prepare a mux master to listen on a Unix domain socket. */
121 muxserver_listen(void)
123 struct sockaddr_un addr;
127 if (options.control_path == NULL ||
128 options.control_master == SSHCTL_MASTER_NO)
131 debug("setting up multiplex master socket");
133 memset(&addr, '\0', sizeof(addr));
134 addr.sun_family = AF_UNIX;
135 addr_len = offsetof(struct sockaddr_un, sun_path) +
136 strlen(options.control_path) + 1;
138 if (strlcpy(addr.sun_path, options.control_path,
139 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
140 fatal("ControlPath too long");
142 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
143 fatal("%s socket(): %s", __func__, strerror(errno));
145 old_umask = umask(0177);
146 if (bind(muxserver_sock, (struct sockaddr *)&addr, addr_len) == -1) {
148 if (errno == EINVAL || errno == EADDRINUSE) {
149 error("ControlSocket %s already exists, "
150 "disabling multiplexing", options.control_path);
151 close(muxserver_sock);
153 xfree(options.control_path);
154 options.control_path = NULL;
155 options.control_master = SSHCTL_MASTER_NO;
158 fatal("%s bind(): %s", __func__, strerror(errno));
162 if (listen(muxserver_sock, 64) == -1)
163 fatal("%s listen(): %s", __func__, strerror(errno));
165 set_nonblock(muxserver_sock);
168 /* Callback on open confirmation in mux master for a mux client session. */
170 mux_session_confirm(int id, void *arg)
172 struct mux_session_confirm_ctx *cctx = arg;
178 fatal("%s: cctx == NULL", __func__);
179 if ((c = channel_lookup(id)) == NULL)
180 fatal("%s: no channel for id %d", __func__, id);
182 display = getenv("DISPLAY");
183 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
185 /* Get reasonable local authentication information. */
186 client_x11_get_proto(display, options.xauth_location,
187 options.forward_x11_trusted, &proto, &data);
188 /* Request forwarding with authentication spoofing. */
189 debug("Requesting X11 forwarding with authentication spoofing.");
190 x11_request_forwarding_with_spoofing(id, display, proto, data);
191 /* XXX wait for reply */
194 if (cctx->want_agent_fwd && options.forward_agent) {
195 debug("Requesting authentication agent forwarding.");
196 channel_request_start(id, "auth-agent-req@openssh.com", 0);
200 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
201 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
203 c->open_confirm_ctx = NULL;
204 buffer_free(&cctx->cmd);
206 if (cctx->env != NULL) {
207 for (i = 0; cctx->env[i] != NULL; i++)
215 * Accept a connection on the mux master socket and process the
216 * client's request. Returns flag indicating whether mux master should
217 * begin graceful close.
220 muxserver_accept_control(void)
224 int client_fd, new_fd[3], ver, allowed, window, packetmax;
226 struct sockaddr_storage addr;
227 struct mux_session_confirm_ctx *cctx;
229 u_int i, j, len, env_len, mux_command, flags, escape_char;
235 * Accept connection on control socket
237 memset(&addr, 0, sizeof(addr));
238 addrlen = sizeof(addr);
239 if ((client_fd = accept(muxserver_sock,
240 (struct sockaddr*)&addr, &addrlen)) == -1) {
241 error("%s accept: %s", __func__, strerror(errno));
245 if (getpeereid(client_fd, &euid, &egid) < 0) {
246 error("%s getpeereid failed: %s", __func__, strerror(errno));
250 if ((euid != 0) && (getuid() != euid)) {
251 error("control mode uid mismatch: peer euid %u != uid %u",
252 (u_int) euid, (u_int) getuid());
257 /* XXX handle asynchronously */
258 unset_nonblock(client_fd);
262 if (ssh_msg_recv(client_fd, &m) == -1) {
263 error("%s: client msg_recv failed", __func__);
268 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
269 error("%s: wrong client version %d", __func__, ver);
276 mux_command = buffer_get_int(&m);
277 flags = buffer_get_int(&m);
281 switch (mux_command) {
282 case SSHMUX_COMMAND_OPEN:
283 if (options.control_master == SSHCTL_MASTER_ASK ||
284 options.control_master == SSHCTL_MASTER_AUTO_ASK)
285 allowed = ask_permission("Allow shared connection "
289 case SSHMUX_COMMAND_TERMINATE:
290 if (options.control_master == SSHCTL_MASTER_ASK ||
291 options.control_master == SSHCTL_MASTER_AUTO_ASK)
292 allowed = ask_permission("Terminate shared connection "
297 case SSHMUX_COMMAND_ALIVE_CHECK:
298 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
300 buffer_put_int(&m, allowed);
301 buffer_put_int(&m, getpid());
302 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
303 error("%s: client msg_send failed", __func__);
312 error("Unsupported command %d", mux_command);
318 /* Reply for SSHMUX_COMMAND_OPEN */
320 buffer_put_int(&m, allowed);
321 buffer_put_int(&m, getpid());
322 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
323 error("%s: client msg_send failed", __func__);
330 error("Refused control connection");
337 if (ssh_msg_recv(client_fd, &m) == -1) {
338 error("%s: client msg_recv failed", __func__);
343 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
344 error("%s: wrong client version %d", __func__, ver);
350 cctx = xcalloc(1, sizeof(*cctx));
351 cctx->want_tty = (flags & SSHMUX_FLAG_TTY) != 0;
352 cctx->want_subsys = (flags & SSHMUX_FLAG_SUBSYS) != 0;
353 cctx->want_x_fwd = (flags & SSHMUX_FLAG_X11_FWD) != 0;
354 cctx->want_agent_fwd = (flags & SSHMUX_FLAG_AGENT_FWD) != 0;
355 cctx->term = buffer_get_string(&m, &len);
356 escape_char = buffer_get_int(&m);
358 cmd = buffer_get_string(&m, &len);
359 buffer_init(&cctx->cmd);
360 buffer_append(&cctx->cmd, cmd, strlen(cmd));
362 env_len = buffer_get_int(&m);
363 env_len = MIN(env_len, 4096);
364 debug3("%s: receiving %d env vars", __func__, env_len);
366 cctx->env = xcalloc(env_len + 1, sizeof(*cctx->env));
367 for (i = 0; i < env_len; i++)
368 cctx->env[i] = buffer_get_string(&m, &len);
372 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
373 cctx->want_tty, cctx->want_subsys, cmd);
376 /* Gather fds from client */
377 for(i = 0; i < 3; i++) {
378 if ((new_fd[i] = mm_receive_fd(client_fd)) == -1) {
379 error("%s: failed to receive fd %d from slave",
381 for (j = 0; j < i; j++)
383 for (j = 0; j < env_len; j++)
388 buffer_free(&cctx->cmd);
395 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
396 new_fd[0], new_fd[1], new_fd[2]);
398 /* Try to pick up ttymodes from client before it goes raw */
399 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
400 error("%s: tcgetattr: %s", __func__, strerror(errno));
402 /* This roundtrip is just for synchronisation of ttymodes */
404 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
405 error("%s: client msg_send failed", __func__);
413 for (i = 0; i < env_len; i++)
421 /* enable nonblocking unless tty */
422 if (!isatty(new_fd[0]))
423 set_nonblock(new_fd[0]);
424 if (!isatty(new_fd[1]))
425 set_nonblock(new_fd[1]);
426 if (!isatty(new_fd[2]))
427 set_nonblock(new_fd[2]);
429 set_nonblock(client_fd);
431 window = CHAN_SES_WINDOW_DEFAULT;
432 packetmax = CHAN_SES_PACKET_DEFAULT;
433 if (cctx->want_tty) {
438 c = channel_new("session", SSH_CHANNEL_OPENING,
439 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
440 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
442 c->ctl_fd = client_fd;
443 if (cctx->want_tty && escape_char != 0xffffffff) {
444 channel_register_filter(c->self,
445 client_simple_escape_filter, NULL,
446 client_filter_cleanup,
447 client_new_escape_filter_ctx((int)escape_char));
450 debug3("%s: channel_new: %d", __func__, c->self);
452 channel_send_open(c->self);
453 channel_register_open_confirm(c->self, mux_session_confirm, cctx);
457 /* ** Multiplexing client support */
459 /* Exit signal handler */
461 control_client_sighandler(int signo)
463 muxclient_terminate = signo;
467 * Relay signal handler - used to pass some signals from mux client to
471 control_client_sigrelay(int signo)
473 int save_errno = errno;
475 if (muxserver_pid > 1)
476 kill(muxserver_pid, signo);
481 /* Check mux client environment variables before passing them to mux master. */
483 env_permitted(char *env)
486 char name[1024], *cp;
488 if ((cp = strchr(env, '=')) == NULL || cp == env)
490 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
491 if (ret <= 0 || (size_t)ret >= sizeof(name))
492 fatal("env_permitted: name '%.100s...' too long", env);
494 for (i = 0; i < options.num_send_env; i++)
495 if (match_pattern(name, options.send_env[i]))
501 /* Multiplex client main loop. */
503 muxclient(const char *path)
505 struct sockaddr_un addr;
506 int i, r, fd, sock, exitval[2], num_env, addr_len;
509 extern char **environ;
510 u_int allowed, flags;
512 if (muxclient_command == 0)
513 muxclient_command = SSHMUX_COMMAND_OPEN;
515 switch (options.control_master) {
516 case SSHCTL_MASTER_AUTO:
517 case SSHCTL_MASTER_AUTO_ASK:
518 debug("auto-mux: Trying existing master");
520 case SSHCTL_MASTER_NO:
526 memset(&addr, '\0', sizeof(addr));
527 addr.sun_family = AF_UNIX;
528 addr_len = offsetof(struct sockaddr_un, sun_path) +
531 if (strlcpy(addr.sun_path, path,
532 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
533 fatal("ControlPath too long");
535 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
536 fatal("%s socket(): %s", __func__, strerror(errno));
538 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
539 if (muxclient_command != SSHMUX_COMMAND_OPEN) {
540 fatal("Control socket connect(%.100s): %s", path,
544 debug("Control socket \"%.100s\" does not exist", path);
546 error("Control socket connect(%.100s): %s", path,
553 if (stdin_null_flag) {
554 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
555 fatal("open(/dev/null): %s", strerror(errno));
556 if (dup2(fd, STDIN_FILENO) == -1)
557 fatal("dup2: %s", strerror(errno));
558 if (fd > STDERR_FILENO)
562 term = getenv("TERM");
566 flags |= SSHMUX_FLAG_TTY;
568 flags |= SSHMUX_FLAG_SUBSYS;
569 if (options.forward_x11)
570 flags |= SSHMUX_FLAG_X11_FWD;
571 if (options.forward_agent)
572 flags |= SSHMUX_FLAG_AGENT_FWD;
574 signal(SIGPIPE, SIG_IGN);
578 /* Send our command to server */
579 buffer_put_int(&m, muxclient_command);
580 buffer_put_int(&m, flags);
581 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1) {
582 error("%s: msg_send", __func__);
586 if (muxclient_command != SSHMUX_COMMAND_OPEN)
588 logit("Falling back to non-multiplexed connection");
589 xfree(options.control_path);
590 options.control_path = NULL;
591 options.control_master = SSHCTL_MASTER_NO;
596 /* Get authorisation status and PID of controlee */
597 if (ssh_msg_recv(sock, &m) == -1) {
598 error("%s: Did not receive reply from master", __func__);
601 if (buffer_get_char(&m) != SSHMUX_VER) {
602 error("%s: Master replied with wrong version", __func__);
605 if (buffer_get_int_ret(&allowed, &m) != 0) {
606 error("%s: bad server reply", __func__);
610 error("Connection to master denied");
613 muxserver_pid = buffer_get_int(&m);
617 switch (muxclient_command) {
618 case SSHMUX_COMMAND_ALIVE_CHECK:
619 fprintf(stderr, "Master running (pid=%d)\r\n",
622 case SSHMUX_COMMAND_TERMINATE:
623 fprintf(stderr, "Exit request sent.\r\n");
625 case SSHMUX_COMMAND_OPEN:
626 buffer_put_cstring(&m, term ? term : "");
627 if (options.escape_char == SSH_ESCAPECHAR_NONE)
628 buffer_put_int(&m, 0xffffffff);
630 buffer_put_int(&m, options.escape_char);
631 buffer_append(&command, "\0", 1);
632 buffer_put_cstring(&m, buffer_ptr(&command));
634 if (options.num_send_env == 0 || environ == NULL) {
635 buffer_put_int(&m, 0);
637 /* Pass environment */
639 for (i = 0; environ[i] != NULL; i++) {
640 if (env_permitted(environ[i]))
641 num_env++; /* Count */
643 buffer_put_int(&m, num_env);
644 for (i = 0; environ[i] != NULL && num_env >= 0; i++) {
645 if (env_permitted(environ[i])) {
647 buffer_put_cstring(&m, environ[i]);
653 fatal("unrecognised muxclient_command %d", muxclient_command);
656 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1) {
657 error("%s: msg_send", __func__);
661 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
662 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
663 mm_send_fd(sock, STDERR_FILENO) == -1) {
664 error("%s: send fds failed", __func__);
669 * Mux errors are non-recoverable from this point as the master
670 * has ownership of the session now.
673 /* Wait for reply, so master has a chance to gather ttymodes */
675 if (ssh_msg_recv(sock, &m) == -1)
676 fatal("%s: msg_recv", __func__);
677 if (buffer_get_char(&m) != SSHMUX_VER)
678 fatal("%s: wrong version", __func__);
681 signal(SIGHUP, control_client_sighandler);
682 signal(SIGINT, control_client_sighandler);
683 signal(SIGTERM, control_client_sighandler);
684 signal(SIGWINCH, control_client_sigrelay);
687 enter_raw_mode(force_tty_flag);
690 * Stick around until the controlee closes the client_fd.
691 * Before it does, it is expected to write this process' exit
692 * value (one int). This process must read the value and wait for
693 * the closure of the client_fd; if this one closes early, the
694 * multiplex master will terminate early too (possibly losing data).
697 for (i = 0; !muxclient_terminate && i < (int)sizeof(exitval);) {
698 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
700 debug2("Received EOF from master");
706 fatal("%s: read %s", __func__, strerror(errno));
712 leave_raw_mode(force_tty_flag);
713 if (i > (int)sizeof(int))
714 fatal("%s: master returned too much data (%d > %lu)",
715 __func__, i, (u_long)sizeof(int));
716 if (muxclient_terminate) {
717 debug2("Exiting on signal %d", muxclient_terminate);
719 } else if (i < (int)sizeof(int)) {
720 debug2("Control master terminated unexpectedly");
723 debug2("Received exit status from master %d", exitval[0]);
725 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
726 fprintf(stderr, "Shared connection to %s closed.\r\n", host);