1 /* $OpenBSD: mux.c,v 1.8 2009/08/20 23:54:28 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 */
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
;
88 extern int subsystem_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 error("ControlSocket %s already exists, "
149 "disabling multiplexing", options
.control_path
);
150 close(muxserver_sock
);
152 xfree(options
.control_path
);
153 options
.control_path
= NULL
;
154 options
.control_master
= SSHCTL_MASTER_NO
;
157 fatal("%s bind(): %s", __func__
, strerror(errno
));
161 if (listen(muxserver_sock
, 64) == -1)
162 fatal("%s listen(): %s", __func__
, strerror(errno
));
164 set_nonblock(muxserver_sock
);
167 /* Callback on open confirmation in mux master for a mux client session. */
169 mux_session_confirm(int id
, void *arg
)
171 struct mux_session_confirm_ctx
*cctx
= arg
;
177 fatal("%s: cctx == NULL", __func__
);
178 if ((c
= channel_lookup(id
)) == NULL
)
179 fatal("%s: no channel for id %d", __func__
, id
);
181 display
= getenv("DISPLAY");
182 if (cctx
->want_x_fwd
&& options
.forward_x11
&& display
!= NULL
) {
184 /* Get reasonable local authentication information. */
185 client_x11_get_proto(display
, options
.xauth_location
,
186 options
.forward_x11_trusted
, &proto
, &data
);
187 /* Request forwarding with authentication spoofing. */
188 debug("Requesting X11 forwarding with authentication spoofing.");
189 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
190 /* XXX wait for reply */
193 if (cctx
->want_agent_fwd
&& options
.forward_agent
) {
194 debug("Requesting authentication agent forwarding.");
195 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
199 client_session2_setup(id
, cctx
->want_tty
, cctx
->want_subsys
,
200 cctx
->term
, &cctx
->tio
, c
->rfd
, &cctx
->cmd
, cctx
->env
);
202 c
->open_confirm_ctx
= NULL
;
203 buffer_free(&cctx
->cmd
);
205 if (cctx
->env
!= NULL
) {
206 for (i
= 0; cctx
->env
[i
] != NULL
; i
++)
214 * Accept a connection on the mux master socket and process the
215 * client's request. Returns flag indicating whether mux master should
216 * begin graceful close.
219 muxserver_accept_control(void)
223 int client_fd
, new_fd
[3], ver
, allowed
, window
, packetmax
;
225 struct sockaddr_storage addr
;
226 struct mux_session_confirm_ctx
*cctx
;
228 u_int i
, j
, len
, env_len
, mux_command
, flags
, escape_char
;
234 * Accept connection on control socket
236 memset(&addr
, 0, sizeof(addr
));
237 addrlen
= sizeof(addr
);
238 if ((client_fd
= accept(muxserver_sock
,
239 (struct sockaddr
*)&addr
, &addrlen
)) == -1) {
240 error("%s accept: %s", __func__
, strerror(errno
));
244 if (getpeereid(client_fd
, &euid
, &egid
) < 0) {
245 error("%s getpeereid failed: %s", __func__
, strerror(errno
));
249 if ((euid
!= 0) && (getuid() != euid
)) {
250 error("control mode uid mismatch: peer euid %u != uid %u",
251 (u_int
) euid
, (u_int
) getuid());
256 /* XXX handle asynchronously */
257 unset_nonblock(client_fd
);
261 if (ssh_msg_recv(client_fd
, &m
) == -1) {
262 error("%s: client msg_recv failed", __func__
);
267 if ((ver
= buffer_get_char(&m
)) != SSHMUX_VER
) {
268 error("%s: wrong client version %d", __func__
, ver
);
275 mux_command
= buffer_get_int(&m
);
276 flags
= buffer_get_int(&m
);
280 switch (mux_command
) {
281 case SSHMUX_COMMAND_OPEN
:
282 if (options
.control_master
== SSHCTL_MASTER_ASK
||
283 options
.control_master
== SSHCTL_MASTER_AUTO_ASK
)
284 allowed
= ask_permission("Allow shared connection "
288 case SSHMUX_COMMAND_TERMINATE
:
289 if (options
.control_master
== SSHCTL_MASTER_ASK
||
290 options
.control_master
== SSHCTL_MASTER_AUTO_ASK
)
291 allowed
= ask_permission("Terminate shared connection "
296 case SSHMUX_COMMAND_ALIVE_CHECK
:
297 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
299 buffer_put_int(&m
, allowed
);
300 buffer_put_int(&m
, getpid());
301 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
302 error("%s: client msg_send failed", __func__
);
311 error("Unsupported command %d", mux_command
);
317 /* Reply for SSHMUX_COMMAND_OPEN */
319 buffer_put_int(&m
, allowed
);
320 buffer_put_int(&m
, getpid());
321 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
322 error("%s: client msg_send failed", __func__
);
329 error("Refused control connection");
336 if (ssh_msg_recv(client_fd
, &m
) == -1) {
337 error("%s: client msg_recv failed", __func__
);
342 if ((ver
= buffer_get_char(&m
)) != SSHMUX_VER
) {
343 error("%s: wrong client version %d", __func__
, ver
);
349 cctx
= xcalloc(1, sizeof(*cctx
));
350 cctx
->want_tty
= (flags
& SSHMUX_FLAG_TTY
) != 0;
351 cctx
->want_subsys
= (flags
& SSHMUX_FLAG_SUBSYS
) != 0;
352 cctx
->want_x_fwd
= (flags
& SSHMUX_FLAG_X11_FWD
) != 0;
353 cctx
->want_agent_fwd
= (flags
& SSHMUX_FLAG_AGENT_FWD
) != 0;
354 cctx
->term
= buffer_get_string(&m
, &len
);
355 escape_char
= buffer_get_int(&m
);
357 cmd
= buffer_get_string(&m
, &len
);
358 buffer_init(&cctx
->cmd
);
359 buffer_append(&cctx
->cmd
, cmd
, strlen(cmd
));
361 env_len
= buffer_get_int(&m
);
362 env_len
= MIN(env_len
, 4096);
363 debug3("%s: receiving %d env vars", __func__
, env_len
);
365 cctx
->env
= xcalloc(env_len
+ 1, sizeof(*cctx
->env
));
366 for (i
= 0; i
< env_len
; i
++)
367 cctx
->env
[i
] = buffer_get_string(&m
, &len
);
371 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__
,
372 cctx
->want_tty
, cctx
->want_subsys
, cmd
);
375 /* Gather fds from client */
376 for(i
= 0; i
< 3; i
++) {
377 if ((new_fd
[i
] = mm_receive_fd(client_fd
)) == -1) {
378 error("%s: failed to receive fd %d from slave",
380 for (j
= 0; j
< i
; j
++)
382 for (j
= 0; j
< env_len
; j
++)
387 buffer_free(&cctx
->cmd
);
394 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__
,
395 new_fd
[0], new_fd
[1], new_fd
[2]);
397 /* Try to pick up ttymodes from client before it goes raw */
398 if (cctx
->want_tty
&& tcgetattr(new_fd
[0], &cctx
->tio
) == -1)
399 error("%s: tcgetattr: %s", __func__
, strerror(errno
));
401 /* This roundtrip is just for synchronisation of ttymodes */
403 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
404 error("%s: client msg_send failed", __func__
);
412 for (i
= 0; i
< env_len
; i
++)
420 /* enable nonblocking unless tty */
421 if (!isatty(new_fd
[0]))
422 set_nonblock(new_fd
[0]);
423 if (!isatty(new_fd
[1]))
424 set_nonblock(new_fd
[1]);
425 if (!isatty(new_fd
[2]))
426 set_nonblock(new_fd
[2]);
428 set_nonblock(client_fd
);
430 window
= CHAN_SES_WINDOW_DEFAULT
;
431 packetmax
= CHAN_SES_PACKET_DEFAULT
;
432 if (cctx
->want_tty
) {
437 c
= channel_new("session", SSH_CHANNEL_OPENING
,
438 new_fd
[0], new_fd
[1], new_fd
[2], window
, packetmax
,
439 CHAN_EXTENDED_WRITE
, "client-session", /*nonblock*/0);
441 c
->ctl_fd
= client_fd
;
442 if (cctx
->want_tty
&& escape_char
!= 0xffffffff) {
443 channel_register_filter(c
->self
,
444 client_simple_escape_filter
, NULL
,
445 client_filter_cleanup
,
446 client_new_escape_filter_ctx((int)escape_char
));
449 debug3("%s: channel_new: %d", __func__
, c
->self
);
451 channel_send_open(c
->self
);
452 channel_register_open_confirm(c
->self
, mux_session_confirm
, cctx
);
456 /* ** Multiplexing client support */
458 /* Exit signal handler */
460 control_client_sighandler(int signo
)
462 muxclient_terminate
= signo
;
466 * Relay signal handler - used to pass some signals from mux client to
470 control_client_sigrelay(int signo
)
472 int save_errno
= errno
;
474 if (muxserver_pid
> 1)
475 kill(muxserver_pid
, signo
);
480 /* Check mux client environment variables before passing them to mux master. */
482 env_permitted(char *env
)
485 char name
[1024], *cp
;
487 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
489 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
490 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
491 fatal("env_permitted: name '%.100s...' too long", env
);
493 for (i
= 0; i
< options
.num_send_env
; i
++)
494 if (match_pattern(name
, options
.send_env
[i
]))
500 /* Multiplex client main loop. */
502 muxclient(const char *path
)
504 struct sockaddr_un addr
;
505 int i
, r
, fd
, sock
, exitval
[2], num_env
, addr_len
;
508 extern char **environ
;
509 u_int allowed
, flags
;
511 if (muxclient_command
== 0)
512 muxclient_command
= SSHMUX_COMMAND_OPEN
;
514 switch (options
.control_master
) {
515 case SSHCTL_MASTER_AUTO
:
516 case SSHCTL_MASTER_AUTO_ASK
:
517 debug("auto-mux: Trying existing master");
519 case SSHCTL_MASTER_NO
:
525 memset(&addr
, '\0', sizeof(addr
));
526 addr
.sun_family
= AF_UNIX
;
527 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
530 if (strlcpy(addr
.sun_path
, path
,
531 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
532 fatal("ControlPath too long");
534 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
535 fatal("%s socket(): %s", __func__
, strerror(errno
));
537 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
538 if (muxclient_command
!= SSHMUX_COMMAND_OPEN
) {
539 fatal("Control socket connect(%.100s): %s", path
,
543 debug("Control socket \"%.100s\" does not exist", path
);
545 error("Control socket connect(%.100s): %s", path
,
552 if (stdin_null_flag
) {
553 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
554 fatal("open(/dev/null): %s", strerror(errno
));
555 if (dup2(fd
, STDIN_FILENO
) == -1)
556 fatal("dup2: %s", strerror(errno
));
557 if (fd
> STDERR_FILENO
)
561 term
= getenv("TERM");
565 flags
|= SSHMUX_FLAG_TTY
;
567 flags
|= SSHMUX_FLAG_SUBSYS
;
568 if (options
.forward_x11
)
569 flags
|= SSHMUX_FLAG_X11_FWD
;
570 if (options
.forward_agent
)
571 flags
|= SSHMUX_FLAG_AGENT_FWD
;
573 signal(SIGPIPE
, SIG_IGN
);
577 /* Send our command to server */
578 buffer_put_int(&m
, muxclient_command
);
579 buffer_put_int(&m
, flags
);
580 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1) {
581 error("%s: msg_send", __func__
);
585 if (muxclient_command
!= SSHMUX_COMMAND_OPEN
)
587 logit("Falling back to non-multiplexed connection");
588 xfree(options
.control_path
);
589 options
.control_path
= NULL
;
590 options
.control_master
= SSHCTL_MASTER_NO
;
595 /* Get authorisation status and PID of controlee */
596 if (ssh_msg_recv(sock
, &m
) == -1) {
597 error("%s: Did not receive reply from master", __func__
);
600 if (buffer_get_char(&m
) != SSHMUX_VER
) {
601 error("%s: Master replied with wrong version", __func__
);
604 if (buffer_get_int_ret(&allowed
, &m
) != 0) {
605 error("%s: bad server reply", __func__
);
609 error("Connection to master denied");
612 muxserver_pid
= buffer_get_int(&m
);
616 switch (muxclient_command
) {
617 case SSHMUX_COMMAND_ALIVE_CHECK
:
618 fprintf(stderr
, "Master running (pid=%d)\r\n",
621 case SSHMUX_COMMAND_TERMINATE
:
622 fprintf(stderr
, "Exit request sent.\r\n");
624 case SSHMUX_COMMAND_OPEN
:
625 buffer_put_cstring(&m
, term
? term
: "");
626 if (options
.escape_char
== SSH_ESCAPECHAR_NONE
)
627 buffer_put_int(&m
, 0xffffffff);
629 buffer_put_int(&m
, options
.escape_char
);
630 buffer_append(&command
, "\0", 1);
631 buffer_put_cstring(&m
, buffer_ptr(&command
));
633 if (options
.num_send_env
== 0 || environ
== NULL
) {
634 buffer_put_int(&m
, 0);
636 /* Pass environment */
638 for (i
= 0; environ
[i
] != NULL
; i
++) {
639 if (env_permitted(environ
[i
]))
640 num_env
++; /* Count */
642 buffer_put_int(&m
, num_env
);
643 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++) {
644 if (env_permitted(environ
[i
])) {
646 buffer_put_cstring(&m
, environ
[i
]);
652 fatal("unrecognised muxclient_command %d", muxclient_command
);
655 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1) {
656 error("%s: msg_send", __func__
);
660 if (mm_send_fd(sock
, STDIN_FILENO
) == -1 ||
661 mm_send_fd(sock
, STDOUT_FILENO
) == -1 ||
662 mm_send_fd(sock
, STDERR_FILENO
) == -1) {
663 error("%s: send fds failed", __func__
);
668 * Mux errors are non-recoverable from this point as the master
669 * has ownership of the session now.
672 /* Wait for reply, so master has a chance to gather ttymodes */
674 if (ssh_msg_recv(sock
, &m
) == -1)
675 fatal("%s: msg_recv", __func__
);
676 if (buffer_get_char(&m
) != SSHMUX_VER
)
677 fatal("%s: wrong version", __func__
);
680 signal(SIGHUP
, control_client_sighandler
);
681 signal(SIGINT
, control_client_sighandler
);
682 signal(SIGTERM
, control_client_sighandler
);
683 signal(SIGWINCH
, control_client_sigrelay
);
689 * Stick around until the controlee closes the client_fd.
690 * Before it does, it is expected to write this process' exit
691 * value (one int). This process must read the value and wait for
692 * the closure of the client_fd; if this one closes early, the
693 * multiplex master will terminate early too (possibly losing data).
696 for (i
= 0; !muxclient_terminate
&& i
< (int)sizeof(exitval
);) {
697 r
= read(sock
, (char *)exitval
+ i
, sizeof(exitval
) - i
);
699 debug2("Received EOF from master");
705 fatal("%s: read %s", __func__
, strerror(errno
));
712 if (i
> (int)sizeof(int))
713 fatal("%s: master returned too much data (%d > %lu)",
714 __func__
, i
, (u_long
)sizeof(int));
715 if (muxclient_terminate
) {
716 debug2("Exiting on signal %d", muxclient_terminate
);
718 } else if (i
< (int)sizeof(int)) {
719 debug2("Control master terminated unexpectedly");
722 debug2("Received exit status from master %d", exitval
[0]);
724 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
725 fprintf(stderr
, "Shared connection to %s closed.\r\n", host
);