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