2 /* $OpenBSD: mux.c,v 1.7 2008/06/13 17:21:20 dtucker Exp $ */
4 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 /* ssh session multiplexing support */
23 * 1. partial reads in muxserver_accept_control (maybe make channels
24 * from accepted connections)
25 * 2. Better signalling from master to slave, especially passing of
27 * 3. Better fall-back from mux slave error to new connection.
28 * 3. Add/delete forwardings via slave
29 * 4. ExitOnForwardingFailure (after #3 obviously)
30 * 5. Maybe extension mechanisms for multi-X11/multi-agent forwarding
31 * 6. Document the mux mini-protocol somewhere.
32 * 7. Support ~^Z in mux slaves.
33 * 8. Inspect or control sessions in master.
34 * 9. If we ever support the "signal" channel request, send signals on
39 __RCSID("$NetBSD: mux.c,v 1.3 2009/02/17 05:28:32 dogcow Exp $");
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/queue.h>
44 #include <sys/socket.h>
62 #include "pathnames.h"
69 #include "monitor_fdpass.h"
73 #include "clientloop.h"
77 extern Options options
;
78 extern int stdin_null_flag
;
81 extern Buffer command
;
83 /* Context for session open confirmation callback */
84 struct mux_session_confirm_ctx
{
95 /* fd to control socket */
96 int muxserver_sock
= -1;
98 /* Multiplexing control command */
99 u_int muxclient_command
= 0;
101 /* Set when signalled. */
102 static volatile sig_atomic_t muxclient_terminate
= 0;
104 /* PID of multiplex server */
105 static u_int muxserver_pid
= 0;
108 /* ** Multiplexing master support */
110 /* Prepare a mux master to listen on a Unix domain socket. */
112 muxserver_listen(void)
114 struct sockaddr_un addr
;
117 if (options
.control_path
== NULL
||
118 options
.control_master
== SSHCTL_MASTER_NO
)
121 debug("setting up multiplex master socket");
123 memset(&addr
, '\0', sizeof(addr
));
124 addr
.sun_family
= AF_UNIX
;
125 addr
.sun_len
= offsetof(struct sockaddr_un
, sun_path
) +
126 strlen(options
.control_path
) + 1;
128 if (strlcpy(addr
.sun_path
, options
.control_path
,
129 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
130 fatal("ControlPath too long");
132 if ((muxserver_sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
133 fatal("%s socket(): %s", __func__
, strerror(errno
));
135 old_umask
= umask(0177);
136 if (bind(muxserver_sock
, (struct sockaddr
*)&addr
, addr
.sun_len
) == -1) {
138 if (errno
== EINVAL
|| errno
== EADDRINUSE
) {
139 error("ControlSocket %s already exists, "
140 "disabling multiplexing", options
.control_path
);
141 close(muxserver_sock
);
143 xfree(options
.control_path
);
144 options
.control_path
= NULL
;
145 options
.control_master
= SSHCTL_MASTER_NO
;
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_filter_cleanup
,
437 client_new_escape_filter_ctx((int)escape_char
));
440 debug3("%s: channel_new: %d", __func__
, c
->self
);
442 channel_send_open(c
->self
);
443 channel_register_open_confirm(c
->self
, mux_session_confirm
, cctx
);
447 /* ** Multiplexing client support */
449 /* Exit signal handler */
451 control_client_sighandler(int signo
)
453 muxclient_terminate
= signo
;
457 * Relay signal handler - used to pass some signals from mux client to
461 control_client_sigrelay(int signo
)
463 int save_errno
= errno
;
465 if (muxserver_pid
> 1)
466 kill(muxserver_pid
, signo
);
471 /* Check mux client environment variables before passing them to mux master. */
473 env_permitted(char *env
)
476 char name
[1024], *cp
;
478 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
480 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
481 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
482 fatal("env_permitted: name '%.100s...' too long", env
);
484 for (i
= 0; i
< options
.num_send_env
; i
++)
485 if (match_pattern(name
, options
.send_env
[i
]))
491 /* Multiplex client main loop. */
493 muxclient(const char *path
)
495 struct sockaddr_un addr
;
496 int i
, r
, fd
, sock
, exitval
[2], num_env
;
499 extern char **environ
;
500 u_int allowed
, flags
;
502 if (muxclient_command
== 0)
503 muxclient_command
= SSHMUX_COMMAND_OPEN
;
505 switch (options
.control_master
) {
506 case SSHCTL_MASTER_AUTO
:
507 case SSHCTL_MASTER_AUTO_ASK
:
508 debug("auto-mux: Trying existing master");
510 case SSHCTL_MASTER_NO
:
516 memset(&addr
, '\0', sizeof(addr
));
517 addr
.sun_family
= AF_UNIX
;
518 addr
.sun_len
= offsetof(struct sockaddr_un
, sun_path
) +
521 if (strlcpy(addr
.sun_path
, path
,
522 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
523 fatal("ControlPath too long");
525 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
526 fatal("%s socket(): %s", __func__
, strerror(errno
));
528 if (connect(sock
, (struct sockaddr
*)&addr
, addr
.sun_len
) == -1) {
529 if (muxclient_command
!= SSHMUX_COMMAND_OPEN
) {
530 fatal("Control socket connect(%.100s): %s", path
,
534 debug("Control socket \"%.100s\" does not exist", path
);
536 error("Control socket connect(%.100s): %s", path
,
543 if (stdin_null_flag
) {
544 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
545 fatal("open(/dev/null): %s", strerror(errno
));
546 if (dup2(fd
, STDIN_FILENO
) == -1)
547 fatal("dup2: %s", strerror(errno
));
548 if (fd
> STDERR_FILENO
)
552 term
= getenv("TERM");
556 flags
|= SSHMUX_FLAG_TTY
;
558 flags
|= SSHMUX_FLAG_SUBSYS
;
559 if (options
.forward_x11
)
560 flags
|= SSHMUX_FLAG_X11_FWD
;
561 if (options
.forward_agent
)
562 flags
|= SSHMUX_FLAG_AGENT_FWD
;
564 signal(SIGPIPE
, SIG_IGN
);
568 /* Send our command to server */
569 buffer_put_int(&m
, muxclient_command
);
570 buffer_put_int(&m
, flags
);
571 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1) {
572 error("%s: msg_send", __func__
);
576 if (muxclient_command
!= SSHMUX_COMMAND_OPEN
)
578 logit("Falling back to non-multiplexed connection");
579 xfree(options
.control_path
);
580 options
.control_path
= NULL
;
581 options
.control_master
= SSHCTL_MASTER_NO
;
586 /* Get authorisation status and PID of controlee */
587 if (ssh_msg_recv(sock
, &m
) == -1) {
588 error("%s: Did not receive reply from master", __func__
);
591 if (buffer_get_char(&m
) != SSHMUX_VER
) {
592 error("%s: Master replied with wrong version", __func__
);
595 if (buffer_get_int_ret(&allowed
, &m
) != 0) {
596 error("%s: bad server reply", __func__
);
600 error("Connection to master denied");
603 muxserver_pid
= buffer_get_int(&m
);
607 switch (muxclient_command
) {
608 case SSHMUX_COMMAND_ALIVE_CHECK
:
609 fprintf(stderr
, "Master running (pid=%d)\r\n",
612 case SSHMUX_COMMAND_TERMINATE
:
613 fprintf(stderr
, "Exit request sent.\r\n");
615 case SSHMUX_COMMAND_OPEN
:
616 buffer_put_cstring(&m
, term
? term
: "");
617 if (options
.escape_char
== SSH_ESCAPECHAR_NONE
)
618 buffer_put_int(&m
, 0xffffffff);
620 buffer_put_int(&m
, options
.escape_char
);
621 buffer_append(&command
, "\0", 1);
622 buffer_put_cstring(&m
, buffer_ptr(&command
));
624 if (options
.num_send_env
== 0 || environ
== NULL
) {
625 buffer_put_int(&m
, 0);
627 /* Pass environment */
629 for (i
= 0; environ
[i
] != NULL
; i
++) {
630 if (env_permitted(environ
[i
]))
631 num_env
++; /* Count */
633 buffer_put_int(&m
, num_env
);
634 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++) {
635 if (env_permitted(environ
[i
])) {
637 buffer_put_cstring(&m
, environ
[i
]);
643 fatal("unrecognised muxclient_command %d", muxclient_command
);
646 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1) {
647 error("%s: msg_send", __func__
);
651 if (mm_send_fd(sock
, STDIN_FILENO
) == -1 ||
652 mm_send_fd(sock
, STDOUT_FILENO
) == -1 ||
653 mm_send_fd(sock
, STDERR_FILENO
) == -1) {
654 error("%s: send fds failed", __func__
);
659 * Mux errors are non-recoverable from this point as the master
660 * has ownership of the session now.
663 /* Wait for reply, so master has a chance to gather ttymodes */
665 if (ssh_msg_recv(sock
, &m
) == -1)
666 fatal("%s: msg_recv", __func__
);
667 if (buffer_get_char(&m
) != SSHMUX_VER
)
668 fatal("%s: wrong version", __func__
);
671 signal(SIGHUP
, control_client_sighandler
);
672 signal(SIGINT
, control_client_sighandler
);
673 signal(SIGTERM
, control_client_sighandler
);
674 signal(SIGWINCH
, control_client_sigrelay
);
680 * Stick around until the controlee closes the client_fd.
681 * Before it does, it is expected to write this process' exit
682 * value (one int). This process must read the value and wait for
683 * the closure of the client_fd; if this one closes early, the
684 * multiplex master will terminate early too (possibly losing data).
687 for (i
= 0; !muxclient_terminate
&& i
< (int)sizeof(exitval
);) {
688 r
= read(sock
, (char *)exitval
+ i
, sizeof(exitval
) - i
);
690 debug2("Received EOF from master");
696 fatal("%s: read %s", __func__
, strerror(errno
));
703 if (i
> (int)sizeof(int))
704 fatal("%s: master returned too much data (%d > %lu)",
705 __func__
, i
, (u_long
)sizeof(int));
706 if (muxclient_terminate
) {
707 debug2("Exiting on signal %ld", (long)muxclient_terminate
);
709 } else if (i
< (int)sizeof(int)) {
710 debug2("Control master terminated unexpectedly");
713 debug2("Received exit status from master %d", exitval
[0]);
715 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
716 fprintf(stderr
, "Shared connection to %s closed.\r\n", host
);