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