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