]> andersk Git - openssh.git/blob - mux.c
- djm@cvs.openbsd.org 2010/01/26 02:15:20
[openssh.git] / mux.c
1 /* $OpenBSD: mux.c,v 1.11 2010/01/26 02:15:20 djm Exp $ */
2 /*
3  * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* ssh session multiplexing support */
19
20 /*
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
35 #include <sys/types.h>
36 #include <sys/param.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 #ifdef HAVE_LIBUTIL_H
67 # include <libutil.h>
68 #endif
69
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "log.h"
73 #include "ssh.h"
74 #include "pathnames.h"
75 #include "misc.h"
76 #include "match.h"
77 #include "buffer.h"
78 #include "channels.h"
79 #include "msg.h"
80 #include "packet.h"
81 #include "monitor_fdpass.h"
82 #include "sshpty.h"
83 #include "key.h"
84 #include "readconf.h"
85 #include "clientloop.h"
86
87 /* from ssh.c */
88 extern int tty_flag;
89 extern int force_tty_flag;
90 extern Options options;
91 extern int stdin_null_flag;
92 extern char *host;
93 extern int subsystem_flag;
94 extern Buffer command;
95 extern volatile sig_atomic_t quit_pending;
96 extern char *stdio_forward_host;
97 extern int stdio_forward_port;
98
99 /* Context for session open confirmation callback */
100 struct mux_session_confirm_ctx {
101         u_int want_tty;
102         u_int want_subsys;
103         u_int want_x_fwd;
104         u_int want_agent_fwd;
105         Buffer cmd;
106         char *term;
107         struct termios tio;
108         char **env;
109 };
110
111 /* fd to control socket */
112 int muxserver_sock = -1;
113
114 /* client request id */
115 u_int muxclient_request_id = 0;
116
117 /* Multiplexing control command */
118 u_int muxclient_command = 0;
119
120 /* Set when signalled. */
121 static volatile sig_atomic_t muxclient_terminate = 0;
122
123 /* PID of multiplex server */
124 static u_int muxserver_pid = 0;
125
126 static Channel *mux_listener_channel = NULL;
127
128 struct mux_master_state {
129         int hello_rcvd;
130 };
131
132 /* mux protocol messages */
133 #define MUX_MSG_HELLO           0x00000001
134 #define MUX_C_NEW_SESSION       0x10000002
135 #define MUX_C_ALIVE_CHECK       0x10000004
136 #define MUX_C_TERMINATE         0x10000005
137 #define MUX_C_OPEN_FWD          0x10000006
138 #define MUX_C_CLOSE_FWD         0x10000007
139 #define MUX_C_NEW_STDIO_FWD     0x10000008
140 #define MUX_S_OK                0x80000001
141 #define MUX_S_PERMISSION_DENIED 0x80000002
142 #define MUX_S_FAILURE           0x80000003
143 #define MUX_S_EXIT_MESSAGE      0x80000004
144 #define MUX_S_ALIVE             0x80000005
145 #define MUX_S_SESSION_OPENED    0x80000006
146
147 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
148 #define MUX_FWD_LOCAL   1
149 #define MUX_FWD_REMOTE  2
150 #define MUX_FWD_DYNAMIC 3
151
152 static void mux_session_confirm(int, void *);
153
154 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
155 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
156 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
157 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
158 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
159 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
160 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
161
162 static const struct {
163         u_int type;
164         int (*handler)(u_int, Channel *, Buffer *, Buffer *);
165 } mux_master_handlers[] = {
166         { MUX_MSG_HELLO, process_mux_master_hello },
167         { MUX_C_NEW_SESSION, process_mux_new_session },
168         { MUX_C_ALIVE_CHECK, process_mux_alive_check },
169         { MUX_C_TERMINATE, process_mux_terminate },
170         { MUX_C_OPEN_FWD, process_mux_open_fwd },
171         { MUX_C_CLOSE_FWD, process_mux_close_fwd },
172         { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
173         { 0, NULL }
174 };
175
176 /* Cleanup callback fired on closure of mux slave _session_ channel */
177 /* ARGSUSED */
178 static void
179 mux_master_session_cleanup_cb(int cid, void *unused)
180 {
181         Channel *cc, *c = channel_by_id(cid);
182
183         debug3("%s: entering for channel %d", __func__, cid);
184         if (c == NULL)
185                 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
186         if (c->ctl_chan != -1) {
187                 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
188                         fatal("%s: channel %d missing control channel %d",
189                             __func__, c->self, c->ctl_chan);
190                 c->ctl_chan = -1;
191                 cc->remote_id = -1;
192                 chan_rcvd_oclose(cc);
193         }
194         channel_cancel_cleanup(c->self);
195 }
196
197 /* Cleanup callback fired on closure of mux slave _control_ channel */
198 /* ARGSUSED */
199 static void
200 mux_master_control_cleanup_cb(int cid, void *unused)
201 {
202         Channel *sc, *c = channel_by_id(cid);
203
204         debug3("%s: entering for channel %d", __func__, cid);
205         if (c == NULL)
206                 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
207         if (c->remote_id != -1) {
208                 if ((sc = channel_by_id(c->remote_id)) == NULL)
209                         debug2("%s: channel %d n session channel %d",
210                             __func__, c->self, c->remote_id);
211                 c->remote_id = -1;
212                 sc->ctl_chan = -1;
213                 chan_mark_dead(sc);
214         }
215         channel_cancel_cleanup(c->self);
216 }
217
218 /* Check mux client environment variables before passing them to mux master. */
219 static int
220 env_permitted(char *env)
221 {
222         int i, ret;
223         char name[1024], *cp;
224
225         if ((cp = strchr(env, '=')) == NULL || cp == env)
226                 return 0;
227         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
228         if (ret <= 0 || (size_t)ret >= sizeof(name)) {
229                 error("env_permitted: name '%.100s...' too long", env);
230                 return 0;
231         }
232
233         for (i = 0; i < options.num_send_env; i++)
234                 if (match_pattern(name, options.send_env[i]))
235                         return 1;
236
237         return 0;
238 }
239
240 /* Mux master protocol message handlers */
241
242 static int
243 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
244 {
245         u_int ver;
246         struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
247
248         if (state == NULL)
249                 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
250         if (state->hello_rcvd) {
251                 error("%s: HELLO received twice", __func__);
252                 return -1;
253         }
254         if (buffer_get_int_ret(&ver, m) != 0) {
255  malf:
256                 error("%s: malformed message", __func__);
257                 return -1;
258         }
259         if (ver != SSHMUX_VER) {
260                 error("Unsupported multiplexing protocol version %d "
261                     "(expected %d)", ver, SSHMUX_VER);
262                 return -1;
263         }
264         debug2("%s: channel %d slave version %u", __func__, c->self, ver);
265
266         /* No extensions are presently defined */
267         while (buffer_len(m) > 0) {
268                 char *name = buffer_get_string_ret(m, NULL);
269                 char *value = buffer_get_string_ret(m, NULL);
270
271                 if (name == NULL || value == NULL) {
272                         if (name != NULL)
273                                 xfree(name);
274                         goto malf;
275                 }
276                 debug2("Unrecognised slave extension \"%s\"", name);
277                 xfree(name);
278                 xfree(value);
279         }
280         state->hello_rcvd = 1;
281         return 0;
282 }
283
284 static int
285 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
286 {
287         Channel *nc;
288         struct mux_session_confirm_ctx *cctx;
289         char *reserved, *cmd, *cp;
290         u_int i, j, len, env_len, escape_char, window, packetmax;
291         int new_fd[3];
292
293         /* Reply for SSHMUX_COMMAND_OPEN */
294         cctx = xcalloc(1, sizeof(*cctx));
295         cctx->term = NULL;
296         cmd = reserved = NULL;
297         if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
298             buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
299             buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
300             buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
301             buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
302             buffer_get_int_ret(&escape_char, m) != 0 ||
303             (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
304             (cmd = buffer_get_string_ret(m, &len)) == NULL) {
305  malf:
306                 if (cmd != NULL)
307                         xfree(cmd);
308                 if (reserved != NULL)
309                         xfree(reserved);
310                 if (cctx->term != NULL)
311                         xfree(cctx->term);
312                 error("%s: malformed message", __func__);
313                 return -1;
314         }
315         xfree(reserved);
316         reserved = NULL;
317
318         cctx->env = NULL;
319         env_len = 0;
320         while (buffer_len(m) > 0) {
321 #define MUX_MAX_ENV_VARS        4096
322                 if ((cp = buffer_get_string_ret(m, &len)) == NULL) {
323                         xfree(cmd);
324                         goto malf;
325                 }
326                 if (!env_permitted(cp)) {
327                         xfree(cp);
328                         continue;
329                 }
330                 cctx->env = xrealloc(cctx->env, env_len + 2,
331                     sizeof(*cctx->env));
332                 cctx->env[env_len++] = cp;
333                 cctx->env[env_len] = NULL;
334                 if (env_len > MUX_MAX_ENV_VARS) {
335                         error(">%d environment variables received, ignoring "
336                             "additional", MUX_MAX_ENV_VARS);
337                         break;
338                 }
339         }
340
341         debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
342             "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
343             cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
344             cctx->want_subsys, cctx->term, cmd, env_len);
345
346         buffer_init(&cctx->cmd);
347         buffer_append(&cctx->cmd, cmd, strlen(cmd));
348         xfree(cmd);
349         cmd = NULL;
350
351         /* Gather fds from client */
352         for(i = 0; i < 3; i++) {
353                 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
354                         error("%s: failed to receive fd %d from slave",
355                             __func__, i);
356                         for (j = 0; j < i; j++)
357                                 close(new_fd[j]);
358                         for (j = 0; j < env_len; j++)
359                                 xfree(cctx->env[j]);
360                         if (env_len > 0)
361                                 xfree(cctx->env);
362                         xfree(cctx->term);
363                         buffer_free(&cctx->cmd);
364                         xfree(cctx);
365
366                         /* prepare reply */
367                         buffer_put_int(r, MUX_S_FAILURE);
368                         buffer_put_int(r, rid);
369                         buffer_put_cstring(r,
370                             "did not receive file descriptors");
371                         return -1;
372                 }
373         }
374
375         debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
376             new_fd[0], new_fd[1], new_fd[2]);
377
378         /* XXX support multiple child sessions in future */
379         if (c->remote_id != -1) {
380                 debug2("%s: session already open", __func__);
381                 /* prepare reply */
382                 buffer_put_int(r, MUX_S_FAILURE);
383                 buffer_put_int(r, rid);
384                 buffer_put_cstring(r, "Multiple sessions not supported");
385  cleanup:
386                 close(new_fd[0]);
387                 close(new_fd[1]);
388                 close(new_fd[2]);
389                 xfree(cctx->term);
390                 if (env_len != 0) {
391                         for (i = 0; i < env_len; i++)
392                                 xfree(cctx->env[i]);
393                         xfree(cctx->env);
394                 }
395                 buffer_free(&cctx->cmd);
396                 return 0;
397         }
398
399         if (options.control_master == SSHCTL_MASTER_ASK ||
400             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
401                 if (!ask_permission("Allow shared connection to %s? ", host)) {
402                         debug2("%s: session refused by user", __func__);
403                         /* prepare reply */
404                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
405                         buffer_put_int(r, rid);
406                         buffer_put_cstring(r, "Permission denied");
407                         goto cleanup;
408                 }
409         }
410
411         /* Try to pick up ttymodes from client before it goes raw */
412         if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
413                 error("%s: tcgetattr: %s", __func__, strerror(errno));
414
415         /* enable nonblocking unless tty */
416         if (!isatty(new_fd[0]))
417                 set_nonblock(new_fd[0]);
418         if (!isatty(new_fd[1]))
419                 set_nonblock(new_fd[1]);
420         if (!isatty(new_fd[2]))
421                 set_nonblock(new_fd[2]);
422
423         window = CHAN_SES_WINDOW_DEFAULT;
424         packetmax = CHAN_SES_PACKET_DEFAULT;
425         if (cctx->want_tty) {
426                 window >>= 1;
427                 packetmax >>= 1;
428         }
429
430         nc = channel_new("session", SSH_CHANNEL_OPENING,
431             new_fd[0], new_fd[1], new_fd[2], window, packetmax,
432             CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
433
434         nc->ctl_chan = c->self;         /* link session -> control channel */
435         c->remote_id = nc->self;        /* link control -> session channel */
436
437         if (cctx->want_tty && escape_char != 0xffffffff) {
438                 channel_register_filter(nc->self,
439                     client_simple_escape_filter, NULL,
440                     client_filter_cleanup,
441                     client_new_escape_filter_ctx((int)escape_char));
442         }
443
444         debug2("%s: channel_new: %d linked to control channel %d",
445             __func__, nc->self, nc->ctl_chan);
446
447         channel_send_open(nc->self);
448         channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
449         channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
450
451         /* prepare reply */
452         /* XXX defer until mux_session_confirm() fires */
453         buffer_put_int(r, MUX_S_SESSION_OPENED);
454         buffer_put_int(r, rid);
455         buffer_put_int(r, nc->self);
456
457         return 0;
458 }
459
460 static int
461 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
462 {
463         debug2("%s: channel %d: alive check", __func__, c->self);
464
465         /* prepare reply */
466         buffer_put_int(r, MUX_S_ALIVE);
467         buffer_put_int(r, rid);
468         buffer_put_int(r, (u_int)getpid());
469
470         return 0;
471 }
472
473 static int
474 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
475 {
476         debug2("%s: channel %d: terminate request", __func__, c->self);
477
478         if (options.control_master == SSHCTL_MASTER_ASK ||
479             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
480                 if (!ask_permission("Terminate shared connection to %s? ",
481                     host)) {
482                         debug2("%s: termination refused by user", __func__);
483                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
484                         buffer_put_int(r, rid);
485                         buffer_put_cstring(r, "Permission denied");
486                         return 0;
487                 }
488         }
489
490         quit_pending = 1;
491         buffer_put_int(r, MUX_S_OK);
492         buffer_put_int(r, rid);
493         /* XXX exit happens too soon - message never makes it to client */
494         return 0;
495 }
496
497 static char *
498 format_forward(u_int ftype, Forward *fwd)
499 {
500         char *ret;
501
502         switch (ftype) {
503         case MUX_FWD_LOCAL:
504                 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
505                     (fwd->listen_host == NULL) ?
506                     (options.gateway_ports ? "*" : "LOCALHOST") :
507                     fwd->listen_host, fwd->listen_port,
508                     fwd->connect_host, fwd->connect_port);
509                 break;
510         case MUX_FWD_DYNAMIC:
511                 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
512                     (fwd->listen_host == NULL) ?
513                     (options.gateway_ports ? "*" : "LOCALHOST") :
514                      fwd->listen_host, fwd->listen_port);
515                 break;
516         case MUX_FWD_REMOTE:
517                 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
518                     (fwd->listen_host == NULL) ?
519                     "LOCALHOST" : fwd->listen_host,
520                     fwd->listen_port,
521                     fwd->connect_host, fwd->connect_port);
522                 break;
523         default:
524                 fatal("%s: unknown forward type %u", __func__, ftype);
525         }
526         return ret;
527 }
528
529 static int
530 compare_host(const char *a, const char *b)
531 {
532         if (a == NULL && b == NULL)
533                 return 1;
534         if (a == NULL || b == NULL)
535                 return 0;
536         return strcmp(a, b) == 0;
537 }
538
539 static int
540 compare_forward(Forward *a, Forward *b)
541 {
542         if (!compare_host(a->listen_host, b->listen_host))
543                 return 0;
544         if (a->listen_port != b->listen_port)
545                 return 0;
546         if (!compare_host(a->connect_host, b->connect_host))
547                 return 0;
548         if (a->connect_port != b->connect_port)
549                 return 0;
550
551         return 1;
552 }
553
554 static int
555 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
556 {
557         Forward fwd;
558         char *fwd_desc = NULL;
559         u_int ftype;
560         int i, ret = 0, freefwd = 1;
561
562         fwd.listen_host = fwd.connect_host = NULL;
563         if (buffer_get_int_ret(&ftype, m) != 0 ||
564             (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
565             buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
566             (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
567             buffer_get_int_ret(&fwd.connect_port, m) != 0) {
568                 error("%s: malformed message", __func__);
569                 ret = -1;
570                 goto out;
571         }
572
573         if (*fwd.listen_host == '\0') {
574                 xfree(fwd.listen_host);
575                 fwd.listen_host = NULL;
576         }
577         if (*fwd.connect_host == '\0') {
578                 xfree(fwd.connect_host);
579                 fwd.connect_host = NULL;
580         }
581
582         debug2("%s: channel %d: request %s", __func__, c->self,
583             (fwd_desc = format_forward(ftype, &fwd)));
584
585         if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
586             ftype != MUX_FWD_DYNAMIC) {
587                 logit("%s: invalid forwarding type %u", __func__, ftype);
588  invalid:
589                 xfree(fwd.listen_host);
590                 xfree(fwd.connect_host);
591                 buffer_put_int(r, MUX_S_FAILURE);
592                 buffer_put_int(r, rid);
593                 buffer_put_cstring(r, "Invalid forwarding request");
594                 return 0;
595         }
596         /* XXX support rport0 forwarding with reply of port assigned */
597         if (fwd.listen_port == 0 || fwd.listen_port >= 65536) {
598                 logit("%s: invalid listen port %u", __func__,
599                     fwd.listen_port);
600                 goto invalid;
601         }
602         if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
603             ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
604                 logit("%s: invalid connect port %u", __func__,
605                     fwd.connect_port);
606                 goto invalid;
607         }
608         if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
609                 logit("%s: missing connect host", __func__);
610                 goto invalid;
611         }
612
613         /* Skip forwards that have already been requested */
614         switch (ftype) {
615         case MUX_FWD_LOCAL:
616         case MUX_FWD_DYNAMIC:
617                 for (i = 0; i < options.num_local_forwards; i++) {
618                         if (compare_forward(&fwd,
619                             options.local_forwards + i)) {
620  exists:
621                                 debug2("%s: found existing forwarding",
622                                     __func__);
623                                 buffer_put_int(r, MUX_S_OK);
624                                 buffer_put_int(r, rid);
625                                 goto out;
626                         }
627                 }
628                 break;
629         case MUX_FWD_REMOTE:
630                 for (i = 0; i < options.num_remote_forwards; i++) {
631                         if (compare_forward(&fwd,
632                             options.remote_forwards + i))
633                                 goto exists;
634                 }
635                 break;
636         }
637
638         if (options.control_master == SSHCTL_MASTER_ASK ||
639             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
640                 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
641                         debug2("%s: forwarding refused by user", __func__);
642                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
643                         buffer_put_int(r, rid);
644                         buffer_put_cstring(r, "Permission denied");
645                         goto out;
646                 }
647         }
648
649         if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
650                 if (options.num_local_forwards + 1 >=
651                     SSH_MAX_FORWARDS_PER_DIRECTION ||
652                     channel_setup_local_fwd_listener(fwd.listen_host,
653                     fwd.listen_port, fwd.connect_host, fwd.connect_port,
654                     options.gateway_ports) < 0) {
655  fail:
656                         logit("slave-requested %s failed", fwd_desc);
657                         buffer_put_int(r, MUX_S_FAILURE);
658                         buffer_put_int(r, rid);
659                         buffer_put_cstring(r, "Port forwarding failed");
660                         goto out;
661                 }
662                 add_local_forward(&options, &fwd);
663                 freefwd = 0;
664         } else {
665                 /* XXX wait for remote to confirm */
666                 if (options.num_remote_forwards + 1 >=
667                     SSH_MAX_FORWARDS_PER_DIRECTION ||
668                     channel_request_remote_forwarding(fwd.listen_host,
669                     fwd.listen_port, fwd.connect_host, fwd.connect_port) < 0)
670                         goto fail;
671                 add_remote_forward(&options, &fwd);
672                 freefwd = 0;
673         }
674         buffer_put_int(r, MUX_S_OK);
675         buffer_put_int(r, rid);
676  out:
677         if (fwd_desc != NULL)
678                 xfree(fwd_desc);
679         if (freefwd) {
680                 if (fwd.listen_host != NULL)
681                         xfree(fwd.listen_host);
682                 if (fwd.connect_host != NULL)
683                         xfree(fwd.connect_host);
684         }
685         return ret;
686 }
687
688 static int
689 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
690 {
691         Forward fwd;
692         char *fwd_desc = NULL;
693         u_int ftype;
694         int ret = 0;
695
696         fwd.listen_host = fwd.connect_host = NULL;
697         if (buffer_get_int_ret(&ftype, m) != 0 ||
698             (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
699             buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
700             (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
701             buffer_get_int_ret(&fwd.connect_port, m) != 0) {
702                 error("%s: malformed message", __func__);
703                 ret = -1;
704                 goto out;
705         }
706
707         if (*fwd.listen_host == '\0') {
708                 xfree(fwd.listen_host);
709                 fwd.listen_host = NULL;
710         }
711         if (*fwd.connect_host == '\0') {
712                 xfree(fwd.connect_host);
713                 fwd.connect_host = NULL;
714         }
715
716         debug2("%s: channel %d: request %s", __func__, c->self,
717             (fwd_desc = format_forward(ftype, &fwd)));
718
719         /* XXX implement this */
720         buffer_put_int(r, MUX_S_FAILURE);
721         buffer_put_int(r, rid);
722         buffer_put_cstring(r, "unimplemented");
723
724  out:
725         if (fwd_desc != NULL)
726                 xfree(fwd_desc);
727         if (fwd.listen_host != NULL)
728                 xfree(fwd.listen_host);
729         if (fwd.connect_host != NULL)
730                 xfree(fwd.connect_host);
731
732         return ret;
733 }
734
735 static int
736 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
737 {
738         Channel *nc;
739         char *reserved, *chost;
740         u_int cport, i, j;
741         int new_fd[2];
742
743         chost = reserved = NULL;
744         if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
745            (chost = buffer_get_string_ret(m, NULL)) == NULL ||
746             buffer_get_int_ret(&cport, m) != 0) {
747                 if (reserved != NULL)
748                         xfree(reserved);
749                 if (chost != NULL)
750                         xfree(chost);
751                 error("%s: malformed message", __func__);
752                 return -1;
753         }
754         xfree(reserved);
755
756         debug2("%s: channel %d: request stdio fwd to %s:%u",
757             __func__, c->self, chost, cport);
758
759         /* Gather fds from client */
760         for(i = 0; i < 2; i++) {
761                 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
762                         error("%s: failed to receive fd %d from slave",
763                             __func__, i);
764                         for (j = 0; j < i; j++)
765                                 close(new_fd[j]);
766                         xfree(chost);
767
768                         /* prepare reply */
769                         buffer_put_int(r, MUX_S_FAILURE);
770                         buffer_put_int(r, rid);
771                         buffer_put_cstring(r,
772                             "did not receive file descriptors");
773                         return -1;
774                 }
775         }
776
777         debug3("%s: got fds stdin %d, stdout %d", __func__,
778             new_fd[0], new_fd[1]);
779
780         /* XXX support multiple child sessions in future */
781         if (c->remote_id != -1) {
782                 debug2("%s: session already open", __func__);
783                 /* prepare reply */
784                 buffer_put_int(r, MUX_S_FAILURE);
785                 buffer_put_int(r, rid);
786                 buffer_put_cstring(r, "Multiple sessions not supported");
787  cleanup:
788                 close(new_fd[0]);
789                 close(new_fd[1]);
790                 xfree(chost);
791                 return 0;
792         }
793
794         if (options.control_master == SSHCTL_MASTER_ASK ||
795             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
796                 if (!ask_permission("Allow forward to to %s:%u? ",
797                     chost, cport)) {
798                         debug2("%s: stdio fwd refused by user", __func__);
799                         /* prepare reply */
800                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
801                         buffer_put_int(r, rid);
802                         buffer_put_cstring(r, "Permission denied");
803                         goto cleanup;
804                 }
805         }
806
807         /* enable nonblocking unless tty */
808         if (!isatty(new_fd[0]))
809                 set_nonblock(new_fd[0]);
810         if (!isatty(new_fd[1]))
811                 set_nonblock(new_fd[1]);
812
813         nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
814
815         nc->ctl_chan = c->self;         /* link session -> control channel */
816         c->remote_id = nc->self;        /* link control -> session channel */
817
818         debug2("%s: channel_new: %d linked to control channel %d",
819             __func__, nc->self, nc->ctl_chan);
820
821         channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
822
823         /* prepare reply */
824         /* XXX defer until channel confirmed */
825         buffer_put_int(r, MUX_S_SESSION_OPENED);
826         buffer_put_int(r, rid);
827         buffer_put_int(r, nc->self);
828
829         return 0;
830 }
831
832 /* Channel callbacks fired on read/write from mux slave fd */
833 static int
834 mux_master_read_cb(Channel *c)
835 {
836         struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
837         Buffer in, out;
838         void *ptr;
839         u_int type, rid, have, i;
840         int ret = -1;
841
842         /* Setup ctx and  */
843         if (c->mux_ctx == NULL) {
844                 state = xcalloc(1, sizeof(state));
845                 c->mux_ctx = state;
846                 channel_register_cleanup(c->self,
847                     mux_master_control_cleanup_cb, 0);
848
849                 /* Send hello */
850                 buffer_init(&out);
851                 buffer_put_int(&out, MUX_MSG_HELLO);
852                 buffer_put_int(&out, SSHMUX_VER);
853                 /* no extensions */
854                 buffer_put_string(&c->output, buffer_ptr(&out),
855                     buffer_len(&out));
856                 buffer_free(&out);
857                 debug3("%s: channel %d: hello sent", __func__, c->self);
858                 return 0;
859         }
860
861         buffer_init(&in);
862         buffer_init(&out);
863
864         /* Channel code ensures that we receive whole packets */
865         if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
866  malf:
867                 error("%s: malformed message", __func__);
868                 goto out;
869         }
870         buffer_append(&in, ptr, have);
871
872         if (buffer_get_int_ret(&type, &in) != 0)
873                 goto malf;
874         debug3("%s: channel %d packet type 0x%08x len %u",
875             __func__, c->self, type, buffer_len(&in));
876
877         if (type == MUX_MSG_HELLO)
878                 rid = 0;
879         else {
880                 if (!state->hello_rcvd) {
881                         error("%s: expected MUX_MSG_HELLO(0x%08x), "
882                             "received 0x%08x", __func__, MUX_MSG_HELLO, type);
883                         goto out;
884                 }
885                 if (buffer_get_int_ret(&rid, &in) != 0)
886                         goto malf;
887         }
888
889         for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
890                 if (type == mux_master_handlers[i].type) {
891                         ret = mux_master_handlers[i].handler(rid, c, &in, &out);
892                         break;
893                 }
894         }
895         if (mux_master_handlers[i].handler == NULL) {
896                 error("%s: unsupported mux message 0x%08x", __func__, type);
897                 buffer_put_int(&out, MUX_S_FAILURE);
898                 buffer_put_int(&out, rid);
899                 buffer_put_cstring(&out, "unsupported request");
900                 ret = 0;
901         }
902         /* Enqueue reply packet */
903         if (buffer_len(&out) != 0) {
904                 buffer_put_string(&c->output, buffer_ptr(&out),
905                     buffer_len(&out));
906         }
907  out:
908         buffer_free(&in);
909         buffer_free(&out);
910         return ret;
911 }
912
913 void
914 mux_exit_message(Channel *c, int exitval)
915 {
916         Buffer m;
917         Channel *mux_chan;
918
919         debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
920             exitval);
921
922         if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
923                 fatal("%s: channel %d missing mux channel %d",
924                     __func__, c->self, c->ctl_chan);
925
926         /* Append exit message packet to control socket output queue */
927         buffer_init(&m);
928         buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
929         buffer_put_int(&m, c->self);
930         buffer_put_int(&m, exitval);
931
932         buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
933         buffer_free(&m);
934 }
935
936 /* Prepare a mux master to listen on a Unix domain socket. */
937 void
938 muxserver_listen(void)
939 {
940         struct sockaddr_un addr;
941         socklen_t sun_len;
942         mode_t old_umask;
943
944         if (options.control_path == NULL ||
945             options.control_master == SSHCTL_MASTER_NO)
946                 return;
947
948         debug("setting up multiplex master socket");
949
950         memset(&addr, '\0', sizeof(addr));
951         addr.sun_family = AF_UNIX;
952         sun_len = offsetof(struct sockaddr_un, sun_path) +
953             strlen(options.control_path) + 1;
954
955         if (strlcpy(addr.sun_path, options.control_path,
956             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
957                 fatal("ControlPath too long");
958
959         if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
960                 fatal("%s socket(): %s", __func__, strerror(errno));
961
962         old_umask = umask(0177);
963         if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
964                 muxserver_sock = -1;
965                 if (errno == EINVAL || errno == EADDRINUSE) {
966                         error("ControlSocket %s already exists, "
967                             "disabling multiplexing", options.control_path);
968                         close(muxserver_sock);
969                         muxserver_sock = -1;
970                         xfree(options.control_path);
971                         options.control_path = NULL;
972                         options.control_master = SSHCTL_MASTER_NO;
973                         return;
974                 } else
975                         fatal("%s bind(): %s", __func__, strerror(errno));
976         }
977         umask(old_umask);
978
979         if (listen(muxserver_sock, 64) == -1)
980                 fatal("%s listen(): %s", __func__, strerror(errno));
981
982         set_nonblock(muxserver_sock);
983
984         mux_listener_channel = channel_new("mux listener",
985             SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
986             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
987             0, addr.sun_path, 1);
988         mux_listener_channel->mux_rcb = mux_master_read_cb;
989         debug3("%s: mux listener channel %d fd %d", __func__,
990             mux_listener_channel->self, mux_listener_channel->sock);
991 }
992
993 /* Callback on open confirmation in mux master for a mux client session. */
994 static void
995 mux_session_confirm(int id, void *arg)
996 {
997         struct mux_session_confirm_ctx *cctx = arg;
998         const char *display;
999         Channel *c;
1000         int i;
1001
1002         if (cctx == NULL)
1003                 fatal("%s: cctx == NULL", __func__);
1004         if ((c = channel_by_id(id)) == NULL)
1005                 fatal("%s: no channel for id %d", __func__, id);
1006
1007         display = getenv("DISPLAY");
1008         if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1009                 char *proto, *data;
1010                 /* Get reasonable local authentication information. */
1011                 client_x11_get_proto(display, options.xauth_location,
1012                     options.forward_x11_trusted, &proto, &data);
1013                 /* Request forwarding with authentication spoofing. */
1014                 debug("Requesting X11 forwarding with authentication spoofing.");
1015                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1016                 /* XXX wait for reply */
1017         }
1018
1019         if (cctx->want_agent_fwd && options.forward_agent) {
1020                 debug("Requesting authentication agent forwarding.");
1021                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1022                 packet_send();
1023         }
1024
1025         client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1026             cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1027
1028         c->open_confirm_ctx = NULL;
1029         buffer_free(&cctx->cmd);
1030         xfree(cctx->term);
1031         if (cctx->env != NULL) {
1032                 for (i = 0; cctx->env[i] != NULL; i++)
1033                         xfree(cctx->env[i]);
1034                 xfree(cctx->env);
1035         }
1036         xfree(cctx);
1037 }
1038
1039 /* ** Multiplexing client support */
1040
1041 /* Exit signal handler */
1042 static void
1043 control_client_sighandler(int signo)
1044 {
1045         muxclient_terminate = signo;
1046 }
1047
1048 /*
1049  * Relay signal handler - used to pass some signals from mux client to
1050  * mux master.
1051  */
1052 static void
1053 control_client_sigrelay(int signo)
1054 {
1055         int save_errno = errno;
1056
1057         if (muxserver_pid > 1)
1058                 kill(muxserver_pid, signo);
1059
1060         errno = save_errno;
1061 }
1062
1063 static int
1064 mux_client_read(int fd, Buffer *b, u_int need)
1065 {
1066         u_int have;
1067         ssize_t len;
1068         u_char *p;
1069         struct pollfd pfd;
1070
1071         pfd.fd = fd;
1072         pfd.events = POLLIN;
1073         p = buffer_append_space(b, need);
1074         for (have = 0; have < need; ) {
1075                 if (muxclient_terminate) {
1076                         errno = EINTR;
1077                         return -1;
1078                 }
1079                 len = read(fd, p + have, need - have);
1080                 if (len < 0) {
1081                         switch (errno) {
1082 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1083                         case EWOULDBLOCK:
1084 #endif
1085                         case EAGAIN:
1086                                 (void)poll(&pfd, 1, -1);
1087                                 /* FALLTHROUGH */
1088                         case EINTR:
1089                                 continue;
1090                         default:
1091                                 return -1;
1092                         }
1093                 }
1094                 if (len == 0) {
1095                         errno = EPIPE;
1096                         return -1;
1097                 }
1098                 have += (u_int)len;
1099         }
1100         return 0;
1101 }
1102
1103 static int
1104 mux_client_write_packet(int fd, Buffer *m)
1105 {
1106         Buffer queue;
1107         u_int have, need;
1108         int oerrno, len;
1109         u_char *ptr;
1110         struct pollfd pfd;
1111
1112         pfd.fd = fd;
1113         pfd.events = POLLOUT;
1114         buffer_init(&queue);
1115         buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1116
1117         need = buffer_len(&queue);
1118         ptr = buffer_ptr(&queue);
1119
1120         for (have = 0; have < need; ) {
1121                 if (muxclient_terminate) {
1122                         buffer_free(&queue);
1123                         errno = EINTR;
1124                         return -1;
1125                 }
1126                 len = write(fd, ptr + have, need - have);
1127                 if (len < 0) {
1128                         switch (errno) {
1129 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1130                         case EWOULDBLOCK:
1131 #endif
1132                         case EAGAIN:
1133                                 (void)poll(&pfd, 1, -1);
1134                                 /* FALLTHROUGH */
1135                         case EINTR:
1136                                 continue;
1137                         default:
1138                                 oerrno = errno;
1139                                 buffer_free(&queue);
1140                                 errno = oerrno;
1141                                 return -1;
1142                         }
1143                 }
1144                 if (len == 0) {
1145                         buffer_free(&queue);
1146                         errno = EPIPE;
1147                         return -1;
1148                 }
1149                 have += (u_int)len;
1150         }
1151         buffer_free(&queue);
1152         return 0;
1153 }
1154
1155 static int
1156 mux_client_read_packet(int fd, Buffer *m)
1157 {
1158         Buffer queue;
1159         u_int need, have;
1160         void *ptr;
1161         int oerrno;
1162
1163         buffer_init(&queue);
1164         if (mux_client_read(fd, &queue, 4) != 0) {
1165                 if ((oerrno = errno) == EPIPE)
1166                 debug3("%s: read header failed: %s", __func__, strerror(errno));
1167                 errno = oerrno;
1168                 return -1;
1169         }
1170         need = get_u32(buffer_ptr(&queue));
1171         if (mux_client_read(fd, &queue, need) != 0) {
1172                 oerrno = errno;
1173                 debug3("%s: read body failed: %s", __func__, strerror(errno));
1174                 errno = oerrno;
1175                 return -1;
1176         }
1177         ptr = buffer_get_string_ptr(&queue, &have);
1178         buffer_append(m, ptr, have);
1179         buffer_free(&queue);
1180         return 0;
1181 }
1182
1183 static int
1184 mux_client_hello_exchange(int fd)
1185 {
1186         Buffer m;
1187         u_int type, ver;
1188
1189         buffer_init(&m);
1190         buffer_put_int(&m, MUX_MSG_HELLO);
1191         buffer_put_int(&m, SSHMUX_VER);
1192         /* no extensions */
1193
1194         if (mux_client_write_packet(fd, &m) != 0)
1195                 fatal("%s: write packet: %s", __func__, strerror(errno));
1196
1197         buffer_clear(&m);
1198
1199         /* Read their HELLO */
1200         if (mux_client_read_packet(fd, &m) != 0) {
1201                 buffer_free(&m);
1202                 return -1;
1203         }
1204
1205         type = buffer_get_int(&m);
1206         if (type != MUX_MSG_HELLO)
1207                 fatal("%s: expected HELLO (%u) received %u",
1208                     __func__, MUX_MSG_HELLO, type);
1209         ver = buffer_get_int(&m);
1210         if (ver != SSHMUX_VER)
1211                 fatal("Unsupported multiplexing protocol version %d "
1212                     "(expected %d)", ver, SSHMUX_VER);
1213         debug2("%s: master version %u", __func__, ver);
1214         /* No extensions are presently defined */
1215         while (buffer_len(&m) > 0) {
1216                 char *name = buffer_get_string(&m, NULL);
1217                 char *value = buffer_get_string(&m, NULL);
1218
1219                 debug2("Unrecognised master extension \"%s\"", name);
1220                 xfree(name);
1221                 xfree(value);
1222         }
1223         buffer_free(&m);
1224         return 0;
1225 }
1226
1227 static u_int
1228 mux_client_request_alive(int fd)
1229 {
1230         Buffer m;
1231         char *e;
1232         u_int pid, type, rid;
1233
1234         debug3("%s: entering", __func__);
1235
1236         buffer_init(&m);
1237         buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1238         buffer_put_int(&m, muxclient_request_id);
1239
1240         if (mux_client_write_packet(fd, &m) != 0)
1241                 fatal("%s: write packet: %s", __func__, strerror(errno));
1242
1243         buffer_clear(&m);
1244
1245         /* Read their reply */
1246         if (mux_client_read_packet(fd, &m) != 0) {
1247                 buffer_free(&m);
1248                 return 0;
1249         }
1250
1251         type = buffer_get_int(&m);
1252         if (type != MUX_S_ALIVE) {
1253                 e = buffer_get_string(&m, NULL);
1254                 fatal("%s: master returned error: %s", __func__, e);
1255         }
1256
1257         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1258                 fatal("%s: out of sequence reply: my id %u theirs %u",
1259                     __func__, muxclient_request_id, rid);
1260         pid = buffer_get_int(&m);
1261         buffer_free(&m);
1262
1263         debug3("%s: done pid = %u", __func__, pid);
1264
1265         muxclient_request_id++;
1266
1267         return pid;
1268 }
1269
1270 static void
1271 mux_client_request_terminate(int fd)
1272 {
1273         Buffer m;
1274         char *e;
1275         u_int type, rid;
1276
1277         debug3("%s: entering", __func__);
1278
1279         buffer_init(&m);
1280         buffer_put_int(&m, MUX_C_TERMINATE);
1281         buffer_put_int(&m, muxclient_request_id);
1282
1283         if (mux_client_write_packet(fd, &m) != 0)
1284                 fatal("%s: write packet: %s", __func__, strerror(errno));
1285
1286         buffer_clear(&m);
1287
1288         /* Read their reply */
1289         if (mux_client_read_packet(fd, &m) != 0) {
1290                 /* Remote end exited already */
1291                 if (errno == EPIPE) {
1292                         buffer_free(&m);
1293                         return;
1294                 }
1295                 fatal("%s: read from master failed: %s",
1296                     __func__, strerror(errno));
1297         }
1298
1299         type = buffer_get_int(&m);
1300         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1301                 fatal("%s: out of sequence reply: my id %u theirs %u",
1302                     __func__, muxclient_request_id, rid);
1303         switch (type) {
1304         case MUX_S_OK:
1305                 break;
1306         case MUX_S_PERMISSION_DENIED:
1307                 e = buffer_get_string(&m, NULL);
1308                 fatal("Master refused termination request: %s", e);
1309         case MUX_S_FAILURE:
1310                 e = buffer_get_string(&m, NULL);
1311                 fatal("%s: termination request failed: %s", __func__, e);
1312         default:
1313                 fatal("%s: unexpected response from master 0x%08x",
1314                     __func__, type);
1315         }
1316         buffer_free(&m);
1317         muxclient_request_id++;
1318 }
1319
1320 static int
1321 mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
1322 {
1323         Buffer m;
1324         char *e, *fwd_desc;
1325         u_int type, rid;
1326
1327         fwd_desc = format_forward(ftype, fwd);
1328         debug("Requesting %s", fwd_desc);
1329         xfree(fwd_desc);
1330
1331         buffer_init(&m);
1332         buffer_put_int(&m, MUX_C_OPEN_FWD);
1333         buffer_put_int(&m, muxclient_request_id);
1334         buffer_put_int(&m, ftype);
1335         buffer_put_cstring(&m,
1336             fwd->listen_host == NULL ? "" : fwd->listen_host);
1337         buffer_put_int(&m, fwd->listen_port);
1338         buffer_put_cstring(&m,
1339             fwd->connect_host == NULL ? "" : fwd->connect_host);
1340         buffer_put_int(&m, fwd->connect_port);
1341
1342         if (mux_client_write_packet(fd, &m) != 0)
1343                 fatal("%s: write packet: %s", __func__, strerror(errno));
1344
1345         buffer_clear(&m);
1346
1347         /* Read their reply */
1348         if (mux_client_read_packet(fd, &m) != 0) {
1349                 buffer_free(&m);
1350                 return -1;
1351         }
1352
1353         type = buffer_get_int(&m);
1354         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1355                 fatal("%s: out of sequence reply: my id %u theirs %u",
1356                     __func__, muxclient_request_id, rid);
1357         switch (type) {
1358         case MUX_S_OK:
1359                 break;
1360         case MUX_S_PERMISSION_DENIED:
1361                 e = buffer_get_string(&m, NULL);
1362                 buffer_free(&m);
1363                 error("Master refused forwarding request: %s", e);
1364                 return -1;
1365         case MUX_S_FAILURE:
1366                 e = buffer_get_string(&m, NULL);
1367                 buffer_free(&m);
1368                 error("%s: session request failed: %s", __func__, e);
1369                 return -1;
1370         default:
1371                 fatal("%s: unexpected response from master 0x%08x",
1372                     __func__, type);
1373         }
1374         buffer_free(&m);
1375
1376         muxclient_request_id++;
1377         return 0;
1378 }
1379
1380 static int
1381 mux_client_request_forwards(int fd)
1382 {
1383         int i;
1384
1385         debug3("%s: requesting forwardings: %d local, %d remote", __func__,
1386             options.num_local_forwards, options.num_remote_forwards);
1387
1388         /* XXX ExitOnForwardingFailure */
1389         for (i = 0; i < options.num_local_forwards; i++) {
1390                 if (mux_client_request_forward(fd,
1391                     options.local_forwards[i].connect_port == 0 ?
1392                     MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1393                     options.local_forwards + i) != 0)
1394                         return -1;
1395         }
1396         for (i = 0; i < options.num_remote_forwards; i++) {
1397                 if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
1398                     options.remote_forwards + i) != 0)
1399                         return -1;
1400         }
1401         return 0;
1402 }
1403
1404 static int
1405 mux_client_request_session(int fd)
1406 {
1407         Buffer m;
1408         char *e, *term;
1409         u_int i, rid, sid, esid, exitval, type, exitval_seen;
1410         extern char **environ;
1411         int devnull;
1412
1413         debug3("%s: entering", __func__);
1414
1415         if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1416                 error("%s: master alive request failed", __func__);
1417                 return -1;
1418         }
1419
1420         signal(SIGPIPE, SIG_IGN);
1421
1422         if (stdin_null_flag) {
1423                 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1424                         fatal("open(/dev/null): %s", strerror(errno));
1425                 if (dup2(devnull, STDIN_FILENO) == -1)
1426                         fatal("dup2: %s", strerror(errno));
1427                 if (devnull > STDERR_FILENO)
1428                         close(devnull);
1429         }
1430
1431         term = getenv("TERM");
1432
1433         buffer_init(&m);
1434         buffer_put_int(&m, MUX_C_NEW_SESSION);
1435         buffer_put_int(&m, muxclient_request_id);
1436         buffer_put_cstring(&m, ""); /* reserved */
1437         buffer_put_int(&m, tty_flag);
1438         buffer_put_int(&m, options.forward_x11);
1439         buffer_put_int(&m, options.forward_agent);
1440         buffer_put_int(&m, subsystem_flag);
1441         buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1442             0xffffffff : (u_int)options.escape_char);
1443         buffer_put_cstring(&m, term == NULL ? "" : term);
1444         buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1445
1446         if (options.num_send_env > 0 && environ != NULL) {
1447                 /* Pass environment */
1448                 for (i = 0; environ[i] != NULL; i++) {
1449                         if (env_permitted(environ[i])) {
1450                                 buffer_put_cstring(&m, environ[i]);
1451                         }
1452                 }
1453         }
1454
1455         if (mux_client_write_packet(fd, &m) != 0)
1456                 fatal("%s: write packet: %s", __func__, strerror(errno));
1457
1458         /* Send the stdio file descriptors */
1459         if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1460             mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1461             mm_send_fd(fd, STDERR_FILENO) == -1)
1462                 fatal("%s: send fds failed", __func__);
1463
1464         debug3("%s: session request sent", __func__);
1465
1466         /* Read their reply */
1467         buffer_clear(&m);
1468         if (mux_client_read_packet(fd, &m) != 0) {
1469                 error("%s: read from master failed: %s",
1470                     __func__, strerror(errno));
1471                 buffer_free(&m);
1472                 return -1;
1473         }
1474
1475         type = buffer_get_int(&m);
1476         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1477                 fatal("%s: out of sequence reply: my id %u theirs %u",
1478                     __func__, muxclient_request_id, rid);
1479         switch (type) {
1480         case MUX_S_SESSION_OPENED:
1481                 sid = buffer_get_int(&m);
1482                 debug("%s: master session id: %u", __func__, sid);
1483                 break;
1484         case MUX_S_PERMISSION_DENIED:
1485                 e = buffer_get_string(&m, NULL);
1486                 buffer_free(&m);
1487                 error("Master refused forwarding request: %s", e);
1488                 return -1;
1489         case MUX_S_FAILURE:
1490                 e = buffer_get_string(&m, NULL);
1491                 buffer_free(&m);
1492                 error("%s: forwarding request failed: %s", __func__, e);
1493                 return -1;
1494         default:
1495                 buffer_free(&m);
1496                 error("%s: unexpected response from master 0x%08x",
1497                     __func__, type);
1498                 return -1;
1499         }
1500         muxclient_request_id++;
1501
1502         signal(SIGHUP, control_client_sighandler);
1503         signal(SIGINT, control_client_sighandler);
1504         signal(SIGTERM, control_client_sighandler);
1505         signal(SIGWINCH, control_client_sigrelay);
1506
1507         if (tty_flag)
1508                 enter_raw_mode(force_tty_flag);
1509
1510         /*
1511          * Stick around until the controlee closes the client_fd.
1512          * Before it does, it is expected to write an exit message.
1513          * This process must read the value and wait for the closure of
1514          * the client_fd; if this one closes early, the multiplex master will
1515          * terminate early too (possibly losing data).
1516          */
1517         for (exitval = 255, exitval_seen = 0;;) {
1518                 buffer_clear(&m);
1519                 if (mux_client_read_packet(fd, &m) != 0)
1520                         break;
1521                 type = buffer_get_int(&m);
1522                 if (type != MUX_S_EXIT_MESSAGE) {
1523                         e = buffer_get_string(&m, NULL);
1524                         fatal("%s: master returned error: %s", __func__, e);
1525                 }
1526                 if ((esid = buffer_get_int(&m)) != sid)
1527                         fatal("%s: exit on unknown session: my id %u theirs %u",
1528                             __func__, sid, esid);
1529                 debug("%s: master session id: %u", __func__, sid);
1530                 if (exitval_seen)
1531                         fatal("%s: exitval sent twice", __func__);
1532                 exitval = buffer_get_int(&m);
1533                 exitval_seen = 1;
1534         }
1535
1536         close(fd);
1537         leave_raw_mode(force_tty_flag);
1538
1539         if (muxclient_terminate) {
1540                 debug2("Exiting on signal %d", muxclient_terminate);
1541                 exitval = 255;
1542         } else if (!exitval_seen) {
1543                 debug2("Control master terminated unexpectedly");
1544                 exitval = 255;
1545         } else
1546                 debug2("Received exit status from master %d", exitval);
1547
1548         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1549                 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1550
1551         exit(exitval);
1552 }
1553
1554 static int
1555 mux_client_request_stdio_fwd(int fd)
1556 {
1557         Buffer m;
1558         char *e;
1559         u_int type, rid, sid;
1560         int devnull;
1561
1562         debug3("%s: entering", __func__);
1563
1564         if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1565                 error("%s: master alive request failed", __func__);
1566                 return -1;
1567         }
1568
1569         signal(SIGPIPE, SIG_IGN);
1570
1571         if (stdin_null_flag) {
1572                 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1573                         fatal("open(/dev/null): %s", strerror(errno));
1574                 if (dup2(devnull, STDIN_FILENO) == -1)
1575                         fatal("dup2: %s", strerror(errno));
1576                 if (devnull > STDERR_FILENO)
1577                         close(devnull);
1578         }
1579
1580         buffer_init(&m);
1581         buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1582         buffer_put_int(&m, muxclient_request_id);
1583         buffer_put_cstring(&m, ""); /* reserved */
1584         buffer_put_cstring(&m, stdio_forward_host);
1585         buffer_put_int(&m, stdio_forward_port);
1586
1587         if (mux_client_write_packet(fd, &m) != 0)
1588                 fatal("%s: write packet: %s", __func__, strerror(errno));
1589
1590         /* Send the stdio file descriptors */
1591         if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1592             mm_send_fd(fd, STDOUT_FILENO) == -1)
1593                 fatal("%s: send fds failed", __func__);
1594
1595         debug3("%s: stdio forward request sent", __func__);
1596
1597         /* Read their reply */
1598         buffer_clear(&m);
1599
1600         if (mux_client_read_packet(fd, &m) != 0) {
1601                 error("%s: read from master failed: %s",
1602                     __func__, strerror(errno));
1603                 buffer_free(&m);
1604                 return -1;
1605         }
1606
1607         type = buffer_get_int(&m);
1608         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1609                 fatal("%s: out of sequence reply: my id %u theirs %u",
1610                     __func__, muxclient_request_id, rid);
1611         switch (type) {
1612         case MUX_S_SESSION_OPENED:
1613                 sid = buffer_get_int(&m);
1614                 debug("%s: master session id: %u", __func__, sid);
1615                 break;
1616         case MUX_S_PERMISSION_DENIED:
1617                 e = buffer_get_string(&m, NULL);
1618                 buffer_free(&m);
1619                 fatal("Master refused forwarding request: %s", e);
1620         case MUX_S_FAILURE:
1621                 e = buffer_get_string(&m, NULL);
1622                 buffer_free(&m);
1623                 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1624         default:
1625                 buffer_free(&m);
1626                 error("%s: unexpected response from master 0x%08x",
1627                     __func__, type);
1628                 return -1;
1629         }
1630         muxclient_request_id++;
1631
1632         signal(SIGHUP, control_client_sighandler);
1633         signal(SIGINT, control_client_sighandler);
1634         signal(SIGTERM, control_client_sighandler);
1635         signal(SIGWINCH, control_client_sigrelay);
1636
1637         /*
1638          * Stick around until the controlee closes the client_fd.
1639          */
1640         buffer_clear(&m);
1641         if (mux_client_read_packet(fd, &m) != 0) {
1642                 if (errno == EPIPE ||
1643                     (errno == EINTR && muxclient_terminate != 0))
1644                         return 0;
1645                 fatal("%s: mux_client_read_packet: %s",
1646                     __func__, strerror(errno));
1647         }
1648         fatal("%s: master returned unexpected message %u", __func__, type);
1649 }
1650
1651 /* Multiplex client main loop. */
1652 void
1653 muxclient(const char *path)
1654 {
1655         struct sockaddr_un addr;
1656         socklen_t sun_len;
1657         int sock;
1658         u_int pid;
1659
1660         if (muxclient_command == 0) {
1661                 if (stdio_forward_host != NULL)
1662                         muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1663                 else
1664                         muxclient_command = SSHMUX_COMMAND_OPEN;
1665         }
1666
1667         switch (options.control_master) {
1668         case SSHCTL_MASTER_AUTO:
1669         case SSHCTL_MASTER_AUTO_ASK:
1670                 debug("auto-mux: Trying existing master");
1671                 /* FALLTHROUGH */
1672         case SSHCTL_MASTER_NO:
1673                 break;
1674         default:
1675                 return;
1676         }
1677
1678         memset(&addr, '\0', sizeof(addr));
1679         addr.sun_family = AF_UNIX;
1680         sun_len = offsetof(struct sockaddr_un, sun_path) +
1681             strlen(path) + 1;
1682
1683         if (strlcpy(addr.sun_path, path,
1684             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1685                 fatal("ControlPath too long");
1686
1687         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1688                 fatal("%s socket(): %s", __func__, strerror(errno));
1689
1690         if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
1691                 switch (muxclient_command) {
1692                 case SSHMUX_COMMAND_OPEN:
1693                 case SSHMUX_COMMAND_STDIO_FWD:
1694                         break;
1695                 default:
1696                         fatal("Control socket connect(%.100s): %s", path,
1697                             strerror(errno));
1698                 }
1699                 if (errno == ENOENT)
1700                         debug("Control socket \"%.100s\" does not exist", path);
1701                 else {
1702                         error("Control socket connect(%.100s): %s", path,
1703                             strerror(errno));
1704                 }
1705                 close(sock);
1706                 return;
1707         }
1708         set_nonblock(sock);
1709
1710         if (mux_client_hello_exchange(sock) != 0) {
1711                 error("%s: master hello exchange failed", __func__);
1712                 close(sock);
1713                 return;
1714         }
1715
1716         switch (muxclient_command) {
1717         case SSHMUX_COMMAND_ALIVE_CHECK:
1718                 if ((pid = mux_client_request_alive(sock)) == 0)
1719                         fatal("%s: master alive check failed", __func__);
1720                 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
1721                 exit(0);
1722         case SSHMUX_COMMAND_TERMINATE:
1723                 mux_client_request_terminate(sock);
1724                 fprintf(stderr, "Exit request sent.\r\n");
1725                 exit(0);
1726         case SSHMUX_COMMAND_OPEN:
1727                 if (mux_client_request_forwards(sock) != 0) {
1728                         error("%s: master forward request failed", __func__);
1729                         return;
1730                 }
1731                 mux_client_request_session(sock);
1732                 return;
1733         case SSHMUX_COMMAND_STDIO_FWD:
1734                 mux_client_request_stdio_fwd(sock);
1735                 exit(0);
1736         default:
1737                 fatal("unrecognised muxclient_command %d", muxclient_command);
1738         }
1739 }
This page took 0.648061 seconds and 5 git commands to generate.