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