1 /* $OpenBSD: mux.c,v 1.4 2008/06/12 15:19:17 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 Options options;
86 extern int stdin_null_flag;
89 extern Buffer command;
91 /* Context for session open confirmation callback */
92 struct mux_session_confirm_ctx {
103 /* fd to control socket */
104 int muxserver_sock = -1;
106 /* Multiplexing control command */
107 u_int muxclient_command = 0;
109 /* Set when signalled. */
110 static volatile sig_atomic_t muxclient_terminate = 0;
112 /* PID of multiplex server */
113 static u_int muxserver_pid = 0;
116 /* ** Multiplexing master support */
118 /* Prepare a mux master to listen on a Unix domain socket. */
120 muxserver_listen(void)
122 struct sockaddr_un addr;
126 if (options.control_path == NULL ||
127 options.control_master == SSHCTL_MASTER_NO)
130 debug("setting up multiplex master socket");
132 memset(&addr, '\0', sizeof(addr));
133 addr.sun_family = AF_UNIX;
134 addr_len = offsetof(struct sockaddr_un, sun_path) +
135 strlen(options.control_path) + 1;
137 if (strlcpy(addr.sun_path, options.control_path,
138 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
139 fatal("ControlPath too long");
141 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
142 fatal("%s socket(): %s", __func__, strerror(errno));
144 old_umask = umask(0177);
145 if (bind(muxserver_sock, (struct sockaddr *)&addr, addr_len) == -1) {
147 if (errno == EINVAL || errno == EADDRINUSE)
148 fatal("ControlSocket %s already exists",
149 options.control_path);
151 fatal("%s bind(): %s", __func__, strerror(errno));
155 if (listen(muxserver_sock, 64) == -1)
156 fatal("%s listen(): %s", __func__, strerror(errno));
158 set_nonblock(muxserver_sock);
161 /* Callback on open confirmation in mux master for a mux client session. */
163 mux_session_confirm(int id, void *arg)
165 struct mux_session_confirm_ctx *cctx = arg;
171 fatal("%s: cctx == NULL", __func__);
172 if ((c = channel_lookup(id)) == NULL)
173 fatal("%s: no channel for id %d", __func__, id);
175 display = getenv("DISPLAY");
176 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
178 /* Get reasonable local authentication information. */
179 client_x11_get_proto(display, options.xauth_location,
180 options.forward_x11_trusted, &proto, &data);
181 /* Request forwarding with authentication spoofing. */
182 debug("Requesting X11 forwarding with authentication spoofing.");
183 x11_request_forwarding_with_spoofing(id, display, proto, data);
184 /* XXX wait for reply */
187 if (cctx->want_agent_fwd && options.forward_agent) {
188 debug("Requesting authentication agent forwarding.");
189 channel_request_start(id, "auth-agent-req@openssh.com", 0);
193 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
194 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
196 c->open_confirm_ctx = NULL;
197 buffer_free(&cctx->cmd);
199 if (cctx->env != NULL) {
200 for (i = 0; cctx->env[i] != NULL; i++)
208 * Accept a connection on the mux master socket and process the
209 * client's request. Returns flag indicating whether mux master should
210 * begin graceful close.
213 muxserver_accept_control(void)
217 int client_fd, new_fd[3], ver, allowed, window, packetmax;
219 struct sockaddr_storage addr;
220 struct mux_session_confirm_ctx *cctx;
222 u_int i, j, len, env_len, mux_command, flags, escape_char;
228 * Accept connection on control socket
230 memset(&addr, 0, sizeof(addr));
231 addrlen = sizeof(addr);
232 if ((client_fd = accept(muxserver_sock,
233 (struct sockaddr*)&addr, &addrlen)) == -1) {
234 error("%s accept: %s", __func__, strerror(errno));
238 if (getpeereid(client_fd, &euid, &egid) < 0) {
239 error("%s getpeereid failed: %s", __func__, strerror(errno));
243 if ((euid != 0) && (getuid() != euid)) {
244 error("control mode uid mismatch: peer euid %u != uid %u",
245 (u_int) euid, (u_int) getuid());
250 /* XXX handle asynchronously */
251 unset_nonblock(client_fd);
255 if (ssh_msg_recv(client_fd, &m) == -1) {
256 error("%s: client msg_recv failed", __func__);
261 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
262 error("%s: wrong client version %d", __func__, ver);
269 mux_command = buffer_get_int(&m);
270 flags = buffer_get_int(&m);
274 switch (mux_command) {
275 case SSHMUX_COMMAND_OPEN:
276 if (options.control_master == SSHCTL_MASTER_ASK ||
277 options.control_master == SSHCTL_MASTER_AUTO_ASK)
278 allowed = ask_permission("Allow shared connection "
282 case SSHMUX_COMMAND_TERMINATE:
283 if (options.control_master == SSHCTL_MASTER_ASK ||
284 options.control_master == SSHCTL_MASTER_AUTO_ASK)
285 allowed = ask_permission("Terminate shared connection "
290 case SSHMUX_COMMAND_ALIVE_CHECK:
291 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
293 buffer_put_int(&m, allowed);
294 buffer_put_int(&m, getpid());
295 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
296 error("%s: client msg_send failed", __func__);
305 error("Unsupported command %d", mux_command);
311 /* Reply for SSHMUX_COMMAND_OPEN */
313 buffer_put_int(&m, allowed);
314 buffer_put_int(&m, getpid());
315 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
316 error("%s: client msg_send failed", __func__);
323 error("Refused control connection");
330 if (ssh_msg_recv(client_fd, &m) == -1) {
331 error("%s: client msg_recv failed", __func__);
336 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
337 error("%s: wrong client version %d", __func__, ver);
343 cctx = xcalloc(1, sizeof(*cctx));
344 cctx->want_tty = (flags & SSHMUX_FLAG_TTY) != 0;
345 cctx->want_subsys = (flags & SSHMUX_FLAG_SUBSYS) != 0;
346 cctx->want_x_fwd = (flags & SSHMUX_FLAG_X11_FWD) != 0;
347 cctx->want_agent_fwd = (flags & SSHMUX_FLAG_AGENT_FWD) != 0;
348 cctx->term = buffer_get_string(&m, &len);
349 escape_char = buffer_get_int(&m);
351 cmd = buffer_get_string(&m, &len);
352 buffer_init(&cctx->cmd);
353 buffer_append(&cctx->cmd, cmd, strlen(cmd));
355 env_len = buffer_get_int(&m);
356 env_len = MIN(env_len, 4096);
357 debug3("%s: receiving %d env vars", __func__, env_len);
359 cctx->env = xcalloc(env_len + 1, sizeof(*cctx->env));
360 for (i = 0; i < env_len; i++)
361 cctx->env[i] = buffer_get_string(&m, &len);
365 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
366 cctx->want_tty, cctx->want_subsys, cmd);
369 /* Gather fds from client */
370 for(i = 0; i < 3; i++) {
371 if ((new_fd[i] = mm_receive_fd(client_fd)) == -1) {
372 error("%s: failed to receive fd %d from slave",
374 for (j = 0; j < i; j++)
376 for (j = 0; j < env_len; j++)
381 buffer_free(&cctx->cmd);
388 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
389 new_fd[0], new_fd[1], new_fd[2]);
391 /* Try to pick up ttymodes from client before it goes raw */
392 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
393 error("%s: tcgetattr: %s", __func__, strerror(errno));
395 /* This roundtrip is just for synchronisation of ttymodes */
397 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
398 error("%s: client msg_send failed", __func__);
406 for (i = 0; i < env_len; i++)
414 /* enable nonblocking unless tty */
415 if (!isatty(new_fd[0]))
416 set_nonblock(new_fd[0]);
417 if (!isatty(new_fd[1]))
418 set_nonblock(new_fd[1]);
419 if (!isatty(new_fd[2]))
420 set_nonblock(new_fd[2]);
422 set_nonblock(client_fd);
424 window = CHAN_SES_WINDOW_DEFAULT;
425 packetmax = CHAN_SES_PACKET_DEFAULT;
426 if (cctx->want_tty) {
431 c = channel_new("session", SSH_CHANNEL_OPENING,
432 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
433 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
435 c->ctl_fd = client_fd;
436 if (cctx->want_tty && escape_char != 0xffffffff) {
437 channel_register_filter(c->self,
438 client_simple_escape_filter, NULL,
439 client_filter_cleanup,
440 client_new_escape_filter_ctx((int)escape_char));
443 debug3("%s: channel_new: %d", __func__, c->self);
445 channel_send_open(c->self);
446 channel_register_open_confirm(c->self, mux_session_confirm, cctx);
450 /* ** Multiplexing client support */
452 /* Exit signal handler */
454 control_client_sighandler(int signo)
456 muxclient_terminate = signo;
460 * Relay signal handler - used to pass some signals from mux client to
464 control_client_sigrelay(int signo)
466 int save_errno = errno;
468 if (muxserver_pid > 1)
469 kill(muxserver_pid, signo);
474 /* Check mux client environment variables before passing them to mux master. */
476 env_permitted(char *env)
479 char name[1024], *cp;
481 if ((cp = strchr(env, '=')) == NULL || cp == env)
483 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
484 if (ret <= 0 || (size_t)ret >= sizeof(name))
485 fatal("env_permitted: name '%.100s...' too long", env);
487 for (i = 0; i < options.num_send_env; i++)
488 if (match_pattern(name, options.send_env[i]))
494 /* Multiplex client main loop. */
496 muxclient(const char *path)
498 struct sockaddr_un addr;
499 int i, r, fd, sock, exitval[2], num_env, addr_len;
502 extern char **environ;
505 if (muxclient_command == 0)
506 muxclient_command = SSHMUX_COMMAND_OPEN;
508 switch (options.control_master) {
509 case SSHCTL_MASTER_AUTO:
510 case SSHCTL_MASTER_AUTO_ASK:
511 debug("auto-mux: Trying existing master");
513 case SSHCTL_MASTER_NO:
519 memset(&addr, '\0', sizeof(addr));
520 addr.sun_family = AF_UNIX;
521 addr_len = offsetof(struct sockaddr_un, sun_path) +
524 if (strlcpy(addr.sun_path, path,
525 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
526 fatal("ControlPath too long");
528 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
529 fatal("%s socket(): %s", __func__, strerror(errno));
531 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
532 if (muxclient_command != SSHMUX_COMMAND_OPEN) {
533 fatal("Control socket connect(%.100s): %s", path,
537 debug("Control socket \"%.100s\" does not exist", path);
539 error("Control socket connect(%.100s): %s", path,
546 if (stdin_null_flag) {
547 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
548 fatal("open(/dev/null): %s", strerror(errno));
549 if (dup2(fd, STDIN_FILENO) == -1)
550 fatal("dup2: %s", strerror(errno));
551 if (fd > STDERR_FILENO)
555 term = getenv("TERM");
559 flags |= SSHMUX_FLAG_TTY;
561 flags |= SSHMUX_FLAG_SUBSYS;
562 if (options.forward_x11)
563 flags |= SSHMUX_FLAG_X11_FWD;
564 if (options.forward_agent)
565 flags |= SSHMUX_FLAG_AGENT_FWD;
567 signal(SIGPIPE, SIG_IGN);
571 /* Send our command to server */
572 buffer_put_int(&m, muxclient_command);
573 buffer_put_int(&m, flags);
574 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
575 fatal("%s: msg_send", __func__);
578 /* Get authorisation status and PID of controlee */
579 if (ssh_msg_recv(sock, &m) == -1)
580 fatal("%s: msg_recv", __func__);
581 if (buffer_get_char(&m) != SSHMUX_VER)
582 fatal("%s: wrong version", __func__);
583 if (buffer_get_int(&m) != 1)
584 fatal("Connection to master denied");
585 muxserver_pid = buffer_get_int(&m);
589 switch (muxclient_command) {
590 case SSHMUX_COMMAND_ALIVE_CHECK:
591 fprintf(stderr, "Master running (pid=%d)\r\n",
594 case SSHMUX_COMMAND_TERMINATE:
595 fprintf(stderr, "Exit request sent.\r\n");
597 case SSHMUX_COMMAND_OPEN:
598 buffer_put_cstring(&m, term ? term : "");
599 if (options.escape_char == SSH_ESCAPECHAR_NONE)
600 buffer_put_int(&m, 0xffffffff);
602 buffer_put_int(&m, options.escape_char);
603 buffer_append(&command, "\0", 1);
604 buffer_put_cstring(&m, buffer_ptr(&command));
606 if (options.num_send_env == 0 || environ == NULL) {
607 buffer_put_int(&m, 0);
609 /* Pass environment */
611 for (i = 0; environ[i] != NULL; i++) {
612 if (env_permitted(environ[i]))
613 num_env++; /* Count */
615 buffer_put_int(&m, num_env);
616 for (i = 0; environ[i] != NULL && num_env >= 0; i++) {
617 if (env_permitted(environ[i])) {
619 buffer_put_cstring(&m, environ[i]);
625 fatal("unrecognised muxclient_command %d", muxclient_command);
628 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
629 fatal("%s: msg_send", __func__);
631 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
632 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
633 mm_send_fd(sock, STDERR_FILENO) == -1)
634 fatal("%s: send fds failed", __func__);
636 /* Wait for reply, so master has a chance to gather ttymodes */
638 if (ssh_msg_recv(sock, &m) == -1)
639 fatal("%s: msg_recv", __func__);
640 if (buffer_get_char(&m) != SSHMUX_VER)
641 fatal("%s: wrong version", __func__);
644 signal(SIGHUP, control_client_sighandler);
645 signal(SIGINT, control_client_sighandler);
646 signal(SIGTERM, control_client_sighandler);
647 signal(SIGWINCH, control_client_sigrelay);
653 * Stick around until the controlee closes the client_fd.
654 * Before it does, it is expected to write this process' exit
655 * value (one int). This process must read the value and wait for
656 * the closure of the client_fd; if this one closes early, the
657 * multiplex master will terminate early too (possibly losing data).
660 for (i = 0; !muxclient_terminate && i < (int)sizeof(exitval);) {
661 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
663 debug2("Received EOF from master");
669 fatal("%s: read %s", __func__, strerror(errno));
676 if (i > (int)sizeof(int))
677 fatal("%s: master returned too much data (%d > %lu)",
678 __func__, i, sizeof(int));
679 if (muxclient_terminate) {
680 debug2("Exiting on signal %d", muxclient_terminate);
682 } else if (i < (int)sizeof(int)) {
683 debug2("Control master terminated unexpectedly");
686 debug2("Received exit status from master %d", exitval[0]);
688 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
689 fprintf(stderr, "Shared connection to %s closed.\r\n", host);