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