1 /* $OpenBSD: mux.c,v 1.1 2008/05/09 14:18:44 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 */
22 #include <sys/types.h>
23 #include <sys/param.h>
25 #include <sys/socket.h>
49 #include "openbsd-compat/sys-queue.h"
53 #include "pathnames.h"
60 #include "monitor_fdpass.h"
64 #include "clientloop.h"
68 extern Options options
;
69 extern int stdin_null_flag
;
72 extern Buffer command
;
74 /* fd to control socket */
75 int muxserver_sock
= -1;
77 /* Multiplexing control command */
78 u_int muxclient_command
= 0;
80 /* Set when signalled. */
81 static volatile sig_atomic_t muxclient_terminate
= 0;
83 /* PID of multiplex server */
84 static u_int muxserver_pid
= 0;
87 /* ** Multiplexing master support */
89 /* Prepare a mux master to listen on a Unix domain socket. */
91 muxserver_listen(void)
93 struct sockaddr_un addr
;
97 if (options
.control_path
== NULL
||
98 options
.control_master
== SSHCTL_MASTER_NO
)
101 debug("setting up multiplex master socket");
103 memset(&addr
, '\0', sizeof(addr
));
104 addr
.sun_family
= AF_UNIX
;
105 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
106 strlen(options
.control_path
) + 1;
108 if (strlcpy(addr
.sun_path
, options
.control_path
,
109 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
110 fatal("ControlPath too long");
112 if ((muxserver_sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
113 fatal("%s socket(): %s", __func__
, strerror(errno
));
115 old_umask
= umask(0177);
116 if (bind(muxserver_sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
118 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
119 fatal("ControlSocket %s already exists",
120 options
.control_path
);
122 fatal("%s bind(): %s", __func__
, strerror(errno
));
126 if (listen(muxserver_sock
, 64) == -1)
127 fatal("%s listen(): %s", __func__
, strerror(errno
));
129 set_nonblock(muxserver_sock
);
132 /* Callback on open confirmation in mux master for a mux client session. */
134 client_extra_session2_setup(int id
, void *arg
)
136 struct mux_session_confirm_ctx
*cctx
= arg
;
142 fatal("%s: cctx == NULL", __func__
);
143 if ((c
= channel_lookup(id
)) == NULL
)
144 fatal("%s: no channel for id %d", __func__
, id
);
146 display
= getenv("DISPLAY");
147 if (cctx
->want_x_fwd
&& options
.forward_x11
&& display
!= NULL
) {
149 /* Get reasonable local authentication information. */
150 client_x11_get_proto(display
, options
.xauth_location
,
151 options
.forward_x11_trusted
, &proto
, &data
);
152 /* Request forwarding with authentication spoofing. */
153 debug("Requesting X11 forwarding with authentication spoofing.");
154 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
155 /* XXX wait for reply */
158 if (cctx
->want_agent_fwd
&& options
.forward_agent
) {
159 debug("Requesting authentication agent forwarding.");
160 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
164 client_session2_setup(id
, cctx
->want_tty
, cctx
->want_subsys
,
165 cctx
->term
, &cctx
->tio
, c
->rfd
, &cctx
->cmd
, cctx
->env
);
167 c
->open_confirm_ctx
= NULL
;
168 buffer_free(&cctx
->cmd
);
170 if (cctx
->env
!= NULL
) {
171 for (i
= 0; cctx
->env
[i
] != NULL
; i
++)
179 * Accept a connection on the mux master socket and process the
180 * client's request. Returns flag indicating whether mux master should
181 * begin graceful close.
184 muxserver_accept_control(void)
188 int client_fd
, new_fd
[3], ver
, allowed
, window
, packetmax
;
190 struct sockaddr_storage addr
;
191 struct mux_session_confirm_ctx
*cctx
;
193 u_int i
, j
, len
, env_len
, mux_command
, flags
;
199 * Accept connection on control socket
201 memset(&addr
, 0, sizeof(addr
));
202 addrlen
= sizeof(addr
);
203 if ((client_fd
= accept(muxserver_sock
,
204 (struct sockaddr
*)&addr
, &addrlen
)) == -1) {
205 error("%s accept: %s", __func__
, strerror(errno
));
209 if (getpeereid(client_fd
, &euid
, &egid
) < 0) {
210 error("%s getpeereid failed: %s", __func__
, strerror(errno
));
214 if ((euid
!= 0) && (getuid() != euid
)) {
215 error("control mode uid mismatch: peer euid %u != uid %u",
216 (u_int
) euid
, (u_int
) getuid());
221 /* XXX handle asynchronously */
222 unset_nonblock(client_fd
);
226 if (ssh_msg_recv(client_fd
, &m
) == -1) {
227 error("%s: client msg_recv failed", __func__
);
232 if ((ver
= buffer_get_char(&m
)) != SSHMUX_VER
) {
233 error("%s: wrong client version %d", __func__
, ver
);
240 mux_command
= buffer_get_int(&m
);
241 flags
= buffer_get_int(&m
);
245 switch (mux_command
) {
246 case SSHMUX_COMMAND_OPEN
:
247 if (options
.control_master
== SSHCTL_MASTER_ASK
||
248 options
.control_master
== SSHCTL_MASTER_AUTO_ASK
)
249 allowed
= ask_permission("Allow shared connection "
253 case SSHMUX_COMMAND_TERMINATE
:
254 if (options
.control_master
== SSHCTL_MASTER_ASK
||
255 options
.control_master
== SSHCTL_MASTER_AUTO_ASK
)
256 allowed
= ask_permission("Terminate shared connection "
261 case SSHMUX_COMMAND_ALIVE_CHECK
:
262 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
264 buffer_put_int(&m
, allowed
);
265 buffer_put_int(&m
, getpid());
266 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
267 error("%s: client msg_send failed", __func__
);
276 error("Unsupported command %d", mux_command
);
282 /* Reply for SSHMUX_COMMAND_OPEN */
284 buffer_put_int(&m
, allowed
);
285 buffer_put_int(&m
, getpid());
286 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
287 error("%s: client msg_send failed", __func__
);
294 error("Refused control connection");
301 if (ssh_msg_recv(client_fd
, &m
) == -1) {
302 error("%s: client msg_recv failed", __func__
);
307 if ((ver
= buffer_get_char(&m
)) != SSHMUX_VER
) {
308 error("%s: wrong client version %d", __func__
, ver
);
314 cctx
= xcalloc(1, sizeof(*cctx
));
315 cctx
->want_tty
= (flags
& SSHMUX_FLAG_TTY
) != 0;
316 cctx
->want_subsys
= (flags
& SSHMUX_FLAG_SUBSYS
) != 0;
317 cctx
->want_x_fwd
= (flags
& SSHMUX_FLAG_X11_FWD
) != 0;
318 cctx
->want_agent_fwd
= (flags
& SSHMUX_FLAG_AGENT_FWD
) != 0;
319 cctx
->term
= buffer_get_string(&m
, &len
);
321 cmd
= buffer_get_string(&m
, &len
);
322 buffer_init(&cctx
->cmd
);
323 buffer_append(&cctx
->cmd
, cmd
, strlen(cmd
));
325 env_len
= buffer_get_int(&m
);
326 env_len
= MIN(env_len
, 4096);
327 debug3("%s: receiving %d env vars", __func__
, env_len
);
329 cctx
->env
= xcalloc(env_len
+ 1, sizeof(*cctx
->env
));
330 for (i
= 0; i
< env_len
; i
++)
331 cctx
->env
[i
] = buffer_get_string(&m
, &len
);
335 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__
,
336 cctx
->want_tty
, cctx
->want_subsys
, cmd
);
339 /* Gather fds from client */
340 for(i
= 0; i
< 3; i
++) {
341 if ((new_fd
[i
] = mm_receive_fd(client_fd
)) == -1) {
342 error("%s: failed to receive fd %d from slave",
344 for (j
= 0; j
< i
; j
++)
346 for (j
= 0; j
< env_len
; j
++)
351 buffer_free(&cctx
->cmd
);
358 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__
,
359 new_fd
[0], new_fd
[1], new_fd
[2]);
361 /* Try to pick up ttymodes from client before it goes raw */
362 if (cctx
->want_tty
&& tcgetattr(new_fd
[0], &cctx
->tio
) == -1)
363 error("%s: tcgetattr: %s", __func__
, strerror(errno
));
365 /* This roundtrip is just for synchronisation of ttymodes */
367 if (ssh_msg_send(client_fd
, SSHMUX_VER
, &m
) == -1) {
368 error("%s: client msg_send failed", __func__
);
376 for (i
= 0; i
< env_len
; i
++)
384 /* enable nonblocking unless tty */
385 if (!isatty(new_fd
[0]))
386 set_nonblock(new_fd
[0]);
387 if (!isatty(new_fd
[1]))
388 set_nonblock(new_fd
[1]);
389 if (!isatty(new_fd
[2]))
390 set_nonblock(new_fd
[2]);
392 set_nonblock(client_fd
);
394 window
= CHAN_SES_WINDOW_DEFAULT
;
395 packetmax
= CHAN_SES_PACKET_DEFAULT
;
396 if (cctx
->want_tty
) {
401 c
= channel_new("session", SSH_CHANNEL_OPENING
,
402 new_fd
[0], new_fd
[1], new_fd
[2], window
, packetmax
,
403 CHAN_EXTENDED_WRITE
, "client-session", /*nonblock*/0);
406 c
->ctl_fd
= client_fd
;
408 debug3("%s: channel_new: %d", __func__
, c
->self
);
410 channel_send_open(c
->self
);
411 channel_register_open_confirm(c
->self
,
412 client_extra_session2_setup
, cctx
);
416 /* ** Multiplexing client support */
418 /* Exit signal handler */
420 control_client_sighandler(int signo
)
422 muxclient_terminate
= signo
;
426 * Relay signal handler - used to pass some signals from mux client to
430 control_client_sigrelay(int signo
)
432 int save_errno
= errno
;
434 if (muxserver_pid
> 1)
435 kill(muxserver_pid
, signo
);
440 /* Check mux client environment variables before passing them to mux master. */
442 env_permitted(char *env
)
445 char name
[1024], *cp
;
447 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
449 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
450 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
451 fatal("env_permitted: name '%.100s...' too long", env
);
453 for (i
= 0; i
< options
.num_send_env
; i
++)
454 if (match_pattern(name
, options
.send_env
[i
]))
460 /* Multiplex client main loop. */
462 muxclient(const char *path
)
464 struct sockaddr_un addr
;
465 int i
, r
, fd
, sock
, exitval
[2], num_env
, addr_len
;
468 extern char **environ
;
471 if (muxclient_command
== 0)
472 muxclient_command
= SSHMUX_COMMAND_OPEN
;
474 switch (options
.control_master
) {
475 case SSHCTL_MASTER_AUTO
:
476 case SSHCTL_MASTER_AUTO_ASK
:
477 debug("auto-mux: Trying existing master");
479 case SSHCTL_MASTER_NO
:
485 memset(&addr
, '\0', sizeof(addr
));
486 addr
.sun_family
= AF_UNIX
;
487 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
490 if (strlcpy(addr
.sun_path
, path
,
491 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
492 fatal("ControlPath too long");
494 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
495 fatal("%s socket(): %s", __func__
, strerror(errno
));
497 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
498 if (muxclient_command
!= SSHMUX_COMMAND_OPEN
) {
499 fatal("Control socket connect(%.100s): %s", path
,
503 debug("Control socket \"%.100s\" does not exist", path
);
505 error("Control socket connect(%.100s): %s", path
,
512 if (stdin_null_flag
) {
513 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
514 fatal("open(/dev/null): %s", strerror(errno
));
515 if (dup2(fd
, STDIN_FILENO
) == -1)
516 fatal("dup2: %s", strerror(errno
));
517 if (fd
> STDERR_FILENO
)
521 term
= getenv("TERM");
525 flags
|= SSHMUX_FLAG_TTY
;
527 flags
|= SSHMUX_FLAG_SUBSYS
;
528 if (options
.forward_x11
)
529 flags
|= SSHMUX_FLAG_X11_FWD
;
530 if (options
.forward_agent
)
531 flags
|= SSHMUX_FLAG_AGENT_FWD
;
533 signal(SIGPIPE
, SIG_IGN
);
537 /* Send our command to server */
538 buffer_put_int(&m
, muxclient_command
);
539 buffer_put_int(&m
, flags
);
540 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
541 fatal("%s: msg_send", __func__
);
544 /* Get authorisation status and PID of controlee */
545 if (ssh_msg_recv(sock
, &m
) == -1)
546 fatal("%s: msg_recv", __func__
);
547 if (buffer_get_char(&m
) != SSHMUX_VER
)
548 fatal("%s: wrong version", __func__
);
549 if (buffer_get_int(&m
) != 1)
550 fatal("Connection to master denied");
551 muxserver_pid
= buffer_get_int(&m
);
555 switch (muxclient_command
) {
556 case SSHMUX_COMMAND_ALIVE_CHECK
:
557 fprintf(stderr
, "Master running (pid=%d)\r\n",
560 case SSHMUX_COMMAND_TERMINATE
:
561 fprintf(stderr
, "Exit request sent.\r\n");
563 case SSHMUX_COMMAND_OPEN
:
567 fatal("silly muxclient_command %d", muxclient_command
);
570 /* SSHMUX_COMMAND_OPEN */
571 buffer_put_cstring(&m
, term
? term
: "");
572 buffer_append(&command
, "\0", 1);
573 buffer_put_cstring(&m
, buffer_ptr(&command
));
575 if (options
.num_send_env
== 0 || environ
== NULL
) {
576 buffer_put_int(&m
, 0);
578 /* Pass environment */
580 for (i
= 0; environ
[i
] != NULL
; i
++)
581 if (env_permitted(environ
[i
]))
582 num_env
++; /* Count */
584 buffer_put_int(&m
, num_env
);
586 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
587 if (env_permitted(environ
[i
])) {
589 buffer_put_cstring(&m
, environ
[i
]);
593 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
594 fatal("%s: msg_send", __func__
);
596 if (mm_send_fd(sock
, STDIN_FILENO
) == -1 ||
597 mm_send_fd(sock
, STDOUT_FILENO
) == -1 ||
598 mm_send_fd(sock
, STDERR_FILENO
) == -1)
599 fatal("%s: send fds failed", __func__
);
601 /* Wait for reply, so master has a chance to gather ttymodes */
603 if (ssh_msg_recv(sock
, &m
) == -1)
604 fatal("%s: msg_recv", __func__
);
605 if (buffer_get_char(&m
) != SSHMUX_VER
)
606 fatal("%s: wrong version", __func__
);
609 signal(SIGHUP
, control_client_sighandler
);
610 signal(SIGINT
, control_client_sighandler
);
611 signal(SIGTERM
, control_client_sighandler
);
612 signal(SIGWINCH
, control_client_sigrelay
);
618 * Stick around until the controlee closes the client_fd.
619 * Before it does, it is expected to write this process' exit
620 * value (one int). This process must read the value and wait for
621 * the closure of the client_fd; if this one closes early, the
622 * multiplex master will terminate early too (possibly losing data).
625 for (i
= 0; !muxclient_terminate
&& i
< (int)sizeof(exitval
);) {
626 r
= read(sock
, (char *)exitval
+ i
, sizeof(exitval
) - i
);
628 debug2("Received EOF from master");
634 fatal("%s: read %s", __func__
, strerror(errno
));
641 if (i
> (int)sizeof(int))
642 fatal("%s: master returned too much data (%d > %lu)",
643 __func__
, i
, sizeof(int));
644 if (muxclient_terminate
) {
645 debug2("Exiting on signal %d", muxclient_terminate
);
647 } else if (i
< (int)sizeof(int)) {
648 debug2("Control master terminated unexpectedly");
651 debug2("Received exit status from master %d", exitval
[0]);
653 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
654 fprintf(stderr
, "Shared connection to %s closed.\r\n", host
);