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