• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* $OpenBSD: mux.c,v 1.29 2011/06/22 22:08:42 djm Exp $ */
2 /*
3  * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
4  *
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.
8  *
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.
16  */
17 
18 /* ssh session multiplexing support */
19 
20 /*
21  * TODO:
22  *   - Better signalling from master to slave, especially passing of
23  *      error messages
24  *   - Better fall-back from mux slave error to new connection.
25  *   - ExitOnForwardingFailure
26  *   - Maybe extension mechanisms for multi-X11/multi-agent forwarding
27  *   - Support ~^Z in mux slaves.
28  *   - Inspect or control sessions in master.
29  *   - If we ever support the "signal" channel request, send signals on
30  *     sessions in master.
31  */
32 
33 #include "includes.h"
34 
35 #include <sys/types.h>
36 #include <sys/param.h>
37 #include <sys/stat.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <stdarg.h>
45 #include <stddef.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <unistd.h>
50 #ifdef HAVE_PATHS_H
51 #include <paths.h>
52 #endif
53 
54 #ifdef HAVE_POLL_H
55 #include <poll.h>
56 #else
57 # ifdef HAVE_SYS_POLL_H
58 #  include <sys/poll.h>
59 # endif
60 #endif
61 
62 #ifdef HAVE_UTIL_H
63 # include <util.h>
64 #endif
65 
66 #ifdef HAVE_LIBUTIL_H
67 # include <libutil.h>
68 #endif
69 
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "log.h"
73 #include "ssh.h"
74 #include "ssh2.h"
75 #include "pathnames.h"
76 #include "misc.h"
77 #include "match.h"
78 #include "buffer.h"
79 #include "channels.h"
80 #include "msg.h"
81 #include "packet.h"
82 #include "monitor_fdpass.h"
83 #include "sshpty.h"
84 #include "key.h"
85 #include "readconf.h"
86 #include "clientloop.h"
87 
88 /* from ssh.c */
89 extern int tty_flag;
90 extern Options options;
91 extern int stdin_null_flag;
92 extern char *host;
93 extern int subsystem_flag;
94 extern Buffer command;
95 extern volatile sig_atomic_t quit_pending;
96 extern char *stdio_forward_host;
97 extern int stdio_forward_port;
98 
99 /* Context for session open confirmation callback */
100 struct mux_session_confirm_ctx {
101 	u_int want_tty;
102 	u_int want_subsys;
103 	u_int want_x_fwd;
104 	u_int want_agent_fwd;
105 	Buffer cmd;
106 	char *term;
107 	struct termios tio;
108 	char **env;
109 	u_int rid;
110 };
111 
112 /* Context for global channel callback */
113 struct mux_channel_confirm_ctx {
114 	u_int cid;	/* channel id */
115 	u_int rid;	/* request id */
116 	int fid;	/* forward id */
117 };
118 
119 /* fd to control socket */
120 int muxserver_sock = -1;
121 
122 /* client request id */
123 u_int muxclient_request_id = 0;
124 
125 /* Multiplexing control command */
126 u_int muxclient_command = 0;
127 
128 /* Set when signalled. */
129 static volatile sig_atomic_t muxclient_terminate = 0;
130 
131 /* PID of multiplex server */
132 static u_int muxserver_pid = 0;
133 
134 static Channel *mux_listener_channel = NULL;
135 
136 struct mux_master_state {
137 	int hello_rcvd;
138 };
139 
140 /* mux protocol messages */
141 #define MUX_MSG_HELLO		0x00000001
142 #define MUX_C_NEW_SESSION	0x10000002
143 #define MUX_C_ALIVE_CHECK	0x10000004
144 #define MUX_C_TERMINATE		0x10000005
145 #define MUX_C_OPEN_FWD		0x10000006
146 #define MUX_C_CLOSE_FWD		0x10000007
147 #define MUX_C_NEW_STDIO_FWD	0x10000008
148 #define MUX_C_STOP_LISTENING	0x10000009
149 #define MUX_S_OK		0x80000001
150 #define MUX_S_PERMISSION_DENIED	0x80000002
151 #define MUX_S_FAILURE		0x80000003
152 #define MUX_S_EXIT_MESSAGE	0x80000004
153 #define MUX_S_ALIVE		0x80000005
154 #define MUX_S_SESSION_OPENED	0x80000006
155 #define MUX_S_REMOTE_PORT	0x80000007
156 #define MUX_S_TTY_ALLOC_FAIL	0x80000008
157 
158 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
159 #define MUX_FWD_LOCAL   1
160 #define MUX_FWD_REMOTE  2
161 #define MUX_FWD_DYNAMIC 3
162 
163 static void mux_session_confirm(int, int, void *);
164 
165 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
173 
174 static const struct {
175 	u_int type;
176 	int (*handler)(u_int, Channel *, Buffer *, Buffer *);
177 } mux_master_handlers[] = {
178 	{ MUX_MSG_HELLO, process_mux_master_hello },
179 	{ MUX_C_NEW_SESSION, process_mux_new_session },
180 	{ MUX_C_ALIVE_CHECK, process_mux_alive_check },
181 	{ MUX_C_TERMINATE, process_mux_terminate },
182 	{ MUX_C_OPEN_FWD, process_mux_open_fwd },
183 	{ MUX_C_CLOSE_FWD, process_mux_close_fwd },
184 	{ MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
185 	{ MUX_C_STOP_LISTENING, process_mux_stop_listening },
186 	{ 0, NULL }
187 };
188 
189 /* Cleanup callback fired on closure of mux slave _session_ channel */
190 /* ARGSUSED */
191 static void
mux_master_session_cleanup_cb(int cid,void * unused)192 mux_master_session_cleanup_cb(int cid, void *unused)
193 {
194 	Channel *cc, *c = channel_by_id(cid);
195 
196 	debug3("%s: entering for channel %d", __func__, cid);
197 	if (c == NULL)
198 		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
199 	if (c->ctl_chan != -1) {
200 		if ((cc = channel_by_id(c->ctl_chan)) == NULL)
201 			fatal("%s: channel %d missing control channel %d",
202 			    __func__, c->self, c->ctl_chan);
203 		c->ctl_chan = -1;
204 		cc->remote_id = -1;
205 		chan_rcvd_oclose(cc);
206 	}
207 	channel_cancel_cleanup(c->self);
208 }
209 
210 /* Cleanup callback fired on closure of mux slave _control_ channel */
211 /* ARGSUSED */
212 static void
mux_master_control_cleanup_cb(int cid,void * unused)213 mux_master_control_cleanup_cb(int cid, void *unused)
214 {
215 	Channel *sc, *c = channel_by_id(cid);
216 
217 	debug3("%s: entering for channel %d", __func__, cid);
218 	if (c == NULL)
219 		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
220 	if (c->remote_id != -1) {
221 		if ((sc = channel_by_id(c->remote_id)) == NULL)
222 			fatal("%s: channel %d missing session channel %d",
223 			    __func__, c->self, c->remote_id);
224 		c->remote_id = -1;
225 		sc->ctl_chan = -1;
226 		if (sc->type != SSH_CHANNEL_OPEN) {
227 			debug2("%s: channel %d: not open", __func__, sc->self);
228 			chan_mark_dead(sc);
229 		} else {
230 			if (sc->istate == CHAN_INPUT_OPEN)
231 				chan_read_failed(sc);
232 			if (sc->ostate == CHAN_OUTPUT_OPEN)
233 				chan_write_failed(sc);
234 		}
235 	}
236 	channel_cancel_cleanup(c->self);
237 }
238 
239 /* Check mux client environment variables before passing them to mux master. */
240 static int
env_permitted(char * env)241 env_permitted(char *env)
242 {
243 	int i, ret;
244 	char name[1024], *cp;
245 
246 	if ((cp = strchr(env, '=')) == NULL || cp == env)
247 		return 0;
248 	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
249 	if (ret <= 0 || (size_t)ret >= sizeof(name)) {
250 		error("env_permitted: name '%.100s...' too long", env);
251 		return 0;
252 	}
253 
254 	for (i = 0; i < options.num_send_env; i++)
255 		if (match_pattern(name, options.send_env[i]))
256 			return 1;
257 
258 	return 0;
259 }
260 
261 /* Mux master protocol message handlers */
262 
263 static int
process_mux_master_hello(u_int rid,Channel * c,Buffer * m,Buffer * r)264 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
265 {
266 	u_int ver;
267 	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
268 
269 	if (state == NULL)
270 		fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
271 	if (state->hello_rcvd) {
272 		error("%s: HELLO received twice", __func__);
273 		return -1;
274 	}
275 	if (buffer_get_int_ret(&ver, m) != 0) {
276  malf:
277 		error("%s: malformed message", __func__);
278 		return -1;
279 	}
280 	if (ver != SSHMUX_VER) {
281 		error("Unsupported multiplexing protocol version %d "
282 		    "(expected %d)", ver, SSHMUX_VER);
283 		return -1;
284 	}
285 	debug2("%s: channel %d slave version %u", __func__, c->self, ver);
286 
287 	/* No extensions are presently defined */
288 	while (buffer_len(m) > 0) {
289 		char *name = buffer_get_string_ret(m, NULL);
290 		char *value = buffer_get_string_ret(m, NULL);
291 
292 		if (name == NULL || value == NULL) {
293 			if (name != NULL)
294 				xfree(name);
295 			goto malf;
296 		}
297 		debug2("Unrecognised slave extension \"%s\"", name);
298 		xfree(name);
299 		xfree(value);
300 	}
301 	state->hello_rcvd = 1;
302 	return 0;
303 }
304 
305 static int
process_mux_new_session(u_int rid,Channel * c,Buffer * m,Buffer * r)306 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
307 {
308 	Channel *nc;
309 	struct mux_session_confirm_ctx *cctx;
310 	char *reserved, *cmd, *cp;
311 	u_int i, j, len, env_len, escape_char, window, packetmax;
312 	int new_fd[3];
313 
314 	/* Reply for SSHMUX_COMMAND_OPEN */
315 	cctx = xcalloc(1, sizeof(*cctx));
316 	cctx->term = NULL;
317 	cctx->rid = rid;
318 	cmd = reserved = NULL;
319 	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
320 	    buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
321 	    buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
322 	    buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
323 	    buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
324 	    buffer_get_int_ret(&escape_char, m) != 0 ||
325 	    (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
326 	    (cmd = buffer_get_string_ret(m, &len)) == NULL) {
327  malf:
328 		if (cmd != NULL)
329 			xfree(cmd);
330 		if (reserved != NULL)
331 			xfree(reserved);
332 		if (cctx->term != NULL)
333 			xfree(cctx->term);
334 		error("%s: malformed message", __func__);
335 		return -1;
336 	}
337 	xfree(reserved);
338 	reserved = NULL;
339 
340 	cctx->env = NULL;
341 	env_len = 0;
342 	while (buffer_len(m) > 0) {
343 #define MUX_MAX_ENV_VARS	4096
344 		if ((cp = buffer_get_string_ret(m, &len)) == NULL) {
345 			xfree(cmd);
346 			goto malf;
347 		}
348 		if (!env_permitted(cp)) {
349 			xfree(cp);
350 			continue;
351 		}
352 		cctx->env = xrealloc(cctx->env, env_len + 2,
353 		    sizeof(*cctx->env));
354 		cctx->env[env_len++] = cp;
355 		cctx->env[env_len] = NULL;
356 		if (env_len > MUX_MAX_ENV_VARS) {
357 			error(">%d environment variables received, ignoring "
358 			    "additional", MUX_MAX_ENV_VARS);
359 			break;
360 		}
361 	}
362 
363 	debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
364 	    "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
365 	    cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
366 	    cctx->want_subsys, cctx->term, cmd, env_len);
367 
368 	buffer_init(&cctx->cmd);
369 	buffer_append(&cctx->cmd, cmd, strlen(cmd));
370 	xfree(cmd);
371 	cmd = NULL;
372 
373 	/* Gather fds from client */
374 	for(i = 0; i < 3; i++) {
375 		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
376 			error("%s: failed to receive fd %d from slave",
377 			    __func__, i);
378 			for (j = 0; j < i; j++)
379 				close(new_fd[j]);
380 			for (j = 0; j < env_len; j++)
381 				xfree(cctx->env[j]);
382 			if (env_len > 0)
383 				xfree(cctx->env);
384 			xfree(cctx->term);
385 			buffer_free(&cctx->cmd);
386 			xfree(cctx);
387 
388 			/* prepare reply */
389 			buffer_put_int(r, MUX_S_FAILURE);
390 			buffer_put_int(r, rid);
391 			buffer_put_cstring(r,
392 			    "did not receive file descriptors");
393 			return -1;
394 		}
395 	}
396 
397 	debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
398 	    new_fd[0], new_fd[1], new_fd[2]);
399 
400 	/* XXX support multiple child sessions in future */
401 	if (c->remote_id != -1) {
402 		debug2("%s: session already open", __func__);
403 		/* prepare reply */
404 		buffer_put_int(r, MUX_S_FAILURE);
405 		buffer_put_int(r, rid);
406 		buffer_put_cstring(r, "Multiple sessions not supported");
407  cleanup:
408 		close(new_fd[0]);
409 		close(new_fd[1]);
410 		close(new_fd[2]);
411 		xfree(cctx->term);
412 		if (env_len != 0) {
413 			for (i = 0; i < env_len; i++)
414 				xfree(cctx->env[i]);
415 			xfree(cctx->env);
416 		}
417 		buffer_free(&cctx->cmd);
418 		return 0;
419 	}
420 
421 	if (options.control_master == SSHCTL_MASTER_ASK ||
422 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
423 		if (!ask_permission("Allow shared connection to %s? ", host)) {
424 			debug2("%s: session refused by user", __func__);
425 			/* prepare reply */
426 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
427 			buffer_put_int(r, rid);
428 			buffer_put_cstring(r, "Permission denied");
429 			goto cleanup;
430 		}
431 	}
432 
433 	/* Try to pick up ttymodes from client before it goes raw */
434 	if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
435 		error("%s: tcgetattr: %s", __func__, strerror(errno));
436 
437 	/* enable nonblocking unless tty */
438 	if (!isatty(new_fd[0]))
439 		set_nonblock(new_fd[0]);
440 	if (!isatty(new_fd[1]))
441 		set_nonblock(new_fd[1]);
442 	if (!isatty(new_fd[2]))
443 		set_nonblock(new_fd[2]);
444 
445 	window = CHAN_SES_WINDOW_DEFAULT;
446 	packetmax = CHAN_SES_PACKET_DEFAULT;
447 	if (cctx->want_tty) {
448 		window >>= 1;
449 		packetmax >>= 1;
450 	}
451 
452 	nc = channel_new("session", SSH_CHANNEL_OPENING,
453 	    new_fd[0], new_fd[1], new_fd[2], window, packetmax,
454 	    CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
455 
456 	nc->ctl_chan = c->self;		/* link session -> control channel */
457 	c->remote_id = nc->self; 	/* link control -> session channel */
458 
459 	if (cctx->want_tty && escape_char != 0xffffffff) {
460 		channel_register_filter(nc->self,
461 		    client_simple_escape_filter, NULL,
462 		    client_filter_cleanup,
463 		    client_new_escape_filter_ctx((int)escape_char));
464 	}
465 
466 	debug2("%s: channel_new: %d linked to control channel %d",
467 	    __func__, nc->self, nc->ctl_chan);
468 
469 	channel_send_open(nc->self);
470 	channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
471 	c->mux_pause = 1; /* stop handling messages until open_confirm done */
472 	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
473 
474 	/* reply is deferred, sent by mux_session_confirm */
475 	return 0;
476 }
477 
478 static int
process_mux_alive_check(u_int rid,Channel * c,Buffer * m,Buffer * r)479 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
480 {
481 	debug2("%s: channel %d: alive check", __func__, c->self);
482 
483 	/* prepare reply */
484 	buffer_put_int(r, MUX_S_ALIVE);
485 	buffer_put_int(r, rid);
486 	buffer_put_int(r, (u_int)getpid());
487 
488 	return 0;
489 }
490 
491 static int
process_mux_terminate(u_int rid,Channel * c,Buffer * m,Buffer * r)492 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
493 {
494 	debug2("%s: channel %d: terminate request", __func__, c->self);
495 
496 	if (options.control_master == SSHCTL_MASTER_ASK ||
497 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
498 		if (!ask_permission("Terminate shared connection to %s? ",
499 		    host)) {
500 			debug2("%s: termination refused by user", __func__);
501 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
502 			buffer_put_int(r, rid);
503 			buffer_put_cstring(r, "Permission denied");
504 			return 0;
505 		}
506 	}
507 
508 	quit_pending = 1;
509 	buffer_put_int(r, MUX_S_OK);
510 	buffer_put_int(r, rid);
511 	/* XXX exit happens too soon - message never makes it to client */
512 	return 0;
513 }
514 
515 static char *
format_forward(u_int ftype,Forward * fwd)516 format_forward(u_int ftype, Forward *fwd)
517 {
518 	char *ret;
519 
520 	switch (ftype) {
521 	case MUX_FWD_LOCAL:
522 		xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
523 		    (fwd->listen_host == NULL) ?
524 		    (options.gateway_ports ? "*" : "LOCALHOST") :
525 		    fwd->listen_host, fwd->listen_port,
526 		    fwd->connect_host, fwd->connect_port);
527 		break;
528 	case MUX_FWD_DYNAMIC:
529 		xasprintf(&ret, "dynamic forward %.200s:%d -> *",
530 		    (fwd->listen_host == NULL) ?
531 		    (options.gateway_ports ? "*" : "LOCALHOST") :
532 		     fwd->listen_host, fwd->listen_port);
533 		break;
534 	case MUX_FWD_REMOTE:
535 		xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
536 		    (fwd->listen_host == NULL) ?
537 		    "LOCALHOST" : fwd->listen_host,
538 		    fwd->listen_port,
539 		    fwd->connect_host, fwd->connect_port);
540 		break;
541 	default:
542 		fatal("%s: unknown forward type %u", __func__, ftype);
543 	}
544 	return ret;
545 }
546 
547 static int
compare_host(const char * a,const char * b)548 compare_host(const char *a, const char *b)
549 {
550 	if (a == NULL && b == NULL)
551 		return 1;
552 	if (a == NULL || b == NULL)
553 		return 0;
554 	return strcmp(a, b) == 0;
555 }
556 
557 static int
compare_forward(Forward * a,Forward * b)558 compare_forward(Forward *a, Forward *b)
559 {
560 	if (!compare_host(a->listen_host, b->listen_host))
561 		return 0;
562 	if (a->listen_port != b->listen_port)
563 		return 0;
564 	if (!compare_host(a->connect_host, b->connect_host))
565 		return 0;
566 	if (a->connect_port != b->connect_port)
567 		return 0;
568 
569 	return 1;
570 }
571 
572 static void
mux_confirm_remote_forward(int type,u_int32_t seq,void * ctxt)573 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
574 {
575 	struct mux_channel_confirm_ctx *fctx = ctxt;
576 	char *failmsg = NULL;
577 	Forward *rfwd;
578 	Channel *c;
579 	Buffer out;
580 
581 	if ((c = channel_by_id(fctx->cid)) == NULL) {
582 		/* no channel for reply */
583 		error("%s: unknown channel", __func__);
584 		return;
585 	}
586 	buffer_init(&out);
587 	if (fctx->fid >= options.num_remote_forwards) {
588 		xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
589 		goto fail;
590 	}
591 	rfwd = &options.remote_forwards[fctx->fid];
592 	debug("%s: %s for: listen %d, connect %s:%d", __func__,
593 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
594 	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
595 	if (type == SSH2_MSG_REQUEST_SUCCESS) {
596 		if (rfwd->listen_port == 0) {
597 			rfwd->allocated_port = packet_get_int();
598 			logit("Allocated port %u for mux remote forward"
599 			    " to %s:%d", rfwd->allocated_port,
600 			    rfwd->connect_host, rfwd->connect_port);
601 			buffer_put_int(&out, MUX_S_REMOTE_PORT);
602 			buffer_put_int(&out, fctx->rid);
603 			buffer_put_int(&out, rfwd->allocated_port);
604 		} else {
605 			buffer_put_int(&out, MUX_S_OK);
606 			buffer_put_int(&out, fctx->rid);
607 		}
608 		goto out;
609 	} else {
610 		xasprintf(&failmsg, "remote port forwarding failed for "
611 		    "listen port %d", rfwd->listen_port);
612 	}
613  fail:
614 	error("%s: %s", __func__, failmsg);
615 	buffer_put_int(&out, MUX_S_FAILURE);
616 	buffer_put_int(&out, fctx->rid);
617 	buffer_put_cstring(&out, failmsg);
618 	xfree(failmsg);
619  out:
620 	buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
621 	buffer_free(&out);
622 	if (c->mux_pause <= 0)
623 		fatal("%s: mux_pause %d", __func__, c->mux_pause);
624 	c->mux_pause = 0; /* start processing messages again */
625 }
626 
627 static int
process_mux_open_fwd(u_int rid,Channel * c,Buffer * m,Buffer * r)628 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
629 {
630 	Forward fwd;
631 	char *fwd_desc = NULL;
632 	u_int ftype;
633 	int i, ret = 0, freefwd = 1;
634 
635 	fwd.listen_host = fwd.connect_host = NULL;
636 	if (buffer_get_int_ret(&ftype, m) != 0 ||
637 	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
638 	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
639 	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
640 	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
641 		error("%s: malformed message", __func__);
642 		ret = -1;
643 		goto out;
644 	}
645 
646 	if (*fwd.listen_host == '\0') {
647 		xfree(fwd.listen_host);
648 		fwd.listen_host = NULL;
649 	}
650 	if (*fwd.connect_host == '\0') {
651 		xfree(fwd.connect_host);
652 		fwd.connect_host = NULL;
653 	}
654 
655 	debug2("%s: channel %d: request %s", __func__, c->self,
656 	    (fwd_desc = format_forward(ftype, &fwd)));
657 
658 	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
659 	    ftype != MUX_FWD_DYNAMIC) {
660 		logit("%s: invalid forwarding type %u", __func__, ftype);
661  invalid:
662 		if (fwd.listen_host)
663 			xfree(fwd.listen_host);
664 		if (fwd.connect_host)
665 			xfree(fwd.connect_host);
666 		buffer_put_int(r, MUX_S_FAILURE);
667 		buffer_put_int(r, rid);
668 		buffer_put_cstring(r, "Invalid forwarding request");
669 		return 0;
670 	}
671 	if (fwd.listen_port >= 65536) {
672 		logit("%s: invalid listen port %u", __func__,
673 		    fwd.listen_port);
674 		goto invalid;
675 	}
676 	if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
677 	    ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
678 		logit("%s: invalid connect port %u", __func__,
679 		    fwd.connect_port);
680 		goto invalid;
681 	}
682 	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
683 		logit("%s: missing connect host", __func__);
684 		goto invalid;
685 	}
686 
687 	/* Skip forwards that have already been requested */
688 	switch (ftype) {
689 	case MUX_FWD_LOCAL:
690 	case MUX_FWD_DYNAMIC:
691 		for (i = 0; i < options.num_local_forwards; i++) {
692 			if (compare_forward(&fwd,
693 			    options.local_forwards + i)) {
694  exists:
695 				debug2("%s: found existing forwarding",
696 				    __func__);
697 				buffer_put_int(r, MUX_S_OK);
698 				buffer_put_int(r, rid);
699 				goto out;
700 			}
701 		}
702 		break;
703 	case MUX_FWD_REMOTE:
704 		for (i = 0; i < options.num_remote_forwards; i++) {
705 			if (compare_forward(&fwd,
706 			    options.remote_forwards + i)) {
707 				if (fwd.listen_port != 0)
708 					goto exists;
709 				debug2("%s: found allocated port",
710 				    __func__);
711 				buffer_put_int(r, MUX_S_REMOTE_PORT);
712 				buffer_put_int(r, rid);
713 				buffer_put_int(r,
714 				    options.remote_forwards[i].allocated_port);
715 				goto out;
716 			}
717 		}
718 		break;
719 	}
720 
721 	if (options.control_master == SSHCTL_MASTER_ASK ||
722 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
723 		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
724 			debug2("%s: forwarding refused by user", __func__);
725 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
726 			buffer_put_int(r, rid);
727 			buffer_put_cstring(r, "Permission denied");
728 			goto out;
729 		}
730 	}
731 
732 	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
733 		if (channel_setup_local_fwd_listener(fwd.listen_host,
734 		    fwd.listen_port, fwd.connect_host, fwd.connect_port,
735 		    options.gateway_ports) < 0) {
736  fail:
737 			logit("slave-requested %s failed", fwd_desc);
738 			buffer_put_int(r, MUX_S_FAILURE);
739 			buffer_put_int(r, rid);
740 			buffer_put_cstring(r, "Port forwarding failed");
741 			goto out;
742 		}
743 		add_local_forward(&options, &fwd);
744 		freefwd = 0;
745 	} else {
746 		struct mux_channel_confirm_ctx *fctx;
747 
748 		if (channel_request_remote_forwarding(fwd.listen_host,
749 		    fwd.listen_port, fwd.connect_host, fwd.connect_port) < 0)
750 			goto fail;
751 		add_remote_forward(&options, &fwd);
752 		fctx = xcalloc(1, sizeof(*fctx));
753 		fctx->cid = c->self;
754 		fctx->rid = rid;
755 		fctx->fid = options.num_remote_forwards - 1;
756 		client_register_global_confirm(mux_confirm_remote_forward,
757 		    fctx);
758 		freefwd = 0;
759 		c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
760 		/* delayed reply in mux_confirm_remote_forward */
761 		goto out;
762 	}
763 	buffer_put_int(r, MUX_S_OK);
764 	buffer_put_int(r, rid);
765  out:
766 	if (fwd_desc != NULL)
767 		xfree(fwd_desc);
768 	if (freefwd) {
769 		if (fwd.listen_host != NULL)
770 			xfree(fwd.listen_host);
771 		if (fwd.connect_host != NULL)
772 			xfree(fwd.connect_host);
773 	}
774 	return ret;
775 }
776 
777 static int
process_mux_close_fwd(u_int rid,Channel * c,Buffer * m,Buffer * r)778 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
779 {
780 	Forward fwd;
781 	char *fwd_desc = NULL;
782 	u_int ftype;
783 	int ret = 0;
784 
785 	fwd.listen_host = fwd.connect_host = NULL;
786 	if (buffer_get_int_ret(&ftype, m) != 0 ||
787 	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
788 	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
789 	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
790 	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
791 		error("%s: malformed message", __func__);
792 		ret = -1;
793 		goto out;
794 	}
795 
796 	if (*fwd.listen_host == '\0') {
797 		xfree(fwd.listen_host);
798 		fwd.listen_host = NULL;
799 	}
800 	if (*fwd.connect_host == '\0') {
801 		xfree(fwd.connect_host);
802 		fwd.connect_host = NULL;
803 	}
804 
805 	debug2("%s: channel %d: request %s", __func__, c->self,
806 	    (fwd_desc = format_forward(ftype, &fwd)));
807 
808 	/* XXX implement this */
809 	buffer_put_int(r, MUX_S_FAILURE);
810 	buffer_put_int(r, rid);
811 	buffer_put_cstring(r, "unimplemented");
812 
813  out:
814 	if (fwd_desc != NULL)
815 		xfree(fwd_desc);
816 	if (fwd.listen_host != NULL)
817 		xfree(fwd.listen_host);
818 	if (fwd.connect_host != NULL)
819 		xfree(fwd.connect_host);
820 
821 	return ret;
822 }
823 
824 static int
process_mux_stdio_fwd(u_int rid,Channel * c,Buffer * m,Buffer * r)825 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
826 {
827 	Channel *nc;
828 	char *reserved, *chost;
829 	u_int cport, i, j;
830 	int new_fd[2];
831 
832 	chost = reserved = NULL;
833 	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
834 	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
835 	    buffer_get_int_ret(&cport, m) != 0) {
836 		if (reserved != NULL)
837 			xfree(reserved);
838 		if (chost != NULL)
839 			xfree(chost);
840 		error("%s: malformed message", __func__);
841 		return -1;
842 	}
843 	xfree(reserved);
844 
845 	debug2("%s: channel %d: request stdio fwd to %s:%u",
846 	    __func__, c->self, chost, cport);
847 
848 	/* Gather fds from client */
849 	for(i = 0; i < 2; i++) {
850 		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
851 			error("%s: failed to receive fd %d from slave",
852 			    __func__, i);
853 			for (j = 0; j < i; j++)
854 				close(new_fd[j]);
855 			xfree(chost);
856 
857 			/* prepare reply */
858 			buffer_put_int(r, MUX_S_FAILURE);
859 			buffer_put_int(r, rid);
860 			buffer_put_cstring(r,
861 			    "did not receive file descriptors");
862 			return -1;
863 		}
864 	}
865 
866 	debug3("%s: got fds stdin %d, stdout %d", __func__,
867 	    new_fd[0], new_fd[1]);
868 
869 	/* XXX support multiple child sessions in future */
870 	if (c->remote_id != -1) {
871 		debug2("%s: session already open", __func__);
872 		/* prepare reply */
873 		buffer_put_int(r, MUX_S_FAILURE);
874 		buffer_put_int(r, rid);
875 		buffer_put_cstring(r, "Multiple sessions not supported");
876  cleanup:
877 		close(new_fd[0]);
878 		close(new_fd[1]);
879 		xfree(chost);
880 		return 0;
881 	}
882 
883 	if (options.control_master == SSHCTL_MASTER_ASK ||
884 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
885 		if (!ask_permission("Allow forward to %s:%u? ",
886 		    chost, cport)) {
887 			debug2("%s: stdio fwd refused by user", __func__);
888 			/* prepare reply */
889 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
890 			buffer_put_int(r, rid);
891 			buffer_put_cstring(r, "Permission denied");
892 			goto cleanup;
893 		}
894 	}
895 
896 	/* enable nonblocking unless tty */
897 	if (!isatty(new_fd[0]))
898 		set_nonblock(new_fd[0]);
899 	if (!isatty(new_fd[1]))
900 		set_nonblock(new_fd[1]);
901 
902 	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
903 
904 	nc->ctl_chan = c->self;		/* link session -> control channel */
905 	c->remote_id = nc->self; 	/* link control -> session channel */
906 
907 	debug2("%s: channel_new: %d linked to control channel %d",
908 	    __func__, nc->self, nc->ctl_chan);
909 
910 	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
911 
912 	/* prepare reply */
913 	/* XXX defer until channel confirmed */
914 	buffer_put_int(r, MUX_S_SESSION_OPENED);
915 	buffer_put_int(r, rid);
916 	buffer_put_int(r, nc->self);
917 
918 	return 0;
919 }
920 
921 static int
process_mux_stop_listening(u_int rid,Channel * c,Buffer * m,Buffer * r)922 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
923 {
924 	debug("%s: channel %d: stop listening", __func__, c->self);
925 
926 	if (options.control_master == SSHCTL_MASTER_ASK ||
927 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
928 		if (!ask_permission("Disable further multiplexing on shared "
929 		    "connection to %s? ", host)) {
930 			debug2("%s: stop listen refused by user", __func__);
931 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
932 			buffer_put_int(r, rid);
933 			buffer_put_cstring(r, "Permission denied");
934 			return 0;
935 		}
936 	}
937 
938 	if (mux_listener_channel != NULL) {
939 		channel_free(mux_listener_channel);
940 		client_stop_mux();
941 		xfree(options.control_path);
942 		options.control_path = NULL;
943 		mux_listener_channel = NULL;
944 		muxserver_sock = -1;
945 	}
946 
947 	/* prepare reply */
948 	buffer_put_int(r, MUX_S_OK);
949 	buffer_put_int(r, rid);
950 
951 	return 0;
952 }
953 
954 /* Channel callbacks fired on read/write from mux slave fd */
955 static int
mux_master_read_cb(Channel * c)956 mux_master_read_cb(Channel *c)
957 {
958 	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
959 	Buffer in, out;
960 	void *ptr;
961 	u_int type, rid, have, i;
962 	int ret = -1;
963 
964 	/* Setup ctx and  */
965 	if (c->mux_ctx == NULL) {
966 		state = xcalloc(1, sizeof(*state));
967 		c->mux_ctx = state;
968 		channel_register_cleanup(c->self,
969 		    mux_master_control_cleanup_cb, 0);
970 
971 		/* Send hello */
972 		buffer_init(&out);
973 		buffer_put_int(&out, MUX_MSG_HELLO);
974 		buffer_put_int(&out, SSHMUX_VER);
975 		/* no extensions */
976 		buffer_put_string(&c->output, buffer_ptr(&out),
977 		    buffer_len(&out));
978 		buffer_free(&out);
979 		debug3("%s: channel %d: hello sent", __func__, c->self);
980 		return 0;
981 	}
982 
983 	buffer_init(&in);
984 	buffer_init(&out);
985 
986 	/* Channel code ensures that we receive whole packets */
987 	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
988  malf:
989 		error("%s: malformed message", __func__);
990 		goto out;
991 	}
992 	buffer_append(&in, ptr, have);
993 
994 	if (buffer_get_int_ret(&type, &in) != 0)
995 		goto malf;
996 	debug3("%s: channel %d packet type 0x%08x len %u",
997 	    __func__, c->self, type, buffer_len(&in));
998 
999 	if (type == MUX_MSG_HELLO)
1000 		rid = 0;
1001 	else {
1002 		if (!state->hello_rcvd) {
1003 			error("%s: expected MUX_MSG_HELLO(0x%08x), "
1004 			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1005 			goto out;
1006 		}
1007 		if (buffer_get_int_ret(&rid, &in) != 0)
1008 			goto malf;
1009 	}
1010 
1011 	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1012 		if (type == mux_master_handlers[i].type) {
1013 			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1014 			break;
1015 		}
1016 	}
1017 	if (mux_master_handlers[i].handler == NULL) {
1018 		error("%s: unsupported mux message 0x%08x", __func__, type);
1019 		buffer_put_int(&out, MUX_S_FAILURE);
1020 		buffer_put_int(&out, rid);
1021 		buffer_put_cstring(&out, "unsupported request");
1022 		ret = 0;
1023 	}
1024 	/* Enqueue reply packet */
1025 	if (buffer_len(&out) != 0) {
1026 		buffer_put_string(&c->output, buffer_ptr(&out),
1027 		    buffer_len(&out));
1028 	}
1029  out:
1030 	buffer_free(&in);
1031 	buffer_free(&out);
1032 	return ret;
1033 }
1034 
1035 void
mux_exit_message(Channel * c,int exitval)1036 mux_exit_message(Channel *c, int exitval)
1037 {
1038 	Buffer m;
1039 	Channel *mux_chan;
1040 
1041 	debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
1042 	    exitval);
1043 
1044 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1045 		fatal("%s: channel %d missing mux channel %d",
1046 		    __func__, c->self, c->ctl_chan);
1047 
1048 	/* Append exit message packet to control socket output queue */
1049 	buffer_init(&m);
1050 	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1051 	buffer_put_int(&m, c->self);
1052 	buffer_put_int(&m, exitval);
1053 
1054 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1055 	buffer_free(&m);
1056 }
1057 
1058 void
mux_tty_alloc_failed(Channel * c)1059 mux_tty_alloc_failed(Channel *c)
1060 {
1061 	Buffer m;
1062 	Channel *mux_chan;
1063 
1064 	debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1065 
1066 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1067 		fatal("%s: channel %d missing mux channel %d",
1068 		    __func__, c->self, c->ctl_chan);
1069 
1070 	/* Append exit message packet to control socket output queue */
1071 	buffer_init(&m);
1072 	buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1073 	buffer_put_int(&m, c->self);
1074 
1075 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1076 	buffer_free(&m);
1077 }
1078 
1079 /* Prepare a mux master to listen on a Unix domain socket. */
1080 void
muxserver_listen(void)1081 muxserver_listen(void)
1082 {
1083 	struct sockaddr_un addr;
1084 	socklen_t sun_len;
1085 	mode_t old_umask;
1086 	char *orig_control_path = options.control_path;
1087 	char rbuf[16+1];
1088 	u_int i, r;
1089 
1090 	if (options.control_path == NULL ||
1091 	    options.control_master == SSHCTL_MASTER_NO)
1092 		return;
1093 
1094 	debug("setting up multiplex master socket");
1095 
1096 	/*
1097 	 * Use a temporary path before listen so we can pseudo-atomically
1098 	 * establish the listening socket in its final location to avoid
1099 	 * other processes racing in between bind() and listen() and hitting
1100 	 * an unready socket.
1101 	 */
1102 	for (i = 0; i < sizeof(rbuf) - 1; i++) {
1103 		r = arc4random_uniform(26+26+10);
1104 		rbuf[i] = (r < 26) ? 'a' + r :
1105 		    (r < 26*2) ? 'A' + r - 26 :
1106 		    '0' + r - 26 - 26;
1107 	}
1108 	rbuf[sizeof(rbuf) - 1] = '\0';
1109 	options.control_path = NULL;
1110 	xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1111 	debug3("%s: temporary control path %s", __func__, options.control_path);
1112 
1113 	memset(&addr, '\0', sizeof(addr));
1114 	addr.sun_family = AF_UNIX;
1115 	sun_len = offsetof(struct sockaddr_un, sun_path) +
1116 	    strlen(options.control_path) + 1;
1117 
1118 	if (strlcpy(addr.sun_path, options.control_path,
1119 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1120 		error("ControlPath \"%s\" too long for Unix domain socket",
1121 		    options.control_path);
1122 		goto disable_mux_master;
1123 	}
1124 
1125 	if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1126 		fatal("%s socket(): %s", __func__, strerror(errno));
1127 
1128 	old_umask = umask(0177);
1129 	if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1130 		if (errno == EINVAL || errno == EADDRINUSE) {
1131 			error("ControlSocket %s already exists, "
1132 			    "disabling multiplexing", options.control_path);
1133  disable_mux_master:
1134 			if (muxserver_sock != -1) {
1135 				close(muxserver_sock);
1136 				muxserver_sock = -1;
1137 			}
1138 			xfree(options.control_path);
1139 			options.control_path = NULL;
1140 			options.control_master = SSHCTL_MASTER_NO;
1141 			return;
1142 		} else
1143 			fatal("%s bind(): %s", __func__, strerror(errno));
1144 	}
1145 	umask(old_umask);
1146 
1147 	if (listen(muxserver_sock, 64) == -1)
1148 		fatal("%s listen(): %s", __func__, strerror(errno));
1149 
1150 	/* Now atomically "move" the mux socket into position */
1151 	if (link(options.control_path, orig_control_path) != 0) {
1152 		if (errno != EEXIST) {
1153 			fatal("%s: link mux listener %s => %s: %s", __func__,
1154 			    options.control_path, orig_control_path,
1155 			    strerror(errno));
1156 		}
1157 		error("ControlSocket %s already exists, disabling multiplexing",
1158 		    orig_control_path);
1159 		xfree(orig_control_path);
1160 		unlink(options.control_path);
1161 		goto disable_mux_master;
1162 	}
1163 	unlink(options.control_path);
1164 	xfree(options.control_path);
1165 	options.control_path = orig_control_path;
1166 
1167 	set_nonblock(muxserver_sock);
1168 
1169 	mux_listener_channel = channel_new("mux listener",
1170 	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1171 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1172 	    0, options.control_path, 1);
1173 	mux_listener_channel->mux_rcb = mux_master_read_cb;
1174 	debug3("%s: mux listener channel %d fd %d", __func__,
1175 	    mux_listener_channel->self, mux_listener_channel->sock);
1176 }
1177 
1178 /* Callback on open confirmation in mux master for a mux client session. */
1179 static void
mux_session_confirm(int id,int success,void * arg)1180 mux_session_confirm(int id, int success, void *arg)
1181 {
1182 	struct mux_session_confirm_ctx *cctx = arg;
1183 	const char *display;
1184 	Channel *c, *cc;
1185 	int i;
1186 	Buffer reply;
1187 
1188 	if (cctx == NULL)
1189 		fatal("%s: cctx == NULL", __func__);
1190 	if ((c = channel_by_id(id)) == NULL)
1191 		fatal("%s: no channel for id %d", __func__, id);
1192 	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1193 		fatal("%s: channel %d lacks control channel %d", __func__,
1194 		    id, c->ctl_chan);
1195 
1196 	if (!success) {
1197 		debug3("%s: sending failure reply", __func__);
1198 		/* prepare reply */
1199 		buffer_init(&reply);
1200 		buffer_put_int(&reply, MUX_S_FAILURE);
1201 		buffer_put_int(&reply, cctx->rid);
1202 		buffer_put_cstring(&reply, "Session open refused by peer");
1203 		goto done;
1204 	}
1205 
1206 	display = getenv("DISPLAY");
1207 	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1208 		char *proto, *data;
1209 
1210 		/* Get reasonable local authentication information. */
1211 		client_x11_get_proto(display, options.xauth_location,
1212 		    options.forward_x11_trusted, options.forward_x11_timeout,
1213 		    &proto, &data);
1214 		/* Request forwarding with authentication spoofing. */
1215 		debug("Requesting X11 forwarding with authentication "
1216 		    "spoofing.");
1217 		x11_request_forwarding_with_spoofing(id, display, proto,
1218 		    data, 1);
1219 		client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1220 		/* XXX exit_on_forward_failure */
1221 	}
1222 
1223 	if (cctx->want_agent_fwd && options.forward_agent) {
1224 		debug("Requesting authentication agent forwarding.");
1225 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1226 		packet_send();
1227 	}
1228 
1229 	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1230 	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1231 
1232 	debug3("%s: sending success reply", __func__);
1233 	/* prepare reply */
1234 	buffer_init(&reply);
1235 	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1236 	buffer_put_int(&reply, cctx->rid);
1237 	buffer_put_int(&reply, c->self);
1238 
1239  done:
1240 	/* Send reply */
1241 	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1242 	buffer_free(&reply);
1243 
1244 	if (cc->mux_pause <= 0)
1245 		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1246 	cc->mux_pause = 0; /* start processing messages again */
1247 	c->open_confirm_ctx = NULL;
1248 	buffer_free(&cctx->cmd);
1249 	xfree(cctx->term);
1250 	if (cctx->env != NULL) {
1251 		for (i = 0; cctx->env[i] != NULL; i++)
1252 			xfree(cctx->env[i]);
1253 		xfree(cctx->env);
1254 	}
1255 	xfree(cctx);
1256 }
1257 
1258 /* ** Multiplexing client support */
1259 
1260 /* Exit signal handler */
1261 static void
control_client_sighandler(int signo)1262 control_client_sighandler(int signo)
1263 {
1264 	muxclient_terminate = signo;
1265 }
1266 
1267 /*
1268  * Relay signal handler - used to pass some signals from mux client to
1269  * mux master.
1270  */
1271 static void
control_client_sigrelay(int signo)1272 control_client_sigrelay(int signo)
1273 {
1274 	int save_errno = errno;
1275 
1276 	if (muxserver_pid > 1)
1277 		kill(muxserver_pid, signo);
1278 
1279 	errno = save_errno;
1280 }
1281 
1282 static int
mux_client_read(int fd,Buffer * b,u_int need)1283 mux_client_read(int fd, Buffer *b, u_int need)
1284 {
1285 	u_int have;
1286 	ssize_t len;
1287 	u_char *p;
1288 	struct pollfd pfd;
1289 
1290 	pfd.fd = fd;
1291 	pfd.events = POLLIN;
1292 	p = buffer_append_space(b, need);
1293 	for (have = 0; have < need; ) {
1294 		if (muxclient_terminate) {
1295 			errno = EINTR;
1296 			return -1;
1297 		}
1298 		len = read(fd, p + have, need - have);
1299 		if (len < 0) {
1300 			switch (errno) {
1301 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1302 			case EWOULDBLOCK:
1303 #endif
1304 			case EAGAIN:
1305 				(void)poll(&pfd, 1, -1);
1306 				/* FALLTHROUGH */
1307 			case EINTR:
1308 				continue;
1309 			default:
1310 				return -1;
1311 			}
1312 		}
1313 		if (len == 0) {
1314 			errno = EPIPE;
1315 			return -1;
1316 		}
1317 		have += (u_int)len;
1318 	}
1319 	return 0;
1320 }
1321 
1322 static int
mux_client_write_packet(int fd,Buffer * m)1323 mux_client_write_packet(int fd, Buffer *m)
1324 {
1325 	Buffer queue;
1326 	u_int have, need;
1327 	int oerrno, len;
1328 	u_char *ptr;
1329 	struct pollfd pfd;
1330 
1331 	pfd.fd = fd;
1332 	pfd.events = POLLOUT;
1333 	buffer_init(&queue);
1334 	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1335 
1336 	need = buffer_len(&queue);
1337 	ptr = buffer_ptr(&queue);
1338 
1339 	for (have = 0; have < need; ) {
1340 		if (muxclient_terminate) {
1341 			buffer_free(&queue);
1342 			errno = EINTR;
1343 			return -1;
1344 		}
1345 		len = write(fd, ptr + have, need - have);
1346 		if (len < 0) {
1347 			switch (errno) {
1348 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1349 			case EWOULDBLOCK:
1350 #endif
1351 			case EAGAIN:
1352 				(void)poll(&pfd, 1, -1);
1353 				/* FALLTHROUGH */
1354 			case EINTR:
1355 				continue;
1356 			default:
1357 				oerrno = errno;
1358 				buffer_free(&queue);
1359 				errno = oerrno;
1360 				return -1;
1361 			}
1362 		}
1363 		if (len == 0) {
1364 			buffer_free(&queue);
1365 			errno = EPIPE;
1366 			return -1;
1367 		}
1368 		have += (u_int)len;
1369 	}
1370 	buffer_free(&queue);
1371 	return 0;
1372 }
1373 
1374 static int
mux_client_read_packet(int fd,Buffer * m)1375 mux_client_read_packet(int fd, Buffer *m)
1376 {
1377 	Buffer queue;
1378 	u_int need, have;
1379 	void *ptr;
1380 	int oerrno;
1381 
1382 	buffer_init(&queue);
1383 	if (mux_client_read(fd, &queue, 4) != 0) {
1384 		if ((oerrno = errno) == EPIPE)
1385 		debug3("%s: read header failed: %s", __func__, strerror(errno));
1386 		errno = oerrno;
1387 		return -1;
1388 	}
1389 	need = get_u32(buffer_ptr(&queue));
1390 	if (mux_client_read(fd, &queue, need) != 0) {
1391 		oerrno = errno;
1392 		debug3("%s: read body failed: %s", __func__, strerror(errno));
1393 		errno = oerrno;
1394 		return -1;
1395 	}
1396 	ptr = buffer_get_string_ptr(&queue, &have);
1397 	buffer_append(m, ptr, have);
1398 	buffer_free(&queue);
1399 	return 0;
1400 }
1401 
1402 static int
mux_client_hello_exchange(int fd)1403 mux_client_hello_exchange(int fd)
1404 {
1405 	Buffer m;
1406 	u_int type, ver;
1407 
1408 	buffer_init(&m);
1409 	buffer_put_int(&m, MUX_MSG_HELLO);
1410 	buffer_put_int(&m, SSHMUX_VER);
1411 	/* no extensions */
1412 
1413 	if (mux_client_write_packet(fd, &m) != 0)
1414 		fatal("%s: write packet: %s", __func__, strerror(errno));
1415 
1416 	buffer_clear(&m);
1417 
1418 	/* Read their HELLO */
1419 	if (mux_client_read_packet(fd, &m) != 0) {
1420 		buffer_free(&m);
1421 		return -1;
1422 	}
1423 
1424 	type = buffer_get_int(&m);
1425 	if (type != MUX_MSG_HELLO)
1426 		fatal("%s: expected HELLO (%u) received %u",
1427 		    __func__, MUX_MSG_HELLO, type);
1428 	ver = buffer_get_int(&m);
1429 	if (ver != SSHMUX_VER)
1430 		fatal("Unsupported multiplexing protocol version %d "
1431 		    "(expected %d)", ver, SSHMUX_VER);
1432 	debug2("%s: master version %u", __func__, ver);
1433 	/* No extensions are presently defined */
1434 	while (buffer_len(&m) > 0) {
1435 		char *name = buffer_get_string(&m, NULL);
1436 		char *value = buffer_get_string(&m, NULL);
1437 
1438 		debug2("Unrecognised master extension \"%s\"", name);
1439 		xfree(name);
1440 		xfree(value);
1441 	}
1442 	buffer_free(&m);
1443 	return 0;
1444 }
1445 
1446 static u_int
mux_client_request_alive(int fd)1447 mux_client_request_alive(int fd)
1448 {
1449 	Buffer m;
1450 	char *e;
1451 	u_int pid, type, rid;
1452 
1453 	debug3("%s: entering", __func__);
1454 
1455 	buffer_init(&m);
1456 	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1457 	buffer_put_int(&m, muxclient_request_id);
1458 
1459 	if (mux_client_write_packet(fd, &m) != 0)
1460 		fatal("%s: write packet: %s", __func__, strerror(errno));
1461 
1462 	buffer_clear(&m);
1463 
1464 	/* Read their reply */
1465 	if (mux_client_read_packet(fd, &m) != 0) {
1466 		buffer_free(&m);
1467 		return 0;
1468 	}
1469 
1470 	type = buffer_get_int(&m);
1471 	if (type != MUX_S_ALIVE) {
1472 		e = buffer_get_string(&m, NULL);
1473 		fatal("%s: master returned error: %s", __func__, e);
1474 	}
1475 
1476 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1477 		fatal("%s: out of sequence reply: my id %u theirs %u",
1478 		    __func__, muxclient_request_id, rid);
1479 	pid = buffer_get_int(&m);
1480 	buffer_free(&m);
1481 
1482 	debug3("%s: done pid = %u", __func__, pid);
1483 
1484 	muxclient_request_id++;
1485 
1486 	return pid;
1487 }
1488 
1489 static void
mux_client_request_terminate(int fd)1490 mux_client_request_terminate(int fd)
1491 {
1492 	Buffer m;
1493 	char *e;
1494 	u_int type, rid;
1495 
1496 	debug3("%s: entering", __func__);
1497 
1498 	buffer_init(&m);
1499 	buffer_put_int(&m, MUX_C_TERMINATE);
1500 	buffer_put_int(&m, muxclient_request_id);
1501 
1502 	if (mux_client_write_packet(fd, &m) != 0)
1503 		fatal("%s: write packet: %s", __func__, strerror(errno));
1504 
1505 	buffer_clear(&m);
1506 
1507 	/* Read their reply */
1508 	if (mux_client_read_packet(fd, &m) != 0) {
1509 		/* Remote end exited already */
1510 		if (errno == EPIPE) {
1511 			buffer_free(&m);
1512 			return;
1513 		}
1514 		fatal("%s: read from master failed: %s",
1515 		    __func__, strerror(errno));
1516 	}
1517 
1518 	type = buffer_get_int(&m);
1519 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1520 		fatal("%s: out of sequence reply: my id %u theirs %u",
1521 		    __func__, muxclient_request_id, rid);
1522 	switch (type) {
1523 	case MUX_S_OK:
1524 		break;
1525 	case MUX_S_PERMISSION_DENIED:
1526 		e = buffer_get_string(&m, NULL);
1527 		fatal("Master refused termination request: %s", e);
1528 	case MUX_S_FAILURE:
1529 		e = buffer_get_string(&m, NULL);
1530 		fatal("%s: termination request failed: %s", __func__, e);
1531 	default:
1532 		fatal("%s: unexpected response from master 0x%08x",
1533 		    __func__, type);
1534 	}
1535 	buffer_free(&m);
1536 	muxclient_request_id++;
1537 }
1538 
1539 static int
mux_client_request_forward(int fd,u_int ftype,Forward * fwd)1540 mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
1541 {
1542 	Buffer m;
1543 	char *e, *fwd_desc;
1544 	u_int type, rid;
1545 
1546 	fwd_desc = format_forward(ftype, fwd);
1547 	debug("Requesting %s", fwd_desc);
1548 	xfree(fwd_desc);
1549 
1550 	buffer_init(&m);
1551 	buffer_put_int(&m, MUX_C_OPEN_FWD);
1552 	buffer_put_int(&m, muxclient_request_id);
1553 	buffer_put_int(&m, ftype);
1554 	buffer_put_cstring(&m,
1555 	    fwd->listen_host == NULL ? "" : fwd->listen_host);
1556 	buffer_put_int(&m, fwd->listen_port);
1557 	buffer_put_cstring(&m,
1558 	    fwd->connect_host == NULL ? "" : fwd->connect_host);
1559 	buffer_put_int(&m, fwd->connect_port);
1560 
1561 	if (mux_client_write_packet(fd, &m) != 0)
1562 		fatal("%s: write packet: %s", __func__, strerror(errno));
1563 
1564 	buffer_clear(&m);
1565 
1566 	/* Read their reply */
1567 	if (mux_client_read_packet(fd, &m) != 0) {
1568 		buffer_free(&m);
1569 		return -1;
1570 	}
1571 
1572 	type = buffer_get_int(&m);
1573 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1574 		fatal("%s: out of sequence reply: my id %u theirs %u",
1575 		    __func__, muxclient_request_id, rid);
1576 	switch (type) {
1577 	case MUX_S_OK:
1578 		break;
1579 	case MUX_S_REMOTE_PORT:
1580 		fwd->allocated_port = buffer_get_int(&m);
1581 		logit("Allocated port %u for remote forward to %s:%d",
1582 		    fwd->allocated_port,
1583 		    fwd->connect_host ? fwd->connect_host : "",
1584 		    fwd->connect_port);
1585 		if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1586 			fprintf(stdout, "%u\n", fwd->allocated_port);
1587 		break;
1588 	case MUX_S_PERMISSION_DENIED:
1589 		e = buffer_get_string(&m, NULL);
1590 		buffer_free(&m);
1591 		error("Master refused forwarding request: %s", e);
1592 		return -1;
1593 	case MUX_S_FAILURE:
1594 		e = buffer_get_string(&m, NULL);
1595 		buffer_free(&m);
1596 		error("%s: forwarding request failed: %s", __func__, e);
1597 		return -1;
1598 	default:
1599 		fatal("%s: unexpected response from master 0x%08x",
1600 		    __func__, type);
1601 	}
1602 	buffer_free(&m);
1603 
1604 	muxclient_request_id++;
1605 	return 0;
1606 }
1607 
1608 static int
mux_client_request_forwards(int fd)1609 mux_client_request_forwards(int fd)
1610 {
1611 	int i;
1612 
1613 	debug3("%s: requesting forwardings: %d local, %d remote", __func__,
1614 	    options.num_local_forwards, options.num_remote_forwards);
1615 
1616 	/* XXX ExitOnForwardingFailure */
1617 	for (i = 0; i < options.num_local_forwards; i++) {
1618 		if (mux_client_request_forward(fd,
1619 		    options.local_forwards[i].connect_port == 0 ?
1620 		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1621 		    options.local_forwards + i) != 0)
1622 			return -1;
1623 	}
1624 	for (i = 0; i < options.num_remote_forwards; i++) {
1625 		if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
1626 		    options.remote_forwards + i) != 0)
1627 			return -1;
1628 	}
1629 	return 0;
1630 }
1631 
1632 static int
mux_client_request_session(int fd)1633 mux_client_request_session(int fd)
1634 {
1635 	Buffer m;
1636 	char *e, *term;
1637 	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1638 	extern char **environ;
1639 	int devnull, rawmode;
1640 
1641 	debug3("%s: entering", __func__);
1642 
1643 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1644 		error("%s: master alive request failed", __func__);
1645 		return -1;
1646 	}
1647 
1648 	signal(SIGPIPE, SIG_IGN);
1649 
1650 	if (stdin_null_flag) {
1651 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1652 			fatal("open(/dev/null): %s", strerror(errno));
1653 		if (dup2(devnull, STDIN_FILENO) == -1)
1654 			fatal("dup2: %s", strerror(errno));
1655 		if (devnull > STDERR_FILENO)
1656 			close(devnull);
1657 	}
1658 
1659 	term = getenv("TERM");
1660 
1661 	buffer_init(&m);
1662 	buffer_put_int(&m, MUX_C_NEW_SESSION);
1663 	buffer_put_int(&m, muxclient_request_id);
1664 	buffer_put_cstring(&m, ""); /* reserved */
1665 	buffer_put_int(&m, tty_flag);
1666 	buffer_put_int(&m, options.forward_x11);
1667 	buffer_put_int(&m, options.forward_agent);
1668 	buffer_put_int(&m, subsystem_flag);
1669 	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1670 	    0xffffffff : (u_int)options.escape_char);
1671 	buffer_put_cstring(&m, term == NULL ? "" : term);
1672 	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1673 
1674 	if (options.num_send_env > 0 && environ != NULL) {
1675 		/* Pass environment */
1676 		for (i = 0; environ[i] != NULL; i++) {
1677 			if (env_permitted(environ[i])) {
1678 				buffer_put_cstring(&m, environ[i]);
1679 			}
1680 		}
1681 	}
1682 
1683 	if (mux_client_write_packet(fd, &m) != 0)
1684 		fatal("%s: write packet: %s", __func__, strerror(errno));
1685 
1686 	/* Send the stdio file descriptors */
1687 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1688 	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1689 	    mm_send_fd(fd, STDERR_FILENO) == -1)
1690 		fatal("%s: send fds failed", __func__);
1691 
1692 	debug3("%s: session request sent", __func__);
1693 
1694 	/* Read their reply */
1695 	buffer_clear(&m);
1696 	if (mux_client_read_packet(fd, &m) != 0) {
1697 		error("%s: read from master failed: %s",
1698 		    __func__, strerror(errno));
1699 		buffer_free(&m);
1700 		return -1;
1701 	}
1702 
1703 	type = buffer_get_int(&m);
1704 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1705 		fatal("%s: out of sequence reply: my id %u theirs %u",
1706 		    __func__, muxclient_request_id, rid);
1707 	switch (type) {
1708 	case MUX_S_SESSION_OPENED:
1709 		sid = buffer_get_int(&m);
1710 		debug("%s: master session id: %u", __func__, sid);
1711 		break;
1712 	case MUX_S_PERMISSION_DENIED:
1713 		e = buffer_get_string(&m, NULL);
1714 		buffer_free(&m);
1715 		error("Master refused session request: %s", e);
1716 		return -1;
1717 	case MUX_S_FAILURE:
1718 		e = buffer_get_string(&m, NULL);
1719 		buffer_free(&m);
1720 		error("%s: session request failed: %s", __func__, e);
1721 		return -1;
1722 	default:
1723 		buffer_free(&m);
1724 		error("%s: unexpected response from master 0x%08x",
1725 		    __func__, type);
1726 		return -1;
1727 	}
1728 	muxclient_request_id++;
1729 
1730 	signal(SIGHUP, control_client_sighandler);
1731 	signal(SIGINT, control_client_sighandler);
1732 	signal(SIGTERM, control_client_sighandler);
1733 	signal(SIGWINCH, control_client_sigrelay);
1734 
1735 	rawmode = tty_flag;
1736 	if (tty_flag)
1737 		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1738 
1739 	/*
1740 	 * Stick around until the controlee closes the client_fd.
1741 	 * Before it does, it is expected to write an exit message.
1742 	 * This process must read the value and wait for the closure of
1743 	 * the client_fd; if this one closes early, the multiplex master will
1744 	 * terminate early too (possibly losing data).
1745 	 */
1746 	for (exitval = 255, exitval_seen = 0;;) {
1747 		buffer_clear(&m);
1748 		if (mux_client_read_packet(fd, &m) != 0)
1749 			break;
1750 		type = buffer_get_int(&m);
1751 		switch (type) {
1752 		case MUX_S_TTY_ALLOC_FAIL:
1753 			if ((esid = buffer_get_int(&m)) != sid)
1754 				fatal("%s: tty alloc fail on unknown session: "
1755 				    "my id %u theirs %u",
1756 				    __func__, sid, esid);
1757 			leave_raw_mode(options.request_tty ==
1758 			    REQUEST_TTY_FORCE);
1759 			rawmode = 0;
1760 			continue;
1761 		case MUX_S_EXIT_MESSAGE:
1762 			if ((esid = buffer_get_int(&m)) != sid)
1763 				fatal("%s: exit on unknown session: "
1764 				    "my id %u theirs %u",
1765 				    __func__, sid, esid);
1766 			if (exitval_seen)
1767 				fatal("%s: exitval sent twice", __func__);
1768 			exitval = buffer_get_int(&m);
1769 			exitval_seen = 1;
1770 			continue;
1771 		default:
1772 			e = buffer_get_string(&m, NULL);
1773 			fatal("%s: master returned error: %s", __func__, e);
1774 		}
1775 	}
1776 
1777 	close(fd);
1778 	if (rawmode)
1779 		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1780 
1781 	if (muxclient_terminate) {
1782 		debug2("Exiting on signal %d", muxclient_terminate);
1783 		exitval = 255;
1784 	} else if (!exitval_seen) {
1785 		debug2("Control master terminated unexpectedly");
1786 		exitval = 255;
1787 	} else
1788 		debug2("Received exit status from master %d", exitval);
1789 
1790 	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1791 		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1792 
1793 	exit(exitval);
1794 }
1795 
1796 static int
mux_client_request_stdio_fwd(int fd)1797 mux_client_request_stdio_fwd(int fd)
1798 {
1799 	Buffer m;
1800 	char *e;
1801 	u_int type, rid, sid;
1802 	int devnull;
1803 
1804 	debug3("%s: entering", __func__);
1805 
1806 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1807 		error("%s: master alive request failed", __func__);
1808 		return -1;
1809 	}
1810 
1811 	signal(SIGPIPE, SIG_IGN);
1812 
1813 	if (stdin_null_flag) {
1814 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1815 			fatal("open(/dev/null): %s", strerror(errno));
1816 		if (dup2(devnull, STDIN_FILENO) == -1)
1817 			fatal("dup2: %s", strerror(errno));
1818 		if (devnull > STDERR_FILENO)
1819 			close(devnull);
1820 	}
1821 
1822 	buffer_init(&m);
1823 	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1824 	buffer_put_int(&m, muxclient_request_id);
1825 	buffer_put_cstring(&m, ""); /* reserved */
1826 	buffer_put_cstring(&m, stdio_forward_host);
1827 	buffer_put_int(&m, stdio_forward_port);
1828 
1829 	if (mux_client_write_packet(fd, &m) != 0)
1830 		fatal("%s: write packet: %s", __func__, strerror(errno));
1831 
1832 	/* Send the stdio file descriptors */
1833 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1834 	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1835 		fatal("%s: send fds failed", __func__);
1836 
1837 	debug3("%s: stdio forward request sent", __func__);
1838 
1839 	/* Read their reply */
1840 	buffer_clear(&m);
1841 
1842 	if (mux_client_read_packet(fd, &m) != 0) {
1843 		error("%s: read from master failed: %s",
1844 		    __func__, strerror(errno));
1845 		buffer_free(&m);
1846 		return -1;
1847 	}
1848 
1849 	type = buffer_get_int(&m);
1850 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1851 		fatal("%s: out of sequence reply: my id %u theirs %u",
1852 		    __func__, muxclient_request_id, rid);
1853 	switch (type) {
1854 	case MUX_S_SESSION_OPENED:
1855 		sid = buffer_get_int(&m);
1856 		debug("%s: master session id: %u", __func__, sid);
1857 		break;
1858 	case MUX_S_PERMISSION_DENIED:
1859 		e = buffer_get_string(&m, NULL);
1860 		buffer_free(&m);
1861 		fatal("Master refused stdio forwarding request: %s", e);
1862 	case MUX_S_FAILURE:
1863 		e = buffer_get_string(&m, NULL);
1864 		buffer_free(&m);
1865 		fatal("%s: stdio forwarding request failed: %s", __func__, e);
1866 	default:
1867 		buffer_free(&m);
1868 		error("%s: unexpected response from master 0x%08x",
1869 		    __func__, type);
1870 		return -1;
1871 	}
1872 	muxclient_request_id++;
1873 
1874 	signal(SIGHUP, control_client_sighandler);
1875 	signal(SIGINT, control_client_sighandler);
1876 	signal(SIGTERM, control_client_sighandler);
1877 	signal(SIGWINCH, control_client_sigrelay);
1878 
1879 	/*
1880 	 * Stick around until the controlee closes the client_fd.
1881 	 */
1882 	buffer_clear(&m);
1883 	if (mux_client_read_packet(fd, &m) != 0) {
1884 		if (errno == EPIPE ||
1885 		    (errno == EINTR && muxclient_terminate != 0))
1886 			return 0;
1887 		fatal("%s: mux_client_read_packet: %s",
1888 		    __func__, strerror(errno));
1889 	}
1890 	fatal("%s: master returned unexpected message %u", __func__, type);
1891 }
1892 
1893 static void
mux_client_request_stop_listening(int fd)1894 mux_client_request_stop_listening(int fd)
1895 {
1896 	Buffer m;
1897 	char *e;
1898 	u_int type, rid;
1899 
1900 	debug3("%s: entering", __func__);
1901 
1902 	buffer_init(&m);
1903 	buffer_put_int(&m, MUX_C_STOP_LISTENING);
1904 	buffer_put_int(&m, muxclient_request_id);
1905 
1906 	if (mux_client_write_packet(fd, &m) != 0)
1907 		fatal("%s: write packet: %s", __func__, strerror(errno));
1908 
1909 	buffer_clear(&m);
1910 
1911 	/* Read their reply */
1912 	if (mux_client_read_packet(fd, &m) != 0)
1913 		fatal("%s: read from master failed: %s",
1914 		    __func__, strerror(errno));
1915 
1916 	type = buffer_get_int(&m);
1917 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1918 		fatal("%s: out of sequence reply: my id %u theirs %u",
1919 		    __func__, muxclient_request_id, rid);
1920 	switch (type) {
1921 	case MUX_S_OK:
1922 		break;
1923 	case MUX_S_PERMISSION_DENIED:
1924 		e = buffer_get_string(&m, NULL);
1925 		fatal("Master refused stop listening request: %s", e);
1926 	case MUX_S_FAILURE:
1927 		e = buffer_get_string(&m, NULL);
1928 		fatal("%s: stop listening request failed: %s", __func__, e);
1929 	default:
1930 		fatal("%s: unexpected response from master 0x%08x",
1931 		    __func__, type);
1932 	}
1933 	buffer_free(&m);
1934 	muxclient_request_id++;
1935 }
1936 
1937 /* Multiplex client main loop. */
1938 void
muxclient(const char * path)1939 muxclient(const char *path)
1940 {
1941 	struct sockaddr_un addr;
1942 	socklen_t sun_len;
1943 	int sock;
1944 	u_int pid;
1945 
1946 	if (muxclient_command == 0) {
1947 		if (stdio_forward_host != NULL)
1948 			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1949 		else
1950 			muxclient_command = SSHMUX_COMMAND_OPEN;
1951 	}
1952 
1953 	switch (options.control_master) {
1954 	case SSHCTL_MASTER_AUTO:
1955 	case SSHCTL_MASTER_AUTO_ASK:
1956 		debug("auto-mux: Trying existing master");
1957 		/* FALLTHROUGH */
1958 	case SSHCTL_MASTER_NO:
1959 		break;
1960 	default:
1961 		return;
1962 	}
1963 
1964 	memset(&addr, '\0', sizeof(addr));
1965 	addr.sun_family = AF_UNIX;
1966 	sun_len = offsetof(struct sockaddr_un, sun_path) +
1967 	    strlen(path) + 1;
1968 
1969 	if (strlcpy(addr.sun_path, path,
1970 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1971 		fatal("ControlPath too long");
1972 
1973 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1974 		fatal("%s socket(): %s", __func__, strerror(errno));
1975 
1976 	if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
1977 		switch (muxclient_command) {
1978 		case SSHMUX_COMMAND_OPEN:
1979 		case SSHMUX_COMMAND_STDIO_FWD:
1980 			break;
1981 		default:
1982 			fatal("Control socket connect(%.100s): %s", path,
1983 			    strerror(errno));
1984 		}
1985 		if (errno == ECONNREFUSED &&
1986 		    options.control_master != SSHCTL_MASTER_NO) {
1987 			debug("Stale control socket %.100s, unlinking", path);
1988 			unlink(path);
1989 		} else if (errno == ENOENT) {
1990 			debug("Control socket \"%.100s\" does not exist", path);
1991 		} else {
1992 			error("Control socket connect(%.100s): %s", path,
1993 			    strerror(errno));
1994 		}
1995 		close(sock);
1996 		return;
1997 	}
1998 	set_nonblock(sock);
1999 
2000 	if (mux_client_hello_exchange(sock) != 0) {
2001 		error("%s: master hello exchange failed", __func__);
2002 		close(sock);
2003 		return;
2004 	}
2005 
2006 	switch (muxclient_command) {
2007 	case SSHMUX_COMMAND_ALIVE_CHECK:
2008 		if ((pid = mux_client_request_alive(sock)) == 0)
2009 			fatal("%s: master alive check failed", __func__);
2010 		fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2011 		exit(0);
2012 	case SSHMUX_COMMAND_TERMINATE:
2013 		mux_client_request_terminate(sock);
2014 		fprintf(stderr, "Exit request sent.\r\n");
2015 		exit(0);
2016 	case SSHMUX_COMMAND_FORWARD:
2017 		if (mux_client_request_forwards(sock) != 0)
2018 			fatal("%s: master forward request failed", __func__);
2019 		exit(0);
2020 	case SSHMUX_COMMAND_OPEN:
2021 		if (mux_client_request_forwards(sock) != 0) {
2022 			error("%s: master forward request failed", __func__);
2023 			return;
2024 		}
2025 		mux_client_request_session(sock);
2026 		return;
2027 	case SSHMUX_COMMAND_STDIO_FWD:
2028 		mux_client_request_stdio_fwd(sock);
2029 		exit(0);
2030 	case SSHMUX_COMMAND_STOP:
2031 		mux_client_request_stop_listening(sock);
2032 		fprintf(stderr, "Stop listening request sent.\r\n");
2033 		exit(0);
2034 	default:
2035 		fatal("unrecognised muxclient_command %d", muxclient_command);
2036 	}
2037 }
2038