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