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