- otto@cvs.openbsd.org 2008/06/12 00:13:13
[openssh-git.git] / mux.c
blob8b9105b0402e50988e186aed6a2f33bba975f363
1 /* $OpenBSD: mux.c,v 1.1 2008/05/09 14:18:44 djm Exp $ */
2 /*
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 */
20 #include "includes.h"
22 #include <sys/types.h>
23 #include <sys/param.h>
24 #include <sys/stat.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <unistd.h>
37 #ifdef HAVE_PATHS_H
38 #include <paths.h>
39 #endif
41 #ifdef HAVE_UTIL_H
42 # include <util.h>
43 #endif
45 #ifdef HAVE_LIBUTIL_H
46 # include <libutil.h>
47 #endif
49 #include "openbsd-compat/sys-queue.h"
50 #include "xmalloc.h"
51 #include "log.h"
52 #include "ssh.h"
53 #include "pathnames.h"
54 #include "misc.h"
55 #include "match.h"
56 #include "buffer.h"
57 #include "channels.h"
58 #include "msg.h"
59 #include "packet.h"
60 #include "monitor_fdpass.h"
61 #include "sshpty.h"
62 #include "key.h"
63 #include "readconf.h"
64 #include "clientloop.h"
66 /* from ssh.c */
67 extern int tty_flag;
68 extern Options options;
69 extern int stdin_null_flag;
70 extern char *host;
71 int subsystem_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. */
90 void
91 muxserver_listen(void)
93 struct sockaddr_un addr;
94 mode_t old_umask;
95 int addr_len;
97 if (options.control_path == NULL ||
98 options.control_master == SSHCTL_MASTER_NO)
99 return;
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) {
117 muxserver_sock = -1;
118 if (errno == EINVAL || errno == EADDRINUSE)
119 fatal("ControlSocket %s already exists",
120 options.control_path);
121 else
122 fatal("%s bind(): %s", __func__, strerror(errno));
124 umask(old_umask);
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. */
133 static void
134 client_extra_session2_setup(int id, void *arg)
136 struct mux_session_confirm_ctx *cctx = arg;
137 const char *display;
138 Channel *c;
139 int i;
141 if (cctx == NULL)
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) {
148 char *proto, *data;
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);
161 packet_send();
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);
169 xfree(cctx->term);
170 if (cctx->env != NULL) {
171 for (i = 0; cctx->env[i] != NULL; i++)
172 xfree(cctx->env[i]);
173 xfree(cctx->env);
175 xfree(cctx);
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)
186 Buffer m;
187 Channel *c;
188 int client_fd, new_fd[3], ver, allowed, window, packetmax;
189 socklen_t addrlen;
190 struct sockaddr_storage addr;
191 struct mux_session_confirm_ctx *cctx;
192 char *cmd;
193 u_int i, j, len, env_len, mux_command, flags;
194 uid_t euid;
195 gid_t egid;
196 int start_close = 0;
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));
206 return 0;
209 if (getpeereid(client_fd, &euid, &egid) < 0) {
210 error("%s getpeereid failed: %s", __func__, strerror(errno));
211 close(client_fd);
212 return 0;
214 if ((euid != 0) && (getuid() != euid)) {
215 error("control mode uid mismatch: peer euid %u != uid %u",
216 (u_int) euid, (u_int) getuid());
217 close(client_fd);
218 return 0;
221 /* XXX handle asynchronously */
222 unset_nonblock(client_fd);
224 /* Read command */
225 buffer_init(&m);
226 if (ssh_msg_recv(client_fd, &m) == -1) {
227 error("%s: client msg_recv failed", __func__);
228 close(client_fd);
229 buffer_free(&m);
230 return 0;
232 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
233 error("%s: wrong client version %d", __func__, ver);
234 buffer_free(&m);
235 close(client_fd);
236 return 0;
239 allowed = 1;
240 mux_command = buffer_get_int(&m);
241 flags = buffer_get_int(&m);
243 buffer_clear(&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 "
250 "to %s? ", host);
251 /* continue below */
252 break;
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 "
257 "to %s? ", host);
258 if (allowed)
259 start_close = 1;
260 /* FALLTHROUGH */
261 case SSHMUX_COMMAND_ALIVE_CHECK:
262 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
263 buffer_clear(&m);
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__);
268 close(client_fd);
269 buffer_free(&m);
270 return start_close;
272 buffer_free(&m);
273 close(client_fd);
274 return start_close;
275 default:
276 error("Unsupported command %d", mux_command);
277 buffer_free(&m);
278 close(client_fd);
279 return 0;
282 /* Reply for SSHMUX_COMMAND_OPEN */
283 buffer_clear(&m);
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__);
288 close(client_fd);
289 buffer_free(&m);
290 return 0;
293 if (!allowed) {
294 error("Refused control connection");
295 close(client_fd);
296 buffer_free(&m);
297 return 0;
300 buffer_clear(&m);
301 if (ssh_msg_recv(client_fd, &m) == -1) {
302 error("%s: client msg_recv failed", __func__);
303 close(client_fd);
304 buffer_free(&m);
305 return 0;
307 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
308 error("%s: wrong client version %d", __func__, ver);
309 buffer_free(&m);
310 close(client_fd);
311 return 0;
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);
328 if (env_len != 0) {
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);
332 cctx->env[i] = NULL;
335 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
336 cctx->want_tty, cctx->want_subsys, cmd);
337 xfree(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",
343 __func__, i);
344 for (j = 0; j < i; j++)
345 close(new_fd[j]);
346 for (j = 0; j < env_len; j++)
347 xfree(cctx->env[j]);
348 if (env_len > 0)
349 xfree(cctx->env);
350 xfree(cctx->term);
351 buffer_free(&cctx->cmd);
352 close(client_fd);
353 xfree(cctx);
354 return 0;
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 */
366 buffer_clear(&m);
367 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
368 error("%s: client msg_send failed", __func__);
369 close(client_fd);
370 close(new_fd[0]);
371 close(new_fd[1]);
372 close(new_fd[2]);
373 buffer_free(&m);
374 xfree(cctx->term);
375 if (env_len != 0) {
376 for (i = 0; i < env_len; i++)
377 xfree(cctx->env[i]);
378 xfree(cctx->env);
380 return 0;
382 buffer_free(&m);
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) {
397 window >>= 1;
398 packetmax >>= 1;
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);
405 /* XXX */
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);
413 return 0;
416 /* ** Multiplexing client support */
418 /* Exit signal handler */
419 static void
420 control_client_sighandler(int signo)
422 muxclient_terminate = signo;
426 * Relay signal handler - used to pass some signals from mux client to
427 * mux master.
429 static void
430 control_client_sigrelay(int signo)
432 int save_errno = errno;
434 if (muxserver_pid > 1)
435 kill(muxserver_pid, signo);
437 errno = save_errno;
440 /* Check mux client environment variables before passing them to mux master. */
441 static int
442 env_permitted(char *env)
444 int i, ret;
445 char name[1024], *cp;
447 if ((cp = strchr(env, '=')) == NULL || cp == env)
448 return (0);
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]))
455 return (1);
457 return (0);
460 /* Multiplex client main loop. */
461 void
462 muxclient(const char *path)
464 struct sockaddr_un addr;
465 int i, r, fd, sock, exitval[2], num_env, addr_len;
466 Buffer m;
467 char *term;
468 extern char **environ;
469 u_int flags;
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");
478 /* FALLTHROUGH */
479 case SSHCTL_MASTER_NO:
480 break;
481 default:
482 return;
485 memset(&addr, '\0', sizeof(addr));
486 addr.sun_family = AF_UNIX;
487 addr_len = offsetof(struct sockaddr_un, sun_path) +
488 strlen(path) + 1;
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,
500 strerror(errno));
502 if (errno == ENOENT)
503 debug("Control socket \"%.100s\" does not exist", path);
504 else {
505 error("Control socket connect(%.100s): %s", path,
506 strerror(errno));
508 close(sock);
509 return;
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)
518 close(fd);
521 term = getenv("TERM");
523 flags = 0;
524 if (tty_flag)
525 flags |= SSHMUX_FLAG_TTY;
526 if (subsystem_flag)
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);
535 buffer_init(&m);
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__);
542 buffer_clear(&m);
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);
553 buffer_clear(&m);
555 switch (muxclient_command) {
556 case SSHMUX_COMMAND_ALIVE_CHECK:
557 fprintf(stderr, "Master running (pid=%d)\r\n",
558 muxserver_pid);
559 exit(0);
560 case SSHMUX_COMMAND_TERMINATE:
561 fprintf(stderr, "Exit request sent.\r\n");
562 exit(0);
563 case SSHMUX_COMMAND_OPEN:
564 /* continue below */
565 break;
566 default:
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);
577 } else {
578 /* Pass environment */
579 num_env = 0;
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])) {
588 num_env--;
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 */
602 buffer_clear(&m);
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__);
607 buffer_free(&m);
609 signal(SIGHUP, control_client_sighandler);
610 signal(SIGINT, control_client_sighandler);
611 signal(SIGTERM, control_client_sighandler);
612 signal(SIGWINCH, control_client_sigrelay);
614 if (tty_flag)
615 enter_raw_mode();
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).
624 exitval[0] = 0;
625 for (i = 0; !muxclient_terminate && i < (int)sizeof(exitval);) {
626 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
627 if (r == 0) {
628 debug2("Received EOF from master");
629 break;
631 if (r == -1) {
632 if (errno == EINTR)
633 continue;
634 fatal("%s: read %s", __func__, strerror(errno));
636 i += r;
639 close(sock);
640 leave_raw_mode();
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);
646 exitval[0] = 255;
647 } else if (i < (int)sizeof(int)) {
648 debug2("Control master terminated unexpectedly");
649 exitval[0] = 255;
650 } else
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);
656 exit(exitval[0]);