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