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