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