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