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