1 /* $OpenBSD: mux.c,v 1.2 2008/06/12 03:40:52 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 * 6. Support ~^Z in mux slaves.
36 #include <sys/types.h>
37 #include <sys/param.h>
39 #include <sys/socket.h>
63 #include "openbsd-compat/sys-queue.h"
67 #include "pathnames.h"
74 #include "monitor_fdpass.h"
78 #include "clientloop.h"
82 extern Options options;
83 extern int stdin_null_flag;
86 extern Buffer command;
88 /* Context for session open confirmation callback */
89 struct mux_session_confirm_ctx {
100 /* fd to control socket */
101 int muxserver_sock = -1;
103 /* Multiplexing control command */
104 u_int muxclient_command = 0;
106 /* Set when signalled. */
107 static volatile sig_atomic_t muxclient_terminate = 0;
109 /* PID of multiplex server */
110 static u_int muxserver_pid = 0;
113 /* ** Multiplexing master support */
115 /* Prepare a mux master to listen on a Unix domain socket. */
117 muxserver_listen(void)
119 struct sockaddr_un addr;
123 if (options.control_path == NULL ||
124 options.control_master == SSHCTL_MASTER_NO)
127 debug("setting up multiplex master socket");
129 memset(&addr, '\0', sizeof(addr));
130 addr.sun_family = AF_UNIX;
131 addr_len = offsetof(struct sockaddr_un, sun_path) +
132 strlen(options.control_path) + 1;
134 if (strlcpy(addr.sun_path, options.control_path,
135 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
136 fatal("ControlPath too long");
138 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
139 fatal("%s socket(): %s", __func__, strerror(errno));
141 old_umask = umask(0177);
142 if (bind(muxserver_sock, (struct sockaddr *)&addr, addr_len) == -1) {
144 if (errno == EINVAL || errno == EADDRINUSE)
145 fatal("ControlSocket %s already exists",
146 options.control_path);
148 fatal("%s bind(): %s", __func__, strerror(errno));
152 if (listen(muxserver_sock, 64) == -1)
153 fatal("%s listen(): %s", __func__, strerror(errno));
155 set_nonblock(muxserver_sock);
158 /* Callback on open confirmation in mux master for a mux client session. */
160 mux_session_confirm(int id, void *arg)
162 struct mux_session_confirm_ctx *cctx = arg;
168 fatal("%s: cctx == NULL", __func__);
169 if ((c = channel_lookup(id)) == NULL)
170 fatal("%s: no channel for id %d", __func__, id);
172 display = getenv("DISPLAY");
173 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
175 /* Get reasonable local authentication information. */
176 client_x11_get_proto(display, options.xauth_location,
177 options.forward_x11_trusted, &proto, &data);
178 /* Request forwarding with authentication spoofing. */
179 debug("Requesting X11 forwarding with authentication spoofing.");
180 x11_request_forwarding_with_spoofing(id, display, proto, data);
181 /* XXX wait for reply */
184 if (cctx->want_agent_fwd && options.forward_agent) {
185 debug("Requesting authentication agent forwarding.");
186 channel_request_start(id, "auth-agent-req@openssh.com", 0);
190 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
191 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
193 c->open_confirm_ctx = NULL;
194 buffer_free(&cctx->cmd);
196 if (cctx->env != NULL) {
197 for (i = 0; cctx->env[i] != NULL; i++)
205 * Accept a connection on the mux master socket and process the
206 * client's request. Returns flag indicating whether mux master should
207 * begin graceful close.
210 muxserver_accept_control(void)
214 int client_fd, new_fd[3], ver, allowed, window, packetmax;
216 struct sockaddr_storage addr;
217 struct mux_session_confirm_ctx *cctx;
219 u_int i, j, len, env_len, mux_command, flags, escape_char;
225 * Accept connection on control socket
227 memset(&addr, 0, sizeof(addr));
228 addrlen = sizeof(addr);
229 if ((client_fd = accept(muxserver_sock,
230 (struct sockaddr*)&addr, &addrlen)) == -1) {
231 error("%s accept: %s", __func__, strerror(errno));
235 if (getpeereid(client_fd, &euid, &egid) < 0) {
236 error("%s getpeereid failed: %s", __func__, strerror(errno));
240 if ((euid != 0) && (getuid() != euid)) {
241 error("control mode uid mismatch: peer euid %u != uid %u",
242 (u_int) euid, (u_int) getuid());
247 /* XXX handle asynchronously */
248 unset_nonblock(client_fd);
252 if (ssh_msg_recv(client_fd, &m) == -1) {
253 error("%s: client msg_recv failed", __func__);
258 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
259 error("%s: wrong client version %d", __func__, ver);
266 mux_command = buffer_get_int(&m);
267 flags = buffer_get_int(&m);
271 switch (mux_command) {
272 case SSHMUX_COMMAND_OPEN:
273 if (options.control_master == SSHCTL_MASTER_ASK ||
274 options.control_master == SSHCTL_MASTER_AUTO_ASK)
275 allowed = ask_permission("Allow shared connection "
279 case SSHMUX_COMMAND_TERMINATE:
280 if (options.control_master == SSHCTL_MASTER_ASK ||
281 options.control_master == SSHCTL_MASTER_AUTO_ASK)
282 allowed = ask_permission("Terminate shared connection "
287 case SSHMUX_COMMAND_ALIVE_CHECK:
288 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
290 buffer_put_int(&m, allowed);
291 buffer_put_int(&m, getpid());
292 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
293 error("%s: client msg_send failed", __func__);
302 error("Unsupported command %d", mux_command);
308 /* Reply for SSHMUX_COMMAND_OPEN */
310 buffer_put_int(&m, allowed);
311 buffer_put_int(&m, getpid());
312 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
313 error("%s: client msg_send failed", __func__);
320 error("Refused control connection");
327 if (ssh_msg_recv(client_fd, &m) == -1) {
328 error("%s: client msg_recv failed", __func__);
333 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
334 error("%s: wrong client version %d", __func__, ver);
340 cctx = xcalloc(1, sizeof(*cctx));
341 cctx->want_tty = (flags & SSHMUX_FLAG_TTY) != 0;
342 cctx->want_subsys = (flags & SSHMUX_FLAG_SUBSYS) != 0;
343 cctx->want_x_fwd = (flags & SSHMUX_FLAG_X11_FWD) != 0;
344 cctx->want_agent_fwd = (flags & SSHMUX_FLAG_AGENT_FWD) != 0;
345 cctx->term = buffer_get_string(&m, &len);
346 escape_char = buffer_get_int(&m);
348 cmd = buffer_get_string(&m, &len);
349 buffer_init(&cctx->cmd);
350 buffer_append(&cctx->cmd, cmd, strlen(cmd));
352 env_len = buffer_get_int(&m);
353 env_len = MIN(env_len, 4096);
354 debug3("%s: receiving %d env vars", __func__, env_len);
356 cctx->env = xcalloc(env_len + 1, sizeof(*cctx->env));
357 for (i = 0; i < env_len; i++)
358 cctx->env[i] = buffer_get_string(&m, &len);
362 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
363 cctx->want_tty, cctx->want_subsys, cmd);
366 /* Gather fds from client */
367 for(i = 0; i < 3; i++) {
368 if ((new_fd[i] = mm_receive_fd(client_fd)) == -1) {
369 error("%s: failed to receive fd %d from slave",
371 for (j = 0; j < i; j++)
373 for (j = 0; j < env_len; j++)
378 buffer_free(&cctx->cmd);
385 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
386 new_fd[0], new_fd[1], new_fd[2]);
388 /* Try to pick up ttymodes from client before it goes raw */
389 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
390 error("%s: tcgetattr: %s", __func__, strerror(errno));
392 /* This roundtrip is just for synchronisation of ttymodes */
394 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
395 error("%s: client msg_send failed", __func__);
403 for (i = 0; i < env_len; i++)
411 /* enable nonblocking unless tty */
412 if (!isatty(new_fd[0]))
413 set_nonblock(new_fd[0]);
414 if (!isatty(new_fd[1]))
415 set_nonblock(new_fd[1]);
416 if (!isatty(new_fd[2]))
417 set_nonblock(new_fd[2]);
419 set_nonblock(client_fd);
421 window = CHAN_SES_WINDOW_DEFAULT;
422 packetmax = CHAN_SES_PACKET_DEFAULT;
423 if (cctx->want_tty) {
428 c = channel_new("session", SSH_CHANNEL_OPENING,
429 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
430 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
432 c->ctl_fd = client_fd;
433 if (cctx->want_tty && escape_char != 0xffffffff) {
434 channel_register_filter(c->self,
435 client_simple_escape_filter, NULL,
436 client_new_escape_filter_ctx((int)escape_char));
439 debug3("%s: channel_new: %d", __func__, c->self);
441 channel_send_open(c->self);
442 channel_register_open_confirm(c->self, mux_session_confirm, cctx);
446 /* ** Multiplexing client support */
448 /* Exit signal handler */
450 control_client_sighandler(int signo)
452 muxclient_terminate = signo;
456 * Relay signal handler - used to pass some signals from mux client to
460 control_client_sigrelay(int signo)
462 int save_errno = errno;
464 if (muxserver_pid > 1)
465 kill(muxserver_pid, signo);
470 /* Check mux client environment variables before passing them to mux master. */
472 env_permitted(char *env)
475 char name[1024], *cp;
477 if ((cp = strchr(env, '=')) == NULL || cp == env)
479 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
480 if (ret <= 0 || (size_t)ret >= sizeof(name))
481 fatal("env_permitted: name '%.100s...' too long", env);
483 for (i = 0; i < options.num_send_env; i++)
484 if (match_pattern(name, options.send_env[i]))
490 /* Multiplex client main loop. */
492 muxclient(const char *path)
494 struct sockaddr_un addr;
495 int i, r, fd, sock, exitval[2], num_env, addr_len;
498 extern char **environ;
501 if (muxclient_command == 0)
502 muxclient_command = SSHMUX_COMMAND_OPEN;
504 switch (options.control_master) {
505 case SSHCTL_MASTER_AUTO:
506 case SSHCTL_MASTER_AUTO_ASK:
507 debug("auto-mux: Trying existing master");
509 case SSHCTL_MASTER_NO:
515 memset(&addr, '\0', sizeof(addr));
516 addr.sun_family = AF_UNIX;
517 addr_len = offsetof(struct sockaddr_un, sun_path) +
520 if (strlcpy(addr.sun_path, path,
521 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
522 fatal("ControlPath too long");
524 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
525 fatal("%s socket(): %s", __func__, strerror(errno));
527 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
528 if (muxclient_command != SSHMUX_COMMAND_OPEN) {
529 fatal("Control socket connect(%.100s): %s", path,
533 debug("Control socket \"%.100s\" does not exist", path);
535 error("Control socket connect(%.100s): %s", path,
542 if (stdin_null_flag) {
543 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
544 fatal("open(/dev/null): %s", strerror(errno));
545 if (dup2(fd, STDIN_FILENO) == -1)
546 fatal("dup2: %s", strerror(errno));
547 if (fd > STDERR_FILENO)
551 term = getenv("TERM");
555 flags |= SSHMUX_FLAG_TTY;
557 flags |= SSHMUX_FLAG_SUBSYS;
558 if (options.forward_x11)
559 flags |= SSHMUX_FLAG_X11_FWD;
560 if (options.forward_agent)
561 flags |= SSHMUX_FLAG_AGENT_FWD;
563 signal(SIGPIPE, SIG_IGN);
567 /* Send our command to server */
568 buffer_put_int(&m, muxclient_command);
569 buffer_put_int(&m, flags);
570 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
571 fatal("%s: msg_send", __func__);
574 /* Get authorisation status and PID of controlee */
575 if (ssh_msg_recv(sock, &m) == -1)
576 fatal("%s: msg_recv", __func__);
577 if (buffer_get_char(&m) != SSHMUX_VER)
578 fatal("%s: wrong version", __func__);
579 if (buffer_get_int(&m) != 1)
580 fatal("Connection to master denied");
581 muxserver_pid = buffer_get_int(&m);
585 switch (muxclient_command) {
586 case SSHMUX_COMMAND_ALIVE_CHECK:
587 fprintf(stderr, "Master running (pid=%d)\r\n",
590 case SSHMUX_COMMAND_TERMINATE:
591 fprintf(stderr, "Exit request sent.\r\n");
593 case SSHMUX_COMMAND_OPEN:
594 buffer_put_cstring(&m, term ? term : "");
595 if (options.escape_char == SSH_ESCAPECHAR_NONE)
596 buffer_put_int(&m, 0xffffffff);
598 buffer_put_int(&m, options.escape_char);
599 buffer_append(&command, "\0", 1);
600 buffer_put_cstring(&m, buffer_ptr(&command));
602 if (options.num_send_env == 0 || environ == NULL) {
603 buffer_put_int(&m, 0);
605 /* Pass environment */
607 for (i = 0; environ[i] != NULL; i++) {
608 if (env_permitted(environ[i]))
609 num_env++; /* Count */
611 buffer_put_int(&m, num_env);
612 for (i = 0; environ[i] != NULL && num_env >= 0; i++) {
613 if (env_permitted(environ[i])) {
615 buffer_put_cstring(&m, environ[i]);
621 fatal("unrecognised muxclient_command %d", muxclient_command);
624 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
625 fatal("%s: msg_send", __func__);
627 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
628 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
629 mm_send_fd(sock, STDERR_FILENO) == -1)
630 fatal("%s: send fds failed", __func__);
632 /* Wait for reply, so master has a chance to gather ttymodes */
634 if (ssh_msg_recv(sock, &m) == -1)
635 fatal("%s: msg_recv", __func__);
636 if (buffer_get_char(&m) != SSHMUX_VER)
637 fatal("%s: wrong version", __func__);
640 signal(SIGHUP, control_client_sighandler);
641 signal(SIGINT, control_client_sighandler);
642 signal(SIGTERM, control_client_sighandler);
643 signal(SIGWINCH, control_client_sigrelay);
649 * Stick around until the controlee closes the client_fd.
650 * Before it does, it is expected to write this process' exit
651 * value (one int). This process must read the value and wait for
652 * the closure of the client_fd; if this one closes early, the
653 * multiplex master will terminate early too (possibly losing data).
656 for (i = 0; !muxclient_terminate && i < (int)sizeof(exitval);) {
657 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
659 debug2("Received EOF from master");
665 fatal("%s: read %s", __func__, strerror(errno));
672 if (i > (int)sizeof(int))
673 fatal("%s: master returned too much data (%d > %lu)",
674 __func__, i, sizeof(int));
675 if (muxclient_terminate) {
676 debug2("Exiting on signal %d", muxclient_terminate);
678 } else if (i < (int)sizeof(int)) {
679 debug2("Control master terminated unexpectedly");
682 debug2("Received exit status from master %d", exitval[0]);
684 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
685 fprintf(stderr, "Shared connection to %s closed.\r\n", host);