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