1 /* $OpenBSD: channels.c,v 1.416 2022/04/11 22:52:08 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
73 #include "openbsd-compat/sys-queue.h"
87 #include "pathnames.h"
90 /* XXX remove once we're satisfied there's no lurking bugs */
91 /* #define DEBUG_CHANNEL_POLL 1 */
93 /* -- agent forwarding */
96 /* -- tcp forwarding */
97 /* special-case port number meaning allow any port */
98 #define FWD_PERMIT_ANY_PORT 0
100 /* special-case wildcard meaning allow any host */
101 #define FWD_PERMIT_ANY_HOST "*"
103 /* -- X11 forwarding */
104 /* Maximum number of fake X11 displays to try. */
105 #define MAX_DISPLAYS 1000
107 /* Per-channel callback for pre/post IO actions */
108 typedef void chan_fn(struct ssh *, Channel *c);
111 * Data structure for storing which hosts are permitted for forward requests.
112 * The local sides of any remote forwards are stored in this array to prevent
113 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
114 * network (which might be behind a firewall).
116 /* XXX: streamlocal wants a path instead of host:port */
117 /* Overload host_to_connect; we could just make this match Forward */
118 /* XXX - can we use listen_host instead of listen_path? */
120 char *host_to_connect; /* Connect to 'host'. */
121 int port_to_connect; /* Connect to 'port'. */
122 char *listen_host; /* Remote side should listen address. */
123 char *listen_path; /* Remote side should listen path. */
124 int listen_port; /* Remote side should listen port. */
125 Channel *downstream; /* Downstream mux*/
129 * Stores the forwarding permission state for a single direction (local or
132 struct permission_set {
134 * List of all local permitted host/port pairs to allow for the
137 u_int num_permitted_user;
138 struct permission *permitted_user;
141 * List of all permitted host/port pairs to allow for the admin.
143 u_int num_permitted_admin;
144 struct permission *permitted_admin;
147 * If this is true, all opens/listens are permitted. This is the
148 * case on the server on which we have to trust the client anyway,
149 * and the user could do anything after logging in.
154 /* Master structure for channels state */
155 struct ssh_channels {
157 * Pointer to an array containing all allocated channels. The array
158 * is dynamically extended as needed.
163 * Size of the channel array. All slots of the array must always be
164 * initialized (at least the type field); unused slots set to NULL
166 u_int channels_alloc;
169 * 'channel_pre*' are called just before IO to add any bits
170 * relevant to channels in the c->io_want bitmasks.
172 * 'channel_post*': perform any appropriate operations for
173 * channels which have c->io_ready events pending.
175 chan_fn **channel_pre;
176 chan_fn **channel_post;
178 /* -- tcp forwarding */
179 struct permission_set local_perms;
180 struct permission_set remote_perms;
182 /* -- X11 forwarding */
184 /* Saved X11 local (client) display. */
185 char *x11_saved_display;
187 /* Saved X11 authentication protocol name. */
188 char *x11_saved_proto;
190 /* Saved X11 authentication data. This is the real data. */
191 char *x11_saved_data;
192 u_int x11_saved_data_len;
194 /* Deadline after which all X11 connections are refused */
195 u_int x11_refuse_time;
198 * Fake X11 authentication data. This is what the server will be
199 * sending us; we should replace any occurrences of this by the
202 u_char *x11_fake_data;
203 u_int x11_fake_data_len;
205 /* AF_UNSPEC or AF_INET or AF_INET6 */
210 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
211 static const char *channel_rfwd_bind_host(const char *listen_host);
213 /* non-blocking connect helpers */
214 static int connect_next(struct channel_connect *);
215 static void channel_connect_ctx_free(struct channel_connect *);
216 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
217 static int rdynamic_connect_finish(struct ssh *, Channel *);
220 static void channel_handler_init(struct ssh_channels *sc);
222 /* -- channel core */
225 channel_init_channels(struct ssh *ssh)
227 struct ssh_channels *sc;
229 if ((sc = calloc(1, sizeof(*sc))) == NULL)
230 fatal_f("allocation failed");
231 sc->channels_alloc = 10;
232 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
233 sc->IPv4or6 = AF_UNSPEC;
234 channel_handler_init(sc);
240 channel_by_id(struct ssh *ssh, int id)
244 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
245 logit_f("%d: bad id", id);
248 c = ssh->chanctxt->channels[id];
250 logit_f("%d: bad id: channel free", id);
257 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
262 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
263 c = ssh->chanctxt->channels[i];
264 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
271 * Returns the channel if it is allowed to receive protocol messages.
272 * Private channels, like listening sockets, may not receive messages.
275 channel_lookup(struct ssh *ssh, int id)
279 if ((c = channel_by_id(ssh, id)) == NULL)
283 case SSH_CHANNEL_X11_OPEN:
284 case SSH_CHANNEL_LARVAL:
285 case SSH_CHANNEL_CONNECTING:
286 case SSH_CHANNEL_DYNAMIC:
287 case SSH_CHANNEL_RDYNAMIC_OPEN:
288 case SSH_CHANNEL_RDYNAMIC_FINISH:
289 case SSH_CHANNEL_OPENING:
290 case SSH_CHANNEL_OPEN:
291 case SSH_CHANNEL_ABANDONED:
292 case SSH_CHANNEL_MUX_PROXY:
295 logit("Non-public channel %d, type %d.", id, c->type);
300 * Register filedescriptors for a channel, used when allocating a channel or
301 * when the channel consumer/producer is ready, e.g. shell exec'd
304 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
305 int extusage, int nonblock, int is_tty)
308 fcntl(rfd, F_SETFD, FD_CLOEXEC);
309 if (wfd != -1 && wfd != rfd)
310 fcntl(wfd, F_SETFD, FD_CLOEXEC);
311 if (efd != -1 && efd != rfd && efd != wfd)
312 fcntl(efd, F_SETFD, FD_CLOEXEC);
316 c->sock = (rfd == wfd) ? rfd : -1;
318 c->extended_usage = extusage;
320 if ((c->isatty = is_tty) != 0)
321 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
323 /* XXX: Later AIX versions can't push as much data to tty */
324 c->wfd_isatty = is_tty || isatty(c->wfd);
327 /* enable nonblocking mode */
328 c->restore_block = 0;
329 if (nonblock == CHANNEL_NONBLOCK_STDIO) {
331 * Special handling for stdio file descriptors: do not set
332 * non-blocking mode if they are TTYs. Otherwise prepare to
333 * restore their blocking state on exit to avoid interfering
334 * with other programs that follow.
336 if (rfd != -1 && !isatty(rfd) && fcntl(rfd, F_GETFL) == 0) {
337 c->restore_block |= CHANNEL_RESTORE_RFD;
340 if (wfd != -1 && !isatty(wfd) && fcntl(wfd, F_GETFL) == 0) {
341 c->restore_block |= CHANNEL_RESTORE_WFD;
344 if (efd != -1 && !isatty(efd) && fcntl(efd, F_GETFL) == 0) {
345 c->restore_block |= CHANNEL_RESTORE_EFD;
348 } else if (nonblock) {
359 * Allocate a new channel object and set its type and socket. This will cause
360 * remote_name to be freed.
363 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
364 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
366 struct ssh_channels *sc = ssh->chanctxt;
371 /* Try to find a free slot where to put the new channel. */
372 for (i = 0; i < sc->channels_alloc; i++) {
373 if (sc->channels[i] == NULL) {
374 /* Found a free slot. */
379 if (i >= sc->channels_alloc) {
381 * There are no free slots. Take last+1 slot and expand
384 found = sc->channels_alloc;
385 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
386 fatal_f("internal error: channels_alloc %d too big",
388 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
389 sc->channels_alloc + 10, sizeof(*sc->channels));
390 sc->channels_alloc += 10;
391 debug2("channel: expanding %d", sc->channels_alloc);
393 /* Initialize and return new channel. */
394 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
395 if ((c->input = sshbuf_new()) == NULL ||
396 (c->output = sshbuf_new()) == NULL ||
397 (c->extended = sshbuf_new()) == NULL)
398 fatal_f("sshbuf_new failed");
399 if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
400 fatal_fr(r, "sshbuf_set_max_size");
401 c->ostate = CHAN_OUTPUT_OPEN;
402 c->istate = CHAN_INPUT_OPEN;
403 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
407 c->local_window = window;
408 c->local_window_max = window;
409 c->local_maxpacket = maxpack;
410 c->remote_name = xstrdup(remote_name);
412 c->delayed = 1; /* prevent call to channel_post handler */
413 TAILQ_INIT(&c->status_confirms);
414 debug("channel %d: new [%s]", found, remote_name);
419 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
426 if ((*fdp == c->rfd && (c->restore_block & CHANNEL_RESTORE_RFD) != 0) ||
427 (*fdp == c->wfd && (c->restore_block & CHANNEL_RESTORE_WFD) != 0) ||
428 (*fdp == c->efd && (c->restore_block & CHANNEL_RESTORE_EFD) != 0))
429 (void)fcntl(*fdp, F_SETFL, 0); /* restore blocking */
431 if (*fdp == c->rfd) {
432 c->io_want &= ~SSH_CHAN_IO_RFD;
433 c->io_ready &= ~SSH_CHAN_IO_RFD;
437 if (*fdp == c->wfd) {
438 c->io_want &= ~SSH_CHAN_IO_WFD;
439 c->io_ready &= ~SSH_CHAN_IO_WFD;
443 if (*fdp == c->efd) {
444 c->io_want &= ~SSH_CHAN_IO_EFD;
445 c->io_ready &= ~SSH_CHAN_IO_EFD;
449 if (*fdp == c->sock) {
450 c->io_want &= ~SSH_CHAN_IO_SOCK;
451 c->io_ready &= ~SSH_CHAN_IO_SOCK;
457 *fdp = -1; /* probably redundant */
461 /* Close all channel fd/socket. */
463 channel_close_fds(struct ssh *ssh, Channel *c)
465 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
467 channel_close_fd(ssh, c, &c->sock);
469 channel_close_fd(ssh, c, &c->rfd);
470 if (wfd != sock && wfd != rfd)
471 channel_close_fd(ssh, c, &c->wfd);
472 if (efd != sock && efd != rfd && efd != wfd)
473 channel_close_fd(ssh, c, &c->efd);
477 fwd_perm_clear(struct permission *perm)
479 free(perm->host_to_connect);
480 free(perm->listen_host);
481 free(perm->listen_path);
482 memset(perm, 0, sizeof(*perm));
485 /* Returns an printable name for the specified forwarding permission list */
487 fwd_ident(int who, int where)
489 if (who == FORWARD_ADM) {
490 if (where == FORWARD_LOCAL)
491 return "admin local";
492 else if (where == FORWARD_REMOTE)
493 return "admin remote";
494 } else if (who == FORWARD_USER) {
495 if (where == FORWARD_LOCAL)
497 else if (where == FORWARD_REMOTE)
498 return "user remote";
500 fatal("Unknown forward permission list %d/%d", who, where);
503 /* Returns the forwarding permission list for the specified direction */
504 static struct permission_set *
505 permission_set_get(struct ssh *ssh, int where)
507 struct ssh_channels *sc = ssh->chanctxt;
511 return &sc->local_perms;
514 return &sc->remote_perms;
517 fatal_f("invalid forwarding direction %d", where);
521 /* Returns pointers to the specified forwarding list and its element count */
523 permission_set_get_array(struct ssh *ssh, int who, int where,
524 struct permission ***permpp, u_int **npermpp)
526 struct permission_set *pset = permission_set_get(ssh, where);
530 *permpp = &pset->permitted_user;
531 *npermpp = &pset->num_permitted_user;
534 *permpp = &pset->permitted_admin;
535 *npermpp = &pset->num_permitted_admin;
538 fatal_f("invalid forwarding client %d", who);
542 /* Adds an entry to the specified forwarding list */
544 permission_set_add(struct ssh *ssh, int who, int where,
545 const char *host_to_connect, int port_to_connect,
546 const char *listen_host, const char *listen_path, int listen_port,
549 struct permission **permp;
552 permission_set_get_array(ssh, who, where, &permp, &npermp);
554 if (*npermp >= INT_MAX)
555 fatal_f("%s overflow", fwd_ident(who, where));
557 *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
559 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
560 (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
561 (*permp)[n].port_to_connect = port_to_connect;
562 (*permp)[n].listen_host = MAYBE_DUP(listen_host);
563 (*permp)[n].listen_path = MAYBE_DUP(listen_path);
564 (*permp)[n].listen_port = listen_port;
565 (*permp)[n].downstream = downstream;
571 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
573 struct ssh_channels *sc = ssh->chanctxt;
574 struct permission_set *pset = &sc->local_perms;
575 struct permission *perm;
579 for (i = 0; i < pset->num_permitted_user; i++) {
580 perm = &pset->permitted_user[i];
581 if (perm->downstream != c)
584 /* cancel on the server, since mux client is gone */
585 debug("channel %d: cleanup remote forward for %s:%u",
586 c->self, perm->listen_host, perm->listen_port);
587 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
588 (r = sshpkt_put_cstring(ssh,
589 "cancel-tcpip-forward")) != 0 ||
590 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
591 (r = sshpkt_put_cstring(ssh,
592 channel_rfwd_bind_host(perm->listen_host))) != 0 ||
593 (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
594 (r = sshpkt_send(ssh)) != 0) {
595 fatal_fr(r, "channel %i", c->self);
597 fwd_perm_clear(perm); /* unregister */
601 /* Free the channel and close its fd/socket. */
603 channel_free(struct ssh *ssh, Channel *c)
605 struct ssh_channels *sc = ssh->chanctxt;
609 struct channel_confirm *cc;
611 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
612 if ((other = sc->channels[i]) == NULL)
615 /* detach from mux client and prepare for closing */
616 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
617 other->type == SSH_CHANNEL_MUX_PROXY &&
618 other->mux_ctx == c) {
619 other->mux_ctx = NULL;
620 other->type = SSH_CHANNEL_OPEN;
621 other->istate = CHAN_INPUT_CLOSED;
622 other->ostate = CHAN_OUTPUT_CLOSED;
625 debug("channel %d: free: %s, nchannels %u", c->self,
626 c->remote_name ? c->remote_name : "???", n);
628 if (c->type == SSH_CHANNEL_MUX_CLIENT) {
629 mux_remove_remote_forwardings(ssh, c);
632 } else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
637 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
638 s = channel_open_message(ssh);
639 debug3("channel %d: status: %s", c->self, s);
643 channel_close_fds(ssh, c);
644 sshbuf_free(c->input);
645 sshbuf_free(c->output);
646 sshbuf_free(c->extended);
647 c->input = c->output = c->extended = NULL;
648 free(c->remote_name);
649 c->remote_name = NULL;
652 free(c->listening_addr);
653 c->listening_addr = NULL;
654 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
655 if (cc->abandon_cb != NULL)
656 cc->abandon_cb(ssh, c, cc->ctx);
657 TAILQ_REMOVE(&c->status_confirms, cc, entry);
658 freezero(cc, sizeof(*cc));
660 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
661 c->filter_cleanup(ssh, c->self, c->filter_ctx);
662 sc->channels[c->self] = NULL;
663 freezero(c, sizeof(*c));
667 channel_free_all(struct ssh *ssh)
670 struct ssh_channels *sc = ssh->chanctxt;
672 for (i = 0; i < sc->channels_alloc; i++)
673 if (sc->channels[i] != NULL)
674 channel_free(ssh, sc->channels[i]);
678 sc->channels_alloc = 0;
680 free(sc->x11_saved_display);
681 sc->x11_saved_display = NULL;
683 free(sc->x11_saved_proto);
684 sc->x11_saved_proto = NULL;
686 free(sc->x11_saved_data);
687 sc->x11_saved_data = NULL;
688 sc->x11_saved_data_len = 0;
690 free(sc->x11_fake_data);
691 sc->x11_fake_data = NULL;
692 sc->x11_fake_data_len = 0;
696 * Closes the sockets/fds of all channels. This is used to close extra file
697 * descriptors after a fork.
700 channel_close_all(struct ssh *ssh)
704 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
705 if (ssh->chanctxt->channels[i] != NULL)
706 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
710 * Stop listening to channels.
713 channel_stop_listening(struct ssh *ssh)
718 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
719 c = ssh->chanctxt->channels[i];
722 case SSH_CHANNEL_AUTH_SOCKET:
723 case SSH_CHANNEL_PORT_LISTENER:
724 case SSH_CHANNEL_RPORT_LISTENER:
725 case SSH_CHANNEL_X11_LISTENER:
726 case SSH_CHANNEL_UNIX_LISTENER:
727 case SSH_CHANNEL_RUNIX_LISTENER:
728 channel_close_fd(ssh, c, &c->sock);
729 channel_free(ssh, c);
737 * Returns true if no channel has too much buffered data, and false if one or
738 * more channel is overfull.
741 channel_not_very_much_buffered_data(struct ssh *ssh)
744 u_int maxsize = ssh_packet_get_maxsize(ssh);
747 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
748 c = ssh->chanctxt->channels[i];
749 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
751 if (sshbuf_len(c->output) > maxsize) {
752 debug2("channel %d: big output buffer %zu > %u",
753 c->self, sshbuf_len(c->output), maxsize);
760 /* Returns true if any channel is still open. */
762 channel_still_open(struct ssh *ssh)
767 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
768 c = ssh->chanctxt->channels[i];
772 case SSH_CHANNEL_X11_LISTENER:
773 case SSH_CHANNEL_PORT_LISTENER:
774 case SSH_CHANNEL_RPORT_LISTENER:
775 case SSH_CHANNEL_MUX_LISTENER:
776 case SSH_CHANNEL_CLOSED:
777 case SSH_CHANNEL_AUTH_SOCKET:
778 case SSH_CHANNEL_DYNAMIC:
779 case SSH_CHANNEL_RDYNAMIC_OPEN:
780 case SSH_CHANNEL_CONNECTING:
781 case SSH_CHANNEL_ZOMBIE:
782 case SSH_CHANNEL_ABANDONED:
783 case SSH_CHANNEL_UNIX_LISTENER:
784 case SSH_CHANNEL_RUNIX_LISTENER:
786 case SSH_CHANNEL_LARVAL:
788 case SSH_CHANNEL_OPENING:
789 case SSH_CHANNEL_OPEN:
790 case SSH_CHANNEL_RDYNAMIC_FINISH:
791 case SSH_CHANNEL_X11_OPEN:
792 case SSH_CHANNEL_MUX_CLIENT:
793 case SSH_CHANNEL_MUX_PROXY:
796 fatal_f("bad channel type %d", c->type);
803 /* Returns the id of an open channel suitable for keepaliving */
805 channel_find_open(struct ssh *ssh)
810 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
811 c = ssh->chanctxt->channels[i];
812 if (c == NULL || !c->have_remote_id)
815 case SSH_CHANNEL_CLOSED:
816 case SSH_CHANNEL_DYNAMIC:
817 case SSH_CHANNEL_RDYNAMIC_OPEN:
818 case SSH_CHANNEL_RDYNAMIC_FINISH:
819 case SSH_CHANNEL_X11_LISTENER:
820 case SSH_CHANNEL_PORT_LISTENER:
821 case SSH_CHANNEL_RPORT_LISTENER:
822 case SSH_CHANNEL_MUX_LISTENER:
823 case SSH_CHANNEL_MUX_CLIENT:
824 case SSH_CHANNEL_MUX_PROXY:
825 case SSH_CHANNEL_OPENING:
826 case SSH_CHANNEL_CONNECTING:
827 case SSH_CHANNEL_ZOMBIE:
828 case SSH_CHANNEL_ABANDONED:
829 case SSH_CHANNEL_UNIX_LISTENER:
830 case SSH_CHANNEL_RUNIX_LISTENER:
832 case SSH_CHANNEL_LARVAL:
833 case SSH_CHANNEL_AUTH_SOCKET:
834 case SSH_CHANNEL_OPEN:
835 case SSH_CHANNEL_X11_OPEN:
838 fatal_f("bad channel type %d", c->type);
845 /* Returns the state of the channel's extended usage flag */
847 channel_format_extended_usage(const Channel *c)
852 switch (c->extended_usage) {
853 case CHAN_EXTENDED_WRITE:
855 case CHAN_EXTENDED_READ:
857 case CHAN_EXTENDED_IGNORE:
865 channel_format_status(const Channel *c)
869 xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
870 "fd %d/%d/%d sock %d cc %d io 0x%02x/0x%02x",
872 c->have_remote_id ? "r" : "nr", c->remote_id,
873 c->istate, sshbuf_len(c->input),
874 c->ostate, sshbuf_len(c->output),
875 channel_format_extended_usage(c), sshbuf_len(c->extended),
876 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan,
877 c->io_want, c->io_ready);
882 * Returns a message describing the currently open forwarded connections,
883 * suitable for sending to the client. The message contains crlf pairs for
887 channel_open_message(struct ssh *ssh)
895 if ((buf = sshbuf_new()) == NULL)
896 fatal_f("sshbuf_new");
897 if ((r = sshbuf_putf(buf,
898 "The following connections are open:\r\n")) != 0)
899 fatal_fr(r, "sshbuf_putf");
900 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
901 c = ssh->chanctxt->channels[i];
905 case SSH_CHANNEL_X11_LISTENER:
906 case SSH_CHANNEL_PORT_LISTENER:
907 case SSH_CHANNEL_RPORT_LISTENER:
908 case SSH_CHANNEL_CLOSED:
909 case SSH_CHANNEL_AUTH_SOCKET:
910 case SSH_CHANNEL_ZOMBIE:
911 case SSH_CHANNEL_ABANDONED:
912 case SSH_CHANNEL_MUX_LISTENER:
913 case SSH_CHANNEL_UNIX_LISTENER:
914 case SSH_CHANNEL_RUNIX_LISTENER:
916 case SSH_CHANNEL_LARVAL:
917 case SSH_CHANNEL_OPENING:
918 case SSH_CHANNEL_CONNECTING:
919 case SSH_CHANNEL_DYNAMIC:
920 case SSH_CHANNEL_RDYNAMIC_OPEN:
921 case SSH_CHANNEL_RDYNAMIC_FINISH:
922 case SSH_CHANNEL_OPEN:
923 case SSH_CHANNEL_X11_OPEN:
924 case SSH_CHANNEL_MUX_PROXY:
925 case SSH_CHANNEL_MUX_CLIENT:
926 cp = channel_format_status(c);
927 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
928 c->self, c->remote_name, cp)) != 0) {
930 fatal_fr(r, "sshbuf_putf");
935 fatal_f("bad channel type %d", c->type);
939 if ((ret = sshbuf_dup_string(buf)) == NULL)
940 fatal_f("sshbuf_dup_string");
946 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
950 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
951 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
952 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
953 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
954 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
955 fatal_r(r, "%s: channel %i: open", where, c->self);
960 channel_send_open(struct ssh *ssh, int id)
962 Channel *c = channel_lookup(ssh, id);
966 logit("channel_send_open: %d: bad id", id);
969 debug2("channel %d: send open", id);
970 open_preamble(ssh, __func__, c, c->ctype);
971 if ((r = sshpkt_send(ssh)) != 0)
972 fatal_fr(r, "channel %i", c->self);
976 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
978 Channel *c = channel_lookup(ssh, id);
982 logit_f("%d: unknown channel id", id);
985 if (!c->have_remote_id)
986 fatal_f("channel %d: no remote id", c->self);
988 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
989 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
990 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
991 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
992 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
993 fatal_fr(r, "channel %i", c->self);
998 channel_register_status_confirm(struct ssh *ssh, int id,
999 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1001 struct channel_confirm *cc;
1004 if ((c = channel_lookup(ssh, id)) == NULL)
1005 fatal_f("%d: bad id", id);
1007 cc = xcalloc(1, sizeof(*cc));
1009 cc->abandon_cb = abandon_cb;
1011 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1015 channel_register_open_confirm(struct ssh *ssh, int id,
1016 channel_open_fn *fn, void *ctx)
1018 Channel *c = channel_lookup(ssh, id);
1021 logit_f("%d: bad id", id);
1024 c->open_confirm = fn;
1025 c->open_confirm_ctx = ctx;
1029 channel_register_cleanup(struct ssh *ssh, int id,
1030 channel_callback_fn *fn, int do_close)
1032 Channel *c = channel_by_id(ssh, id);
1035 logit_f("%d: bad id", id);
1038 c->detach_user = fn;
1039 c->detach_close = do_close;
1043 channel_cancel_cleanup(struct ssh *ssh, int id)
1045 Channel *c = channel_by_id(ssh, id);
1048 logit_f("%d: bad id", id);
1051 c->detach_user = NULL;
1052 c->detach_close = 0;
1056 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1057 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1059 Channel *c = channel_lookup(ssh, id);
1062 logit_f("%d: bad id", id);
1065 c->input_filter = ifn;
1066 c->output_filter = ofn;
1067 c->filter_ctx = ctx;
1068 c->filter_cleanup = cfn;
1072 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1073 int extusage, int nonblock, int is_tty, u_int window_max)
1075 Channel *c = channel_lookup(ssh, id);
1078 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1079 fatal("channel_activate for non-larval channel %d.", id);
1080 if (!c->have_remote_id)
1081 fatal_f("channel %d: no remote id", c->self);
1083 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1084 c->type = SSH_CHANNEL_OPEN;
1085 c->local_window = c->local_window_max = window_max;
1087 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1088 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1089 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1090 (r = sshpkt_send(ssh)) != 0)
1091 fatal_fr(r, "channel %i", c->self);
1095 channel_pre_listener(struct ssh *ssh, Channel *c)
1097 c->io_want = SSH_CHAN_IO_SOCK_R;
1101 channel_pre_connecting(struct ssh *ssh, Channel *c)
1103 debug3("channel %d: waiting for connection", c->self);
1104 c->io_want = SSH_CHAN_IO_SOCK_W;
1108 channel_pre_open(struct ssh *ssh, Channel *c)
1111 if (c->istate == CHAN_INPUT_OPEN &&
1112 c->remote_window > 0 &&
1113 sshbuf_len(c->input) < c->remote_window &&
1114 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1115 c->io_want |= SSH_CHAN_IO_RFD;
1116 if (c->ostate == CHAN_OUTPUT_OPEN ||
1117 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1118 if (sshbuf_len(c->output) > 0) {
1119 c->io_want |= SSH_CHAN_IO_WFD;
1120 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1121 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1122 debug2("channel %d: "
1123 "obuf_empty delayed efd %d/(%zu)", c->self,
1124 c->efd, sshbuf_len(c->extended));
1126 chan_obuf_empty(ssh, c);
1129 /** XXX check close conditions, too */
1130 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1131 c->ostate == CHAN_OUTPUT_CLOSED)) {
1132 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1133 sshbuf_len(c->extended) > 0)
1134 c->io_want |= SSH_CHAN_IO_EFD_W;
1135 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1136 (c->extended_usage == CHAN_EXTENDED_READ ||
1137 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1138 sshbuf_len(c->extended) < c->remote_window)
1139 c->io_want |= SSH_CHAN_IO_EFD_R;
1141 /* XXX: What about efd? races? */
1145 * This is a special state for X11 authentication spoofing. An opened X11
1146 * connection (when authentication spoofing is being done) remains in this
1147 * state until the first packet has been completely read. The authentication
1148 * data in that packet is then substituted by the real data if it matches the
1149 * fake data, and the channel is put into normal mode.
1150 * XXX All this happens at the client side.
1151 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1154 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1156 struct ssh_channels *sc = ssh->chanctxt;
1158 u_int proto_len, data_len;
1160 /* Is this being called after the refusal deadline? */
1161 if (sc->x11_refuse_time != 0 &&
1162 (u_int)monotime() >= sc->x11_refuse_time) {
1163 verbose("Rejected X11 connection after ForwardX11Timeout "
1168 /* Check if the fixed size part of the packet is in buffer. */
1169 if (sshbuf_len(b) < 12)
1172 /* Parse the lengths of variable-length fields. */
1173 ucp = sshbuf_mutable_ptr(b);
1174 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1175 proto_len = 256 * ucp[6] + ucp[7];
1176 data_len = 256 * ucp[8] + ucp[9];
1177 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1178 proto_len = ucp[6] + 256 * ucp[7];
1179 data_len = ucp[8] + 256 * ucp[9];
1181 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1186 /* Check if the whole packet is in buffer. */
1188 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1191 /* Check if authentication protocol matches. */
1192 if (proto_len != strlen(sc->x11_saved_proto) ||
1193 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1194 debug2("X11 connection uses different authentication protocol.");
1197 /* Check if authentication data matches our fake data. */
1198 if (data_len != sc->x11_fake_data_len ||
1199 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1200 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1201 debug2("X11 auth data does not match fake data.");
1204 /* Check fake data length */
1205 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1206 error("X11 fake_data_len %d != saved_data_len %d",
1207 sc->x11_fake_data_len, sc->x11_saved_data_len);
1211 * Received authentication protocol and data match
1212 * our fake data. Substitute the fake data with real
1215 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1216 sc->x11_saved_data, sc->x11_saved_data_len);
1221 channel_pre_x11_open(struct ssh *ssh, Channel *c)
1223 int ret = x11_open_helper(ssh, c->output);
1225 /* c->force_drain = 1; */
1228 c->type = SSH_CHANNEL_OPEN;
1229 channel_pre_open(ssh, c);
1230 } else if (ret == -1) {
1231 logit("X11 connection rejected because of wrong authentication.");
1232 debug2("X11 rejected %d i%d/o%d",
1233 c->self, c->istate, c->ostate);
1234 chan_read_failed(ssh, c);
1235 sshbuf_reset(c->input);
1236 chan_ibuf_empty(ssh, c);
1237 sshbuf_reset(c->output);
1238 chan_write_failed(ssh, c);
1239 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1244 channel_pre_mux_client(struct ssh *ssh, Channel *c)
1247 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1248 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1249 c->io_want |= SSH_CHAN_IO_RFD;
1250 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1251 /* clear buffer immediately (discard any partial packet) */
1252 sshbuf_reset(c->input);
1253 chan_ibuf_empty(ssh, c);
1254 /* Start output drain. XXX just kill chan? */
1255 chan_rcvd_oclose(ssh, c);
1257 if (c->ostate == CHAN_OUTPUT_OPEN ||
1258 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1259 if (sshbuf_len(c->output) > 0)
1260 c->io_want |= SSH_CHAN_IO_WFD;
1261 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1262 chan_obuf_empty(ssh, c);
1266 /* try to decode a socks4 header */
1268 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1272 u_int len, have, i, found, need;
1277 u_int16_t dest_port;
1278 struct in_addr dest_addr;
1282 debug2("channel %d: decode socks4", c->self);
1284 have = sshbuf_len(input);
1285 len = sizeof(s4_req);
1288 p = sshbuf_ptr(input);
1291 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1292 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1293 debug2("channel %d: socks4a request", c->self);
1294 /* ... and needs an extra string (the hostname) */
1297 /* Check for terminating NUL on the string(s) */
1298 for (found = 0, i = len; i < have; i++) {
1305 /* the peer is probably sending garbage */
1306 debug("channel %d: decode socks4: too long",
1313 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1314 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1315 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1316 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1317 debug_r(r, "channels %d: decode socks4", c->self);
1320 have = sshbuf_len(input);
1321 p = sshbuf_ptr(input);
1322 if (memchr(p, '\0', have) == NULL) {
1323 error("channel %d: decode socks4: unterminated user", c->self);
1327 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1328 len++; /* trailing '\0' */
1329 strlcpy(username, p, sizeof(username));
1330 if ((r = sshbuf_consume(input, len)) != 0)
1331 fatal_fr(r, "channel %d: consume", c->self);
1334 if (need == 1) { /* SOCKS4: one string */
1335 host = inet_ntoa(s4_req.dest_addr);
1336 c->path = xstrdup(host);
1337 } else { /* SOCKS4A: two strings */
1338 have = sshbuf_len(input);
1339 p = sshbuf_ptr(input);
1340 if (memchr(p, '\0', have) == NULL) {
1341 error("channel %d: decode socks4a: host not nul "
1342 "terminated", c->self);
1346 debug2("channel %d: decode socks4a: host %s/%d",
1348 len++; /* trailing '\0' */
1349 if (len > NI_MAXHOST) {
1350 error("channel %d: hostname \"%.100s\" too long",
1354 c->path = xstrdup(p);
1355 if ((r = sshbuf_consume(input, len)) != 0)
1356 fatal_fr(r, "channel %d: consume", c->self);
1358 c->host_port = ntohs(s4_req.dest_port);
1360 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1361 c->self, c->path, c->host_port, s4_req.command);
1363 if (s4_req.command != 1) {
1364 debug("channel %d: cannot handle: %s cn %d",
1365 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1368 s4_rsp.version = 0; /* vn: 0 for reply */
1369 s4_rsp.command = 90; /* cd: req granted */
1370 s4_rsp.dest_port = 0; /* ignored */
1371 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1372 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1373 fatal_fr(r, "channel %d: append reply", c->self);
1377 /* try to decode a socks5 header */
1378 #define SSH_SOCKS5_AUTHDONE 0x1000
1379 #define SSH_SOCKS5_NOAUTH 0x00
1380 #define SSH_SOCKS5_IPV4 0x01
1381 #define SSH_SOCKS5_DOMAIN 0x03
1382 #define SSH_SOCKS5_IPV6 0x04
1383 #define SSH_SOCKS5_CONNECT 0x01
1384 #define SSH_SOCKS5_SUCCESS 0x00
1387 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1389 /* XXX use get/put_u8 instead of trusting struct padding */
1396 u_int16_t dest_port;
1397 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1399 u_int have, need, i, found, nmethods, addrlen, af;
1402 debug2("channel %d: decode socks5", c->self);
1403 p = sshbuf_ptr(input);
1406 have = sshbuf_len(input);
1407 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1408 /* format: ver | nmethods | methods */
1412 if (have < nmethods + 2)
1414 /* look for method: "NO AUTHENTICATION REQUIRED" */
1415 for (found = 0, i = 2; i < nmethods + 2; i++) {
1416 if (p[i] == SSH_SOCKS5_NOAUTH) {
1422 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1426 if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1427 fatal_fr(r, "channel %d: consume", c->self);
1428 /* version, method */
1429 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1430 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1431 fatal_fr(r, "channel %d: append reply", c->self);
1432 c->flags |= SSH_SOCKS5_AUTHDONE;
1433 debug2("channel %d: socks5 auth done", c->self);
1434 return 0; /* need more */
1436 debug2("channel %d: socks5 post auth", c->self);
1437 if (have < sizeof(s5_req)+1)
1438 return 0; /* need more */
1439 memcpy(&s5_req, p, sizeof(s5_req));
1440 if (s5_req.version != 0x05 ||
1441 s5_req.command != SSH_SOCKS5_CONNECT ||
1442 s5_req.reserved != 0x00) {
1443 debug2("channel %d: only socks5 connect supported", c->self);
1446 switch (s5_req.atyp){
1447 case SSH_SOCKS5_IPV4:
1451 case SSH_SOCKS5_DOMAIN:
1452 addrlen = p[sizeof(s5_req)];
1455 case SSH_SOCKS5_IPV6:
1460 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1463 need = sizeof(s5_req) + addrlen + 2;
1464 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1468 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1469 fatal_fr(r, "channel %d: consume", c->self);
1470 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1471 /* host string length */
1472 if ((r = sshbuf_consume(input, 1)) != 0)
1473 fatal_fr(r, "channel %d: consume", c->self);
1475 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1476 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1477 debug_r(r, "channel %d: parse addr/port", c->self);
1480 dest_addr[addrlen] = '\0';
1483 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1484 if (addrlen >= NI_MAXHOST) {
1485 error("channel %d: dynamic request: socks5 hostname "
1486 "\"%.100s\" too long", c->self, dest_addr);
1489 c->path = xstrdup(dest_addr);
1491 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1493 c->path = xstrdup(ntop);
1495 c->host_port = ntohs(dest_port);
1497 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1498 c->self, c->path, c->host_port, s5_req.command);
1500 s5_rsp.version = 0x05;
1501 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1502 s5_rsp.reserved = 0; /* ignored */
1503 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1504 dest_port = 0; /* ignored */
1506 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1507 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1508 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1509 fatal_fr(r, "channel %d: append reply", c->self);
1514 channel_connect_stdio_fwd(struct ssh *ssh,
1515 const char *host_to_connect, u_short port_to_connect,
1516 int in, int out, int nonblock)
1520 debug_f("%s:%d", host_to_connect, port_to_connect);
1522 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1523 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1524 0, "stdio-forward", nonblock);
1526 c->path = xstrdup(host_to_connect);
1527 c->host_port = port_to_connect;
1528 c->listening_port = 0;
1531 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1532 port_open_helper(ssh, c, "direct-tcpip");
1537 /* dynamic port forwarding */
1539 channel_pre_dynamic(struct ssh *ssh, Channel *c)
1546 have = sshbuf_len(c->input);
1547 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1548 /* sshbuf_dump(c->input, stderr); */
1549 /* check if the fixed size part of the packet is in buffer. */
1552 c->io_want |= SSH_CHAN_IO_RFD;
1555 /* try to guess the protocol */
1556 p = sshbuf_ptr(c->input);
1557 /* XXX sshbuf_peek_u8? */
1560 ret = channel_decode_socks4(c, c->input, c->output);
1563 ret = channel_decode_socks5(c, c->input, c->output);
1570 chan_mark_dead(ssh, c);
1571 } else if (ret == 0) {
1572 debug2("channel %d: pre_dynamic: need more", c->self);
1574 c->io_want |= SSH_CHAN_IO_RFD;
1575 if (sshbuf_len(c->output))
1576 c->io_want |= SSH_CHAN_IO_WFD;
1578 /* switch to the next state */
1579 c->type = SSH_CHANNEL_OPENING;
1580 port_open_helper(ssh, c, "direct-tcpip");
1584 /* simulate read-error */
1586 rdynamic_close(struct ssh *ssh, Channel *c)
1588 c->type = SSH_CHANNEL_OPEN;
1589 chan_read_failed(ssh, c);
1590 sshbuf_reset(c->input);
1591 chan_ibuf_empty(ssh, c);
1592 sshbuf_reset(c->output);
1593 chan_write_failed(ssh, c);
1596 /* reverse dynamic port forwarding */
1598 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1604 have = sshbuf_len(c->output);
1605 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1606 /* sshbuf_dump(c->output, stderr); */
1608 if (c->flags & CHAN_EOF_RCVD) {
1609 if ((r = sshbuf_consume(c->output, have)) != 0)
1610 fatal_fr(r, "channel %d: consume", c->self);
1611 rdynamic_close(ssh, c);
1614 /* check if the fixed size part of the packet is in buffer. */
1617 /* try to guess the protocol */
1618 p = sshbuf_ptr(c->output);
1621 /* switch input/output for reverse forwarding */
1622 ret = channel_decode_socks4(c, c->output, c->input);
1625 ret = channel_decode_socks5(c, c->output, c->input);
1632 rdynamic_close(ssh, c);
1633 } else if (ret == 0) {
1634 debug2("channel %d: pre_rdynamic: need more", c->self);
1635 /* send socks request to peer */
1636 len = sshbuf_len(c->input);
1637 if (len > 0 && len < c->remote_window) {
1638 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1639 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1640 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1641 (r = sshpkt_send(ssh)) != 0) {
1642 fatal_fr(r, "channel %i: rdynamic", c->self);
1644 if ((r = sshbuf_consume(c->input, len)) != 0)
1645 fatal_fr(r, "channel %d: consume", c->self);
1646 c->remote_window -= len;
1648 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1649 /* the connect failed */
1650 rdynamic_close(ssh, c);
1654 /* This is our fake X11 server socket. */
1656 channel_post_x11_listener(struct ssh *ssh, Channel *c)
1659 struct sockaddr_storage addr;
1660 int r, newsock, oerrno, remote_port;
1662 char buf[16384], *remote_ipaddr;
1664 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1667 debug("X11 connection requested.");
1668 addrlen = sizeof(addr);
1669 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1670 if (c->single_connection) {
1672 debug2("single_connection: closing X11 listener.");
1673 channel_close_fd(ssh, c, &c->sock);
1674 chan_mark_dead(ssh, c);
1677 if (newsock == -1) {
1678 if (errno != EINTR && errno != EWOULDBLOCK &&
1679 errno != ECONNABORTED)
1680 error("accept: %.100s", strerror(errno));
1681 if (errno == EMFILE || errno == ENFILE)
1682 c->notbefore = monotime() + 1;
1685 set_nodelay(newsock);
1686 remote_ipaddr = get_peer_ipaddr(newsock);
1687 remote_port = get_peer_port(newsock);
1688 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1689 remote_ipaddr, remote_port);
1691 nc = channel_new(ssh, "accepted x11 socket",
1692 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1693 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1694 open_preamble(ssh, __func__, nc, "x11");
1695 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1696 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1697 fatal_fr(r, "channel %i: reply", c->self);
1699 if ((r = sshpkt_send(ssh)) != 0)
1700 fatal_fr(r, "channel %i: send", c->self);
1701 free(remote_ipaddr);
1705 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1707 char *local_ipaddr = get_local_ipaddr(c->sock);
1708 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1709 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1710 int remote_port = get_peer_port(c->sock);
1713 if (remote_port == -1) {
1714 /* Fake addr/port to appease peers that validate it (Tectia) */
1715 free(remote_ipaddr);
1716 remote_ipaddr = xstrdup("127.0.0.1");
1717 remote_port = 65535;
1720 free(c->remote_name);
1721 xasprintf(&c->remote_name,
1722 "%s: listening port %d for %.100s port %d, "
1723 "connect from %.200s port %d to %.100s port %d",
1724 rtype, c->listening_port, c->path, c->host_port,
1725 remote_ipaddr, remote_port, local_ipaddr, local_port);
1727 open_preamble(ssh, __func__, c, rtype);
1728 if (strcmp(rtype, "direct-tcpip") == 0) {
1729 /* target host, port */
1730 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1731 (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1732 fatal_fr(r, "channel %i: reply", c->self);
1733 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1735 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1736 fatal_fr(r, "channel %i: reply", c->self);
1737 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1739 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1740 fatal_fr(r, "channel %i: reply", c->self);
1742 /* listen address, port */
1743 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1744 (r = sshpkt_put_u32(ssh, local_port)) != 0)
1745 fatal_fr(r, "channel %i: reply", c->self);
1747 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1748 /* reserved for future owner/mode info */
1749 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1750 fatal_fr(r, "channel %i: reply", c->self);
1752 /* originator host and port */
1753 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1754 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1755 fatal_fr(r, "channel %i: reply", c->self);
1757 if ((r = sshpkt_send(ssh)) != 0)
1758 fatal_fr(r, "channel %i: send", c->self);
1759 free(remote_ipaddr);
1764 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1766 ssh->chanctxt->x11_refuse_time = refuse_time;
1770 * This socket is listening for connections to a forwarded TCP/IP port.
1773 channel_post_port_listener(struct ssh *ssh, Channel *c)
1776 struct sockaddr_storage addr;
1777 int newsock, nextstate;
1781 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1784 debug("Connection to port %d forwarding to %.100s port %d requested.",
1785 c->listening_port, c->path, c->host_port);
1787 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1788 nextstate = SSH_CHANNEL_OPENING;
1789 rtype = "forwarded-tcpip";
1790 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1791 nextstate = SSH_CHANNEL_OPENING;
1792 rtype = "forwarded-streamlocal@openssh.com";
1793 } else if (c->host_port == PORT_STREAMLOCAL) {
1794 nextstate = SSH_CHANNEL_OPENING;
1795 rtype = "direct-streamlocal@openssh.com";
1796 } else if (c->host_port == 0) {
1797 nextstate = SSH_CHANNEL_DYNAMIC;
1798 rtype = "dynamic-tcpip";
1800 nextstate = SSH_CHANNEL_OPENING;
1801 rtype = "direct-tcpip";
1804 addrlen = sizeof(addr);
1805 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1806 if (newsock == -1) {
1807 if (errno != EINTR && errno != EWOULDBLOCK &&
1808 errno != ECONNABORTED)
1809 error("accept: %.100s", strerror(errno));
1810 if (errno == EMFILE || errno == ENFILE)
1811 c->notbefore = monotime() + 1;
1814 if (c->host_port != PORT_STREAMLOCAL)
1815 set_nodelay(newsock);
1816 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1817 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1818 nc->listening_port = c->listening_port;
1819 nc->host_port = c->host_port;
1820 if (c->path != NULL)
1821 nc->path = xstrdup(c->path);
1823 if (nextstate != SSH_CHANNEL_DYNAMIC)
1824 port_open_helper(ssh, nc, rtype);
1828 * This is the authentication agent socket listening for connections from
1832 channel_post_auth_listener(struct ssh *ssh, Channel *c)
1836 struct sockaddr_storage addr;
1839 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1842 addrlen = sizeof(addr);
1843 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1844 if (newsock == -1) {
1845 error("accept from auth socket: %.100s", strerror(errno));
1846 if (errno == EMFILE || errno == ENFILE)
1847 c->notbefore = monotime() + 1;
1850 nc = channel_new(ssh, "accepted auth socket",
1851 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1852 c->local_window_max, c->local_maxpacket,
1853 0, "accepted auth socket", 1);
1854 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1855 if ((r = sshpkt_send(ssh)) != 0)
1856 fatal_fr(r, "channel %i", c->self);
1860 channel_post_connecting(struct ssh *ssh, Channel *c)
1862 int err = 0, sock, isopen, r;
1863 socklen_t sz = sizeof(err);
1865 if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
1867 if (!c->have_remote_id)
1868 fatal_f("channel %d: no remote id", c->self);
1869 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1870 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1871 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1873 error("getsockopt SO_ERROR failed");
1876 debug("channel %d: connected to %s port %d",
1877 c->self, c->connect_ctx.host, c->connect_ctx.port);
1878 channel_connect_ctx_free(&c->connect_ctx);
1879 c->type = SSH_CHANNEL_OPEN;
1881 /* no message necessary */
1883 if ((r = sshpkt_start(ssh,
1884 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1885 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1886 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1887 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1888 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1889 (r = sshpkt_send(ssh)) != 0)
1890 fatal_fr(r, "channel %i open confirm", c->self);
1893 debug("channel %d: connection failed: %s",
1894 c->self, strerror(err));
1895 /* Try next address, if any */
1896 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1898 c->sock = c->rfd = c->wfd = sock;
1901 /* Exhausted all addresses */
1902 error("connect_to %.100s port %d: failed.",
1903 c->connect_ctx.host, c->connect_ctx.port);
1904 channel_connect_ctx_free(&c->connect_ctx);
1906 rdynamic_close(ssh, c);
1908 if ((r = sshpkt_start(ssh,
1909 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1910 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1911 (r = sshpkt_put_u32(ssh,
1912 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1913 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1914 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1915 (r = sshpkt_send(ssh)) != 0)
1916 fatal_fr(r, "channel %i: failure", c->self);
1917 chan_mark_dead(ssh, c);
1923 channel_handle_rfd(struct ssh *ssh, Channel *c)
1925 char buf[CHAN_RBUF];
1928 size_t have, avail, maxlen = CHANNEL_MAX_READ;
1929 int pty_zeroread = 0;
1932 /* Bug on AIX: read(1) can return 0 for a non-closed fd */
1933 pty_zeroread = c->isatty;
1936 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1938 if (!force && (c->io_ready & SSH_CHAN_IO_RFD) == 0)
1940 if ((avail = sshbuf_avail(c->input)) == 0)
1941 return 1; /* Shouldn't happen */
1944 * For "simple" channels (i.e. not datagram or filtered), we can
1945 * read directly to the channel buffer.
1947 if (!pty_zeroread && c->input_filter == NULL && !c->datagram) {
1948 /* Only OPEN channels have valid rwin */
1949 if (c->type == SSH_CHANNEL_OPEN) {
1950 if ((have = sshbuf_len(c->input)) >= c->remote_window)
1951 return 1; /* shouldn't happen */
1952 if (maxlen > c->remote_window - have)
1953 maxlen = c->remote_window - have;
1957 if ((r = sshbuf_read(c->rfd, c->input, maxlen, NULL)) != 0) {
1958 if (errno == EINTR || (!force &&
1959 (errno == EAGAIN || errno == EWOULDBLOCK)))
1961 debug2("channel %d: read failed rfd %d maxlen %zu: %s",
1962 c->self, c->rfd, maxlen, ssh_err(r));
1969 len = read(c->rfd, buf, sizeof(buf));
1970 /* fixup AIX zero-length read with errno set to look more like errors */
1971 if (pty_zeroread && len == 0 && errno != 0)
1973 if (len == -1 && (errno == EINTR ||
1974 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1976 if (len < 0 || (!pty_zeroread && len == 0)) {
1977 debug2("channel %d: read<=0 rfd %d len %zd: %s",
1978 c->self, c->rfd, len,
1979 len == 0 ? "closed" : strerror(errno));
1981 if (c->type != SSH_CHANNEL_OPEN) {
1982 debug2("channel %d: not open", c->self);
1983 chan_mark_dead(ssh, c);
1986 chan_read_failed(ssh, c);
1990 if (c->input_filter != NULL) {
1991 if (c->input_filter(ssh, c, buf, len) == -1) {
1992 debug2("channel %d: filter stops", c->self);
1993 chan_read_failed(ssh, c);
1995 } else if (c->datagram) {
1996 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1997 fatal_fr(r, "channel %i: put datagram", c->self);
1998 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
1999 fatal_fr(r, "channel %i: put data", c->self);
2005 channel_handle_wfd(struct ssh *ssh, Channel *c)
2008 u_char *data = NULL, *buf; /* XXX const; need filter API change */
2009 size_t dlen, olen = 0;
2012 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2014 if (sshbuf_len(c->output) == 0)
2017 /* Send buffered output data to the socket. */
2018 olen = sshbuf_len(c->output);
2019 if (c->output_filter != NULL) {
2020 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2021 debug2("channel %d: filter stops", c->self);
2022 if (c->type != SSH_CHANNEL_OPEN)
2023 chan_mark_dead(ssh, c);
2025 chan_write_failed(ssh, c);
2028 } else if (c->datagram) {
2029 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2030 fatal_fr(r, "channel %i: get datagram", c->self);
2033 buf = data = sshbuf_mutable_ptr(c->output);
2034 dlen = sshbuf_len(c->output);
2038 /* ignore truncated writes, datagrams might get lost */
2039 len = write(c->wfd, buf, dlen);
2041 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2042 errno == EWOULDBLOCK))
2050 /* XXX: Later AIX versions can't push as much data to tty */
2052 dlen = MINIMUM(dlen, 8*1024);
2055 len = write(c->wfd, buf, dlen);
2057 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2061 if (c->type != SSH_CHANNEL_OPEN) {
2062 debug2("channel %d: not open", c->self);
2063 chan_mark_dead(ssh, c);
2066 chan_write_failed(ssh, c);
2070 #ifndef BROKEN_TCGETATTR_ICANON
2071 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2072 if (tcgetattr(c->wfd, &tio) == 0 &&
2073 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2075 * Simulate echo to reduce the impact of
2076 * traffic analysis. We need to match the
2077 * size of a SSH2_MSG_CHANNEL_DATA message
2078 * (4 byte channel id + buf)
2080 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2081 (r = sshpkt_send(ssh)) != 0)
2082 fatal_fr(r, "channel %i: ignore", c->self);
2085 #endif /* BROKEN_TCGETATTR_ICANON */
2086 if ((r = sshbuf_consume(c->output, len)) != 0)
2087 fatal_fr(r, "channel %i: consume", c->self);
2089 c->local_consumed += olen - sshbuf_len(c->output);
2095 channel_handle_efd_write(struct ssh *ssh, Channel *c)
2100 if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2102 if (sshbuf_len(c->extended) == 0)
2105 len = write(c->efd, sshbuf_ptr(c->extended),
2106 sshbuf_len(c->extended));
2107 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2108 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2109 errno == EWOULDBLOCK))
2112 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2113 channel_close_fd(ssh, c, &c->efd);
2115 if ((r = sshbuf_consume(c->extended, len)) != 0)
2116 fatal_fr(r, "channel %i: consume", c->self);
2117 c->local_consumed += len;
2123 channel_handle_efd_read(struct ssh *ssh, Channel *c)
2125 char buf[CHAN_RBUF];
2129 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2131 if (!force && (c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2134 len = read(c->efd, buf, sizeof(buf));
2135 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2136 if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2137 errno == EWOULDBLOCK) && !force)))
2140 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2141 channel_close_fd(ssh, c, &c->efd);
2142 } else if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2143 debug3("channel %d: discard efd", c->self);
2144 else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2145 fatal_fr(r, "channel %i: append", c->self);
2150 channel_handle_efd(struct ssh *ssh, Channel *c)
2155 /** XXX handle drain efd, too */
2157 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2158 return channel_handle_efd_write(ssh, c);
2159 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2160 c->extended_usage == CHAN_EXTENDED_IGNORE)
2161 return channel_handle_efd_read(ssh, c);
2167 channel_check_window(struct ssh *ssh, Channel *c)
2171 if (c->type == SSH_CHANNEL_OPEN &&
2172 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2173 ((c->local_window_max - c->local_window >
2174 c->local_maxpacket*3) ||
2175 c->local_window < c->local_window_max/2) &&
2176 c->local_consumed > 0) {
2177 if (!c->have_remote_id)
2178 fatal_f("channel %d: no remote id", c->self);
2179 if ((r = sshpkt_start(ssh,
2180 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2181 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2182 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2183 (r = sshpkt_send(ssh)) != 0) {
2184 fatal_fr(r, "channel %i", c->self);
2186 debug2("channel %d: window %d sent adjust %d", c->self,
2187 c->local_window, c->local_consumed);
2188 c->local_window += c->local_consumed;
2189 c->local_consumed = 0;
2195 channel_post_open(struct ssh *ssh, Channel *c)
2197 channel_handle_rfd(ssh, c);
2198 channel_handle_wfd(ssh, c);
2199 channel_handle_efd(ssh, c);
2200 channel_check_window(ssh, c);
2204 read_mux(struct ssh *ssh, Channel *c, u_int need)
2206 char buf[CHAN_RBUF];
2211 if (sshbuf_len(c->input) < need) {
2212 rlen = need - sshbuf_len(c->input);
2213 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2214 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2215 return sshbuf_len(c->input);
2217 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2218 c->self, c->rfd, len);
2219 chan_read_failed(ssh, c);
2221 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2222 fatal_fr(r, "channel %i: append", c->self);
2224 return sshbuf_len(c->input);
2228 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2232 if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2234 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2240 * Don't not read past the precise end of packets to
2241 * avoid disrupting fd passing.
2243 if (read_mux(ssh, c, 4) < 4) /* read header */
2245 /* XXX sshbuf_peek_u32 */
2246 need = PEEK_U32(sshbuf_ptr(c->input));
2247 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2248 if (need > CHANNEL_MUX_MAX_PACKET) {
2249 debug2("channel %d: packet too big %u > %u",
2250 c->self, CHANNEL_MUX_MAX_PACKET, need);
2251 chan_rcvd_oclose(ssh, c);
2254 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2256 if (c->mux_rcb(ssh, c) != 0) {
2257 debug("channel %d: mux_rcb failed", c->self);
2258 chan_mark_dead(ssh, c);
2264 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2269 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2271 if (sshbuf_len(c->output) == 0)
2274 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2275 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2278 chan_mark_dead(ssh, c);
2281 if ((r = sshbuf_consume(c->output, len)) != 0)
2282 fatal_fr(r, "channel %i: consume", c->self);
2286 channel_post_mux_client(struct ssh *ssh, Channel *c)
2288 channel_post_mux_client_read(ssh, c);
2289 channel_post_mux_client_write(ssh, c);
2293 channel_post_mux_listener(struct ssh *ssh, Channel *c)
2296 struct sockaddr_storage addr;
2302 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2305 debug("multiplexing control connection");
2308 * Accept connection on control socket
2310 memset(&addr, 0, sizeof(addr));
2311 addrlen = sizeof(addr);
2312 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2314 error_f("accept: %s", strerror(errno));
2315 if (errno == EMFILE || errno == ENFILE)
2316 c->notbefore = monotime() + 1;
2320 if (getpeereid(newsock, &euid, &egid) == -1) {
2321 error_f("getpeereid failed: %s", strerror(errno));
2325 if ((euid != 0) && (getuid() != euid)) {
2326 error("multiplex uid mismatch: peer euid %u != uid %u",
2327 (u_int)euid, (u_int)getuid());
2331 nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2332 newsock, newsock, -1, c->local_window_max,
2333 c->local_maxpacket, 0, "mux-control", 1);
2334 nc->mux_rcb = c->mux_rcb;
2335 debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2336 /* establish state */
2337 nc->mux_rcb(ssh, nc);
2338 /* mux state transitions must not elicit protocol messages */
2339 nc->flags |= CHAN_LOCAL;
2343 channel_handler_init(struct ssh_channels *sc)
2345 chan_fn **pre, **post;
2347 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2348 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2349 fatal_f("allocation failed");
2351 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2352 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2353 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2354 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2355 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2356 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2357 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2358 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2359 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2360 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2361 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2362 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2363 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2365 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2366 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2367 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2368 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2369 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2370 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2371 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2372 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2373 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2374 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2375 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2376 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2378 sc->channel_pre = pre;
2379 sc->channel_post = post;
2382 /* gc dead channels */
2384 channel_garbage_collect(struct ssh *ssh, Channel *c)
2388 if (c->detach_user != NULL) {
2389 if (!chan_is_dead(ssh, c, c->detach_close))
2392 debug2("channel %d: gc: notify user", c->self);
2393 c->detach_user(ssh, c->self, NULL);
2394 /* if we still have a callback */
2395 if (c->detach_user != NULL)
2397 debug2("channel %d: gc: user detached", c->self);
2399 if (!chan_is_dead(ssh, c, 1))
2401 debug2("channel %d: garbage collecting", c->self);
2402 channel_free(ssh, c);
2405 enum channel_table { CHAN_PRE, CHAN_POST };
2408 channel_handler(struct ssh *ssh, int table, time_t *unpause_secs)
2410 struct ssh_channels *sc = ssh->chanctxt;
2411 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2417 if (unpause_secs != NULL)
2419 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2420 c = sc->channels[i];
2424 if (table == CHAN_PRE)
2429 if (ftab[c->type] != NULL) {
2431 * Run handlers that are not paused.
2433 if (c->notbefore <= now)
2434 (*ftab[c->type])(ssh, c);
2435 else if (unpause_secs != NULL) {
2437 * Collect the time that the earliest
2438 * channel comes off pause.
2440 debug3_f("chan %d: skip for %d more "
2442 (int)(c->notbefore - now));
2443 if (*unpause_secs == 0 ||
2444 (c->notbefore - now) < *unpause_secs)
2445 *unpause_secs = c->notbefore - now;
2448 channel_garbage_collect(ssh, c);
2450 if (unpause_secs != NULL && *unpause_secs != 0)
2451 debug3_f("first channel unpauses in %d seconds",
2452 (int)*unpause_secs);
2456 * Create sockets before preparing IO.
2457 * This is necessary for things that need to happen after reading
2458 * the network-input but need to be completed before IO event setup, e.g.
2459 * because they may create new channels.
2462 channel_before_prepare_io(struct ssh *ssh)
2464 struct ssh_channels *sc = ssh->chanctxt;
2468 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2469 c = sc->channels[i];
2472 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2473 channel_before_prepare_io_rdynamic(ssh, c);
2478 dump_channel_poll(const char *func, const char *what, Channel *c,
2479 u_int pollfd_offset, struct pollfd *pfd)
2481 #ifdef DEBUG_CHANNEL_POLL
2482 debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2483 "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2484 "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2485 c->rfd, c->wfd, c->efd, c->sock,
2486 c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2487 c->io_want, c->io_ready,
2488 pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2492 /* Prepare pollfd entries for a single channel */
2494 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2495 struct pollfd *pfd, u_int npfd)
2497 u_int ev, p = *next_pollfd;
2502 /* Shouldn't happen */
2503 fatal_f("channel %d: bad pfd offset %u (max %u)",
2506 c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2510 * This is a special case, since c->rfd might be the same as
2511 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2516 if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2519 if (c->wfd == c->rfd) {
2520 if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2524 if (c->efd == c->rfd) {
2525 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2527 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2531 if (c->sock == c->rfd) {
2532 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2534 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2537 /* Pack a pfd entry if any event armed for this fd */
2542 dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2546 /* prepare c->wfd if wanting IO and not already handled above */
2547 if (c->wfd != -1 && c->rfd != c->wfd) {
2549 if ((c->io_want & SSH_CHAN_IO_WFD))
2551 /* Pack a pfd entry if any event armed for this fd */
2556 dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2560 /* prepare c->efd if wanting IO and not already handled above */
2561 if (c->efd != -1 && c->rfd != c->efd) {
2563 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2565 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2567 /* Pack a pfd entry if any event armed for this fd */
2572 dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2576 /* prepare c->sock if wanting IO and not already handled above */
2577 if (c->sock != -1 && c->rfd != c->sock) {
2579 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2581 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2583 /* Pack a pfd entry if any event armed for this fd */
2586 pfd[p].fd = c->sock;
2588 dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2595 /* * Allocate/prepare poll structure */
2597 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2598 u_int *npfd_activep, u_int npfd_reserved, time_t *minwait_secs)
2600 struct ssh_channels *sc = ssh->chanctxt;
2601 u_int i, oalloc, p, npfd = npfd_reserved;
2603 channel_before_prepare_io(ssh); /* might create a new channel */
2604 /* clear out I/O flags from last poll */
2605 for (i = 0; i < sc->channels_alloc; i++) {
2606 if (sc->channels[i] == NULL)
2608 sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2610 /* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2611 if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2612 fatal_f("too many channels"); /* shouldn't happen */
2613 if (!ssh_packet_is_rekeying(ssh))
2614 npfd += sc->channels_alloc * 4;
2615 if (npfd > *npfd_allocp) {
2616 *pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2617 npfd, sizeof(**pfdp));
2618 *npfd_allocp = npfd;
2620 *npfd_activep = npfd_reserved;
2621 if (ssh_packet_is_rekeying(ssh))
2624 oalloc = sc->channels_alloc;
2626 channel_handler(ssh, CHAN_PRE, minwait_secs);
2628 if (oalloc != sc->channels_alloc) {
2629 /* shouldn't happen */
2630 fatal_f("channels_alloc changed during CHAN_PRE "
2631 "(was %u, now %u)", oalloc, sc->channels_alloc);
2634 /* Prepare pollfd */
2636 for (i = 0; i < sc->channels_alloc; i++)
2637 channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2642 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2643 const char *what, u_int revents_mask, u_int ready)
2645 struct pollfd *pfd = &pfds[p];
2649 if (p == -1 || (u_int)p >= npfd)
2650 fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2651 dump_channel_poll(__func__, what, c, p, pfd);
2652 if (pfd->fd != fd) {
2653 fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2654 "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2655 c->rfd, c->wfd, c->efd, c->sock);
2657 if ((pfd->revents & POLLNVAL) != 0) {
2658 fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2659 c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2661 if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2662 c->io_ready |= ready & c->io_want;
2666 * After poll, perform any appropriate operations for channels which have
2670 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2672 struct ssh_channels *sc = ssh->chanctxt;
2677 #ifdef DEBUG_CHANNEL_POLL
2678 for (p = 0; p < (int)npfd; p++) {
2679 if (pfd[p].revents == 0)
2681 debug_f("pfd[%u].fd %d rev 0x%04x",
2682 p, pfd[p].fd, pfd[p].revents);
2686 /* Convert pollfd into c->io_ready */
2687 for (i = 0; i < sc->channels_alloc; i++) {
2688 c = sc->channels[i];
2691 /* if rfd is shared with efd/sock then wfd should be too */
2692 if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2693 (c->rfd == c->efd || c->rfd == c->sock)) {
2694 /* Shouldn't happen */
2695 fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2696 c->self, c->rfd, c->wfd, c->efd, c->sock);
2699 /* rfd, potentially shared with wfd, efd and sock */
2700 if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2701 fd_ready(c, p, pfd, npfd, c->rfd,
2702 "rfd", POLLIN, SSH_CHAN_IO_RFD);
2703 if (c->rfd == c->wfd) {
2704 fd_ready(c, p, pfd, npfd, c->wfd,
2705 "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2707 if (c->rfd == c->efd) {
2708 fd_ready(c, p, pfd, npfd, c->efd,
2709 "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2710 fd_ready(c, p, pfd, npfd, c->efd,
2711 "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2713 if (c->rfd == c->sock) {
2714 fd_ready(c, p, pfd, npfd, c->sock,
2715 "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2716 fd_ready(c, p, pfd, npfd, c->sock,
2717 "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2719 dump_channel_poll(__func__, "rfd", c, p, pfd);
2722 if (c->wfd != -1 && c->wfd != c->rfd &&
2723 (p = c->pfds[1]) != -1) {
2724 fd_ready(c, p, pfd, npfd, c->wfd,
2725 "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2726 dump_channel_poll(__func__, "wfd", c, p, pfd);
2729 if (c->efd != -1 && c->efd != c->rfd &&
2730 (p = c->pfds[2]) != -1) {
2731 fd_ready(c, p, pfd, npfd, c->efd,
2732 "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2733 fd_ready(c, p, pfd, npfd, c->efd,
2734 "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2735 dump_channel_poll(__func__, "efd", c, p, pfd);
2738 if (c->sock != -1 && c->sock != c->rfd &&
2739 (p = c->pfds[3]) != -1) {
2740 fd_ready(c, p, pfd, npfd, c->sock,
2741 "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2742 fd_ready(c, p, pfd, npfd, c->sock,
2743 "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2744 dump_channel_poll(__func__, "sock", c, p, pfd);
2747 channel_handler(ssh, CHAN_POST, NULL);
2751 * Enqueue data for channels with open or draining c->input.
2754 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2760 if ((len = sshbuf_len(c->input)) == 0) {
2761 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2763 * input-buffer is empty and read-socket shutdown:
2764 * tell peer, that we will not send more data:
2766 * hack for extended data: delay EOF if EFD still
2769 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2770 debug2("channel %d: "
2771 "ibuf_empty delayed efd %d/(%zu)",
2772 c->self, c->efd, sshbuf_len(c->extended));
2774 chan_ibuf_empty(ssh, c);
2779 if (!c->have_remote_id)
2780 fatal_f("channel %d: no remote id", c->self);
2783 /* Check datagram will fit; drop if not */
2784 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2785 fatal_fr(r, "channel %i: get datagram", c->self);
2787 * XXX this does tail-drop on the datagram queue which is
2788 * usually suboptimal compared to head-drop. Better to have
2789 * backpressure at read time? (i.e. read + discard)
2791 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2792 debug("channel %d: datagram too big", c->self);
2796 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2797 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2798 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2799 (r = sshpkt_send(ssh)) != 0)
2800 fatal_fr(r, "channel %i: send datagram", c->self);
2801 c->remote_window -= plen;
2805 /* Enqueue packet for buffered data. */
2806 if (len > c->remote_window)
2807 len = c->remote_window;
2808 if (len > c->remote_maxpacket)
2809 len = c->remote_maxpacket;
2812 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2813 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2814 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2815 (r = sshpkt_send(ssh)) != 0)
2816 fatal_fr(r, "channel %i: send data", c->self);
2817 if ((r = sshbuf_consume(c->input, len)) != 0)
2818 fatal_fr(r, "channel %i: consume", c->self);
2819 c->remote_window -= len;
2823 * Enqueue data for channels with open c->extended in read mode.
2826 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2831 if ((len = sshbuf_len(c->extended)) == 0)
2834 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2835 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2836 if (len > c->remote_window)
2837 len = c->remote_window;
2838 if (len > c->remote_maxpacket)
2839 len = c->remote_maxpacket;
2842 if (!c->have_remote_id)
2843 fatal_f("channel %d: no remote id", c->self);
2844 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2845 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2846 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2847 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2848 (r = sshpkt_send(ssh)) != 0)
2849 fatal_fr(r, "channel %i: data", c->self);
2850 if ((r = sshbuf_consume(c->extended, len)) != 0)
2851 fatal_fr(r, "channel %i: consume", c->self);
2852 c->remote_window -= len;
2853 debug2("channel %d: sent ext data %zu", c->self, len);
2856 /* If there is data to send to the connection, enqueue some of it now. */
2858 channel_output_poll(struct ssh *ssh)
2860 struct ssh_channels *sc = ssh->chanctxt;
2864 for (i = 0; i < sc->channels_alloc; i++) {
2865 c = sc->channels[i];
2870 * We are only interested in channels that can have buffered
2873 if (c->type != SSH_CHANNEL_OPEN)
2875 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2876 /* XXX is this true? */
2877 debug3("channel %d: will not send data after close",
2882 /* Get the amount of buffered data for this channel. */
2883 if (c->istate == CHAN_INPUT_OPEN ||
2884 c->istate == CHAN_INPUT_WAIT_DRAIN)
2885 channel_output_poll_input_open(ssh, c);
2886 /* Send extended data, i.e. stderr */
2887 if (!(c->flags & CHAN_EOF_SENT) &&
2888 c->extended_usage == CHAN_EXTENDED_READ)
2889 channel_output_poll_extended_read(ssh, c);
2893 /* -- mux proxy support */
2896 * When multiplexing channel messages for mux clients we have to deal
2897 * with downstream messages from the mux client and upstream messages
2898 * from the ssh server:
2899 * 1) Handling downstream messages is straightforward and happens
2900 * in channel_proxy_downstream():
2901 * - We forward all messages (mostly) unmodified to the server.
2902 * - However, in order to route messages from upstream to the correct
2903 * downstream client, we have to replace the channel IDs used by the
2904 * mux clients with a unique channel ID because the mux clients might
2905 * use conflicting channel IDs.
2906 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2907 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2908 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2909 * with the newly allocated channel ID.
2910 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2911 * channels and processed by channel_proxy_upstream(). The local channel ID
2912 * is then translated back to the original mux client ID.
2913 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2914 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2915 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2916 * downstream mux client are removed.
2917 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2918 * requires more work, because they are not addressed to a specific
2919 * channel. E.g. client_request_forwarded_tcpip() needs to figure
2920 * out whether the request is addressed to the local client or a
2921 * specific downstream client based on the listen-address/port.
2922 * 6) Agent and X11-Forwarding have a similar problem and are currently
2923 * not supported as the matching session/channel cannot be identified
2928 * receive packets from downstream mux clients:
2929 * channel callback fired on read from mux client, creates
2930 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2931 * on channel creation.
2934 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2937 struct sshbuf *original = NULL, *modified = NULL;
2939 char *ctype = NULL, *listen_host = NULL;
2943 u_int id, remote_id, listen_port;
2945 /* sshbuf_dump(downstream->input, stderr); */
2946 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2948 error_fr(r, "parse");
2952 error_f("short message");
2956 /* skip padlen + type */
2959 if (ssh_packet_log_type(type))
2960 debug3_f("channel %u: down->up: type %u",
2961 downstream->self, type);
2964 case SSH2_MSG_CHANNEL_OPEN:
2965 if ((original = sshbuf_from(cp, have)) == NULL ||
2966 (modified = sshbuf_new()) == NULL) {
2970 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2971 (r = sshbuf_get_u32(original, &id)) != 0) {
2972 error_fr(r, "parse");
2975 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2976 -1, -1, -1, 0, 0, 0, ctype, 1);
2977 c->mux_ctx = downstream; /* point to mux client */
2978 c->mux_downstream_id = id; /* original downstream id */
2979 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2980 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2981 (r = sshbuf_putb(modified, original)) != 0) {
2982 error_fr(r, "compose");
2983 channel_free(ssh, c);
2987 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2989 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2990 * need to parse 'remote_id' instead of 'ctype'.
2992 if ((original = sshbuf_from(cp, have)) == NULL ||
2993 (modified = sshbuf_new()) == NULL) {
2997 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2998 (r = sshbuf_get_u32(original, &id)) != 0) {
2999 error_fr(r, "parse");
3002 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
3003 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3004 c->mux_ctx = downstream; /* point to mux client */
3005 c->mux_downstream_id = id;
3006 c->remote_id = remote_id;
3007 c->have_remote_id = 1;
3008 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3009 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3010 (r = sshbuf_putb(modified, original)) != 0) {
3011 error_fr(r, "compose");
3012 channel_free(ssh, c);
3016 case SSH2_MSG_GLOBAL_REQUEST:
3017 if ((original = sshbuf_from(cp, have)) == NULL) {
3021 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3022 error_fr(r, "parse");
3025 if (strcmp(ctype, "tcpip-forward") != 0) {
3026 error_f("unsupported request %s", ctype);
3029 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3030 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3031 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3032 error_fr(r, "parse");
3035 if (listen_port > 65535) {
3036 error_f("tcpip-forward for %s: bad port %u",
3037 listen_host, listen_port);
3040 /* Record that connection to this host/port is permitted. */
3041 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3042 listen_host, NULL, (int)listen_port, downstream);
3045 case SSH2_MSG_CHANNEL_CLOSE:
3048 remote_id = PEEK_U32(cp);
3049 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3050 if (c->flags & CHAN_CLOSE_RCVD)
3051 channel_free(ssh, c);
3053 c->flags |= CHAN_CLOSE_SENT;
3058 if ((r = sshpkt_start(ssh, type)) != 0 ||
3059 (r = sshpkt_putb(ssh, modified)) != 0 ||
3060 (r = sshpkt_send(ssh)) != 0) {
3061 error_fr(r, "send");
3065 if ((r = sshpkt_start(ssh, type)) != 0 ||
3066 (r = sshpkt_put(ssh, cp, have)) != 0 ||
3067 (r = sshpkt_send(ssh)) != 0) {
3068 error_fr(r, "send");
3076 sshbuf_free(original);
3077 sshbuf_free(modified);
3082 * receive packets from upstream server and de-multiplex packets
3083 * to correct downstream:
3084 * implemented as a helper for channel input handlers,
3085 * replaces local (proxy) channel ID with downstream channel ID.
3088 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3090 struct sshbuf *b = NULL;
3091 Channel *downstream;
3092 const u_char *cp = NULL;
3097 * When receiving packets from the peer we need to check whether we
3098 * need to forward the packets to the mux client. In this case we
3099 * restore the original channel id and keep track of CLOSE messages,
3100 * so we can cleanup the channel.
3102 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3104 if ((downstream = c->mux_ctx) == NULL)
3107 case SSH2_MSG_CHANNEL_CLOSE:
3108 case SSH2_MSG_CHANNEL_DATA:
3109 case SSH2_MSG_CHANNEL_EOF:
3110 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3111 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3112 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3113 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3114 case SSH2_MSG_CHANNEL_SUCCESS:
3115 case SSH2_MSG_CHANNEL_FAILURE:
3116 case SSH2_MSG_CHANNEL_REQUEST:
3119 debug2_f("channel %u: unsupported type %u", c->self, type);
3122 if ((b = sshbuf_new()) == NULL) {
3123 error_f("alloc reply");
3126 /* get remaining payload (after id) */
3127 cp = sshpkt_ptr(ssh, &len);
3129 error_f("no packet");
3132 /* translate id and send to muxclient */
3133 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
3134 (r = sshbuf_put_u8(b, type)) != 0 ||
3135 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3136 (r = sshbuf_put(b, cp, len)) != 0 ||
3137 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3138 error_fr(r, "compose muxclient");
3141 /* sshbuf_dump(b, stderr); */
3142 if (ssh_packet_log_type(type))
3143 debug3_f("channel %u: up->down: type %u", c->self, type);
3147 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3148 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3149 if (cp && len > 4) {
3150 c->remote_id = PEEK_U32(cp);
3151 c->have_remote_id = 1;
3154 case SSH2_MSG_CHANNEL_CLOSE:
3155 if (c->flags & CHAN_CLOSE_SENT)
3156 channel_free(ssh, c);
3158 c->flags |= CHAN_CLOSE_RCVD;
3165 /* -- protocol input */
3167 /* Parse a channel ID from the current packet */
3169 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3174 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3175 error_r(r, "%s: parse id", where);
3176 ssh_packet_disconnect(ssh, "Invalid %s message", what);
3179 error_r(r, "%s: bad channel id %u", where, id);
3180 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3185 /* Lookup a channel from an ID in the current packet */
3187 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3189 int id = channel_parse_id(ssh, where, what);
3192 if ((c = channel_lookup(ssh, id)) == NULL) {
3193 ssh_packet_disconnect(ssh,
3194 "%s packet referred to nonexistent channel %d", what, id);
3200 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3203 size_t data_len, win_len;
3204 Channel *c = channel_from_packet_id(ssh, __func__, "data");
3207 if (channel_proxy_upstream(c, type, seq, ssh))
3210 /* Ignore any data for non-open channels (might happen on close) */
3211 if (c->type != SSH_CHANNEL_OPEN &&
3212 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3213 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3214 c->type != SSH_CHANNEL_X11_OPEN)
3218 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3219 (r = sshpkt_get_end(ssh)) != 0)
3220 fatal_fr(r, "channel %i: get data", c->self);
3224 win_len += 4; /* string length header */
3227 * The sending side reduces its window as it sends data, so we
3228 * must 'fake' consumption of the data in order to ensure that window
3229 * updates are sent back. Otherwise the connection might deadlock.
3231 if (c->ostate != CHAN_OUTPUT_OPEN) {
3232 c->local_window -= win_len;
3233 c->local_consumed += win_len;
3237 if (win_len > c->local_maxpacket) {
3238 logit("channel %d: rcvd big packet %zu, maxpack %u",
3239 c->self, win_len, c->local_maxpacket);
3242 if (win_len > c->local_window) {
3243 logit("channel %d: rcvd too much data %zu, win %u",
3244 c->self, win_len, c->local_window);
3247 c->local_window -= win_len;
3250 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3251 fatal_fr(r, "channel %i: append datagram", c->self);
3252 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3253 fatal_fr(r, "channel %i: append data", c->self);
3259 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3264 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3267 if (channel_proxy_upstream(c, type, seq, ssh))
3269 if (c->type != SSH_CHANNEL_OPEN) {
3270 logit("channel %d: ext data for non open", c->self);
3273 if (c->flags & CHAN_EOF_RCVD) {
3274 if (ssh->compat & SSH_BUG_EXTEOF)
3275 debug("channel %d: accepting ext data after eof",
3278 ssh_packet_disconnect(ssh, "Received extended_data "
3279 "after EOF on channel %d.", c->self);
3282 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3283 error_fr(r, "parse tcode");
3284 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3287 c->extended_usage != CHAN_EXTENDED_WRITE ||
3288 tcode != SSH2_EXTENDED_DATA_STDERR) {
3289 logit("channel %d: bad ext data", c->self);
3292 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3293 (r = sshpkt_get_end(ssh)) != 0) {
3294 error_fr(r, "parse data");
3295 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3298 if (data_len > c->local_window) {
3299 logit("channel %d: rcvd too much extended_data %zu, win %u",
3300 c->self, data_len, c->local_window);
3303 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3304 /* XXX sshpkt_getb? */
3305 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3306 error_fr(r, "append");
3307 c->local_window -= data_len;
3312 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3314 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3317 if ((r = sshpkt_get_end(ssh)) != 0) {
3318 error_fr(r, "parse data");
3319 ssh_packet_disconnect(ssh, "Invalid ieof message");
3322 if (channel_proxy_upstream(c, type, seq, ssh))
3324 chan_rcvd_ieof(ssh, c);
3326 /* XXX force input close */
3327 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3328 debug("channel %d: FORCE input drain", c->self);
3329 c->istate = CHAN_INPUT_WAIT_DRAIN;
3330 if (sshbuf_len(c->input) == 0)
3331 chan_ibuf_empty(ssh, c);
3337 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3339 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3342 if (channel_proxy_upstream(c, type, seq, ssh))
3344 if ((r = sshpkt_get_end(ssh)) != 0) {
3345 error_fr(r, "parse data");
3346 ssh_packet_disconnect(ssh, "Invalid oclose message");
3348 chan_rcvd_oclose(ssh, c);
3353 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3355 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3356 u_int32_t remote_window, remote_maxpacket;
3359 if (channel_proxy_upstream(c, type, seq, ssh))
3361 if (c->type != SSH_CHANNEL_OPENING)
3362 ssh_packet_disconnect(ssh, "Received open confirmation for "
3363 "non-opening channel %d.", c->self);
3365 * Record the remote channel number and mark that the channel
3368 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3369 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3370 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3371 (r = sshpkt_get_end(ssh)) != 0) {
3372 error_fr(r, "window/maxpacket");
3373 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3376 c->have_remote_id = 1;
3377 c->remote_window = remote_window;
3378 c->remote_maxpacket = remote_maxpacket;
3379 c->type = SSH_CHANNEL_OPEN;
3380 if (c->open_confirm) {
3381 debug2_f("channel %d: callback start", c->self);
3382 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3383 debug2_f("channel %d: callback done", c->self);
3385 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3386 c->remote_window, c->remote_maxpacket);
3391 reason2txt(int reason)
3394 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3395 return "administratively prohibited";
3396 case SSH2_OPEN_CONNECT_FAILED:
3397 return "connect failed";
3398 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3399 return "unknown channel type";
3400 case SSH2_OPEN_RESOURCE_SHORTAGE:
3401 return "resource shortage";
3403 return "unknown reason";
3407 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3409 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3414 if (channel_proxy_upstream(c, type, seq, ssh))
3416 if (c->type != SSH_CHANNEL_OPENING)
3417 ssh_packet_disconnect(ssh, "Received open failure for "
3418 "non-opening channel %d.", c->self);
3419 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3420 error_fr(r, "parse reason");
3421 ssh_packet_disconnect(ssh, "Invalid open failure message");
3424 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3425 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3426 (r = sshpkt_get_end(ssh)) != 0) {
3427 error_fr(r, "parse msg/lang");
3428 ssh_packet_disconnect(ssh, "Invalid open failure message");
3430 logit("channel %d: open failed: %s%s%s", c->self,
3431 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3433 if (c->open_confirm) {
3434 debug2_f("channel %d: callback start", c->self);
3435 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3436 debug2_f("channel %d: callback done", c->self);
3438 /* Schedule the channel for cleanup/deletion. */
3439 chan_mark_dead(ssh, c);
3444 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3446 int id = channel_parse_id(ssh, __func__, "window adjust");
3452 if ((c = channel_lookup(ssh, id)) == NULL) {
3453 logit("Received window adjust for non-open channel %d.", id);
3457 if (channel_proxy_upstream(c, type, seq, ssh))
3459 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3460 (r = sshpkt_get_end(ssh)) != 0) {
3461 error_fr(r, "parse adjust");
3462 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3464 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3465 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3466 fatal("channel %d: adjust %u overflows remote window %u",
3467 c->self, adjust, c->remote_window);
3469 c->remote_window = new_rwin;
3474 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3476 int id = channel_parse_id(ssh, __func__, "status confirm");
3478 struct channel_confirm *cc;
3480 /* Reset keepalive timeout */
3481 ssh_packet_set_alive_timeouts(ssh, 0);
3483 debug2_f("type %d id %d", type, id);
3485 if ((c = channel_lookup(ssh, id)) == NULL) {
3486 logit_f("%d: unknown", id);
3489 if (channel_proxy_upstream(c, type, seq, ssh))
3491 if (sshpkt_get_end(ssh) != 0)
3492 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3493 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3495 cc->cb(ssh, type, c, cc->ctx);
3496 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3497 freezero(cc, sizeof(*cc));
3501 /* -- tcp forwarding */
3504 channel_set_af(struct ssh *ssh, int af)
3506 ssh->chanctxt->IPv4or6 = af;
3511 * Determine whether or not a port forward listens to loopback, the
3512 * specified address or wildcard. On the client, a specified bind
3513 * address will always override gateway_ports. On the server, a
3514 * gateway_ports of 1 (``yes'') will override the client's specification
3515 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3516 * will bind to whatever address the client asked for.
3518 * Special-case listen_addrs are:
3520 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3521 * "" (empty string), "*" -> wildcard v4/v6
3522 * "localhost" -> loopback v4/v6
3523 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3526 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3527 int is_client, struct ForwardOptions *fwd_opts)
3529 const char *addr = NULL;
3532 if (listen_addr == NULL) {
3533 /* No address specified: default to gateway_ports setting */
3534 if (fwd_opts->gateway_ports)
3536 } else if (fwd_opts->gateway_ports || is_client) {
3537 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3538 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3539 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3540 (!is_client && fwd_opts->gateway_ports == 1)) {
3543 * Notify client if they requested a specific listen
3544 * address and it was overridden.
3546 if (*listen_addr != '\0' &&
3547 strcmp(listen_addr, "0.0.0.0") != 0 &&
3548 strcmp(listen_addr, "*") != 0) {
3549 ssh_packet_send_debug(ssh,
3550 "Forwarding listen address "
3551 "\"%s\" overridden by server "
3552 "GatewayPorts", listen_addr);
3554 } else if (strcmp(listen_addr, "localhost") != 0 ||
3555 strcmp(listen_addr, "127.0.0.1") == 0 ||
3556 strcmp(listen_addr, "::1") == 0) {
3558 * Accept explicit localhost address when
3559 * GatewayPorts=yes. The "localhost" hostname is
3560 * deliberately skipped here so it will listen on all
3561 * available local address families.
3565 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3566 strcmp(listen_addr, "::1") == 0) {
3568 * If a specific IPv4/IPv6 localhost address has been
3569 * requested then accept it even if gateway_ports is in
3570 * effect. This allows the client to prefer IPv4 or IPv6.
3574 if (wildcardp != NULL)
3575 *wildcardp = wildcard;
3580 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3581 struct Forward *fwd, int *allocated_listen_port,
3582 struct ForwardOptions *fwd_opts)
3585 int sock, r, success = 0, wildcard = 0, is_client;
3586 struct addrinfo hints, *ai, *aitop;
3587 const char *host, *addr;
3588 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3591 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3593 if (is_client && fwd->connect_path != NULL) {
3594 host = fwd->connect_path;
3596 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3597 fwd->listen_host : fwd->connect_host;
3599 error("No forward host name.");
3602 if (strlen(host) >= NI_MAXHOST) {
3603 error("Forward host name too long.");
3608 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3609 addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3610 is_client, fwd_opts);
3611 debug3_f("type %d wildcard %d addr %s", type, wildcard,
3612 (addr == NULL) ? "NULL" : addr);
3615 * getaddrinfo returns a loopback address if the hostname is
3616 * set to NULL and hints.ai_flags is not AI_PASSIVE
3618 memset(&hints, 0, sizeof(hints));
3619 hints.ai_family = ssh->chanctxt->IPv4or6;
3620 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3621 hints.ai_socktype = SOCK_STREAM;
3622 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3623 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3625 /* This really shouldn't happen */
3626 ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3627 ssh_gai_strerror(r));
3629 error_f("getaddrinfo(%.64s): %s", addr,
3630 ssh_gai_strerror(r));
3634 if (allocated_listen_port != NULL)
3635 *allocated_listen_port = 0;
3636 for (ai = aitop; ai; ai = ai->ai_next) {
3637 switch (ai->ai_family) {
3639 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3643 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3650 * If allocating a port for -R forwards, then use the
3651 * same port for all address families.
3653 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3654 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3655 *allocated_listen_port > 0)
3656 *lport_p = htons(*allocated_listen_port);
3658 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3659 strport, sizeof(strport),
3660 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3661 error_f("getnameinfo failed");
3664 /* Create a port to listen for the host. */
3665 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3667 /* this is no error since kernel may not support ipv6 */
3668 verbose("socket [%s]:%s: %.100s", ntop, strport,
3673 set_reuseaddr(sock);
3674 if (ai->ai_family == AF_INET6)
3675 sock_set_v6only(sock);
3677 debug("Local forwarding listening on %s port %s.",
3680 /* Bind the socket to the address. */
3681 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3683 * address can be in if use ipv6 address is
3687 error("bind [%s]:%s: %.100s",
3688 ntop, strport, strerror(errno));
3690 verbose("bind [%s]:%s: %.100s",
3691 ntop, strport, strerror(errno));
3696 /* Start listening for connections on the socket. */
3697 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3698 error("listen [%s]:%s: %.100s", ntop, strport,
3705 * fwd->listen_port == 0 requests a dynamically allocated port -
3706 * record what we got.
3708 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3709 fwd->listen_port == 0 &&
3710 allocated_listen_port != NULL &&
3711 *allocated_listen_port == 0) {
3712 *allocated_listen_port = get_local_port(sock);
3713 debug("Allocated listen port %d",
3714 *allocated_listen_port);
3717 /* Allocate a channel number for the socket. */
3718 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3719 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3720 0, "port listener", 1);
3721 c->path = xstrdup(host);
3722 c->host_port = fwd->connect_port;
3723 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3724 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3725 !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3726 c->listening_port = *allocated_listen_port;
3728 c->listening_port = fwd->listen_port;
3732 error_f("cannot listen to port: %d", fwd->listen_port);
3733 freeaddrinfo(aitop);
3738 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3739 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3741 struct sockaddr_un sunaddr;
3748 case SSH_CHANNEL_UNIX_LISTENER:
3749 if (fwd->connect_path != NULL) {
3750 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3751 error("Local connecting path too long: %s",
3755 path = fwd->connect_path;
3756 port = PORT_STREAMLOCAL;
3758 if (fwd->connect_host == NULL) {
3759 error("No forward host name.");
3762 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3763 error("Forward host name too long.");
3766 path = fwd->connect_host;
3767 port = fwd->connect_port;
3770 case SSH_CHANNEL_RUNIX_LISTENER:
3771 path = fwd->listen_path;
3772 port = PORT_STREAMLOCAL;
3775 error_f("unexpected channel type %d", type);
3779 if (fwd->listen_path == NULL) {
3780 error("No forward path name.");
3783 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3784 error("Local listening path too long: %s", fwd->listen_path);
3788 debug3_f("type %d path %s", type, fwd->listen_path);
3790 /* Start a Unix domain listener. */
3791 omask = umask(fwd_opts->streamlocal_bind_mask);
3792 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3793 fwd_opts->streamlocal_bind_unlink);
3798 debug("Local forwarding listening on path %s.", fwd->listen_path);
3800 /* Allocate a channel number for the socket. */
3801 c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3802 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3803 0, "unix listener", 1);
3804 c->path = xstrdup(path);
3805 c->host_port = port;
3806 c->listening_port = PORT_STREAMLOCAL;
3807 c->listening_addr = xstrdup(fwd->listen_path);
3812 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3813 const char *host, u_short port)
3818 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3819 Channel *c = ssh->chanctxt->channels[i];
3820 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3822 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3823 debug2_f("close channel %d", i);
3824 channel_free(ssh, c);
3833 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3838 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3839 Channel *c = ssh->chanctxt->channels[i];
3840 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3842 if (c->path == NULL)
3844 if (strcmp(c->path, path) == 0) {
3845 debug2_f("close channel %d", i);
3846 channel_free(ssh, c);
3855 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3857 if (fwd->listen_path != NULL) {
3858 return channel_cancel_rport_listener_streamlocal(ssh,
3861 return channel_cancel_rport_listener_tcpip(ssh,
3862 fwd->listen_host, fwd->listen_port);
3867 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3868 const char *lhost, u_short lport, int cport,
3869 struct ForwardOptions *fwd_opts)
3873 const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3875 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3876 Channel *c = ssh->chanctxt->channels[i];
3877 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3879 if (c->listening_port != lport)
3881 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3882 /* skip dynamic forwardings */
3883 if (c->host_port == 0)
3886 if (c->host_port != cport)
3889 if ((c->listening_addr == NULL && addr != NULL) ||
3890 (c->listening_addr != NULL && addr == NULL))
3892 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3893 debug2_f("close channel %d", i);
3894 channel_free(ssh, c);
3903 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3909 error_f("no path specified.");
3913 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3914 Channel *c = ssh->chanctxt->channels[i];
3915 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3917 if (c->listening_addr == NULL)
3919 if (strcmp(c->listening_addr, path) == 0) {
3920 debug2_f("close channel %d", i);
3921 channel_free(ssh, c);
3930 channel_cancel_lport_listener(struct ssh *ssh,
3931 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3933 if (fwd->listen_path != NULL) {
3934 return channel_cancel_lport_listener_streamlocal(ssh,
3937 return channel_cancel_lport_listener_tcpip(ssh,
3938 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3942 /* protocol local port fwd, used by ssh */
3944 channel_setup_local_fwd_listener(struct ssh *ssh,
3945 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3947 if (fwd->listen_path != NULL) {
3948 return channel_setup_fwd_listener_streamlocal(ssh,
3949 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3951 return channel_setup_fwd_listener_tcpip(ssh,
3952 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3956 /* Matches a remote forwarding permission against a requested forwarding */
3958 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3963 /* XXX add ACLs for streamlocal */
3964 if (fwd->listen_path != NULL)
3967 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3970 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3971 allowed_open->listen_port != fwd->listen_port)
3974 /* Match hostnames case-insensitively */
3975 lhost = xstrdup(fwd->listen_host);
3977 ret = match_pattern(lhost, allowed_open->listen_host);
3983 /* Checks whether a requested remote forwarding is permitted */
3985 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3987 struct ssh_channels *sc = ssh->chanctxt;
3988 struct permission_set *pset = &sc->remote_perms;
3989 u_int i, permit, permit_adm = 1;
3990 struct permission *perm;
3992 /* XXX apply GatewayPorts override before checking? */
3994 permit = pset->all_permitted;
3996 for (i = 0; i < pset->num_permitted_user; i++) {
3997 perm = &pset->permitted_user[i];
3998 if (remote_open_match(perm, fwd)) {
4005 if (pset->num_permitted_admin > 0) {
4007 for (i = 0; i < pset->num_permitted_admin; i++) {
4008 perm = &pset->permitted_admin[i];
4009 if (remote_open_match(perm, fwd)) {
4016 return permit && permit_adm;
4019 /* protocol v2 remote port fwd, used by sshd */
4021 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4022 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4024 if (!check_rfwd_permission(ssh, fwd)) {
4025 ssh_packet_send_debug(ssh, "port forwarding refused");
4026 if (fwd->listen_path != NULL)
4027 /* XXX always allowed, see remote_open_match() */
4028 logit("Received request from %.100s port %d to "
4029 "remote forward to path \"%.100s\", "
4030 "but the request was denied.",
4031 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4033 else if(fwd->listen_host != NULL)
4034 logit("Received request from %.100s port %d to "
4035 "remote forward to host %.100s port %d, "
4036 "but the request was denied.",
4037 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4038 fwd->listen_host, fwd->listen_port );
4040 logit("Received request from %.100s port %d to remote "
4041 "forward, but the request was denied.",
4042 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4045 if (fwd->listen_path != NULL) {
4046 return channel_setup_fwd_listener_streamlocal(ssh,
4047 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4049 return channel_setup_fwd_listener_tcpip(ssh,
4050 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4056 * Translate the requested rfwd listen host to something usable for
4060 channel_rfwd_bind_host(const char *listen_host)
4062 if (listen_host == NULL) {
4064 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4071 * Initiate forwarding of connections to port "port" on remote host through
4072 * the secure channel to host:port from local side.
4073 * Returns handle (index) for updating the dynamic listen port with
4074 * channel_update_permission().
4077 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4079 int r, success = 0, idx = -1;
4080 char *host_to_connect, *listen_host, *listen_path;
4081 int port_to_connect, listen_port;
4083 /* Send the forward request to the remote side. */
4084 if (fwd->listen_path != NULL) {
4085 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4086 (r = sshpkt_put_cstring(ssh,
4087 "streamlocal-forward@openssh.com")) != 0 ||
4088 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4089 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4090 (r = sshpkt_send(ssh)) != 0 ||
4091 (r = ssh_packet_write_wait(ssh)) != 0)
4092 fatal_fr(r, "request streamlocal");
4094 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4095 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4096 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4097 (r = sshpkt_put_cstring(ssh,
4098 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4099 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4100 (r = sshpkt_send(ssh)) != 0 ||
4101 (r = ssh_packet_write_wait(ssh)) != 0)
4102 fatal_fr(r, "request tcpip-forward");
4104 /* Assume that server accepts the request */
4107 /* Record that connection to this host/port is permitted. */
4108 host_to_connect = listen_host = listen_path = NULL;
4109 port_to_connect = listen_port = 0;
4110 if (fwd->connect_path != NULL) {
4111 host_to_connect = xstrdup(fwd->connect_path);
4112 port_to_connect = PORT_STREAMLOCAL;
4114 host_to_connect = xstrdup(fwd->connect_host);
4115 port_to_connect = fwd->connect_port;
4117 if (fwd->listen_path != NULL) {
4118 listen_path = xstrdup(fwd->listen_path);
4119 listen_port = PORT_STREAMLOCAL;
4121 if (fwd->listen_host != NULL)
4122 listen_host = xstrdup(fwd->listen_host);
4123 listen_port = fwd->listen_port;
4125 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4126 host_to_connect, port_to_connect,
4127 listen_host, listen_path, listen_port, NULL);
4133 open_match(struct permission *allowed_open, const char *requestedhost,
4136 if (allowed_open->host_to_connect == NULL)
4138 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4139 allowed_open->port_to_connect != requestedport)
4141 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4142 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4148 * Note that in the listen host/port case
4149 * we don't support FWD_PERMIT_ANY_PORT and
4150 * need to translate between the configured-host (listen_host)
4151 * and what we've sent to the remote server (channel_rfwd_bind_host)
4154 open_listen_match_tcpip(struct permission *allowed_open,
4155 const char *requestedhost, u_short requestedport, int translate)
4157 const char *allowed_host;
4159 if (allowed_open->host_to_connect == NULL)
4161 if (allowed_open->listen_port != requestedport)
4163 if (!translate && allowed_open->listen_host == NULL &&
4164 requestedhost == NULL)
4166 allowed_host = translate ?
4167 channel_rfwd_bind_host(allowed_open->listen_host) :
4168 allowed_open->listen_host;
4169 if (allowed_host == NULL || requestedhost == NULL ||
4170 strcmp(allowed_host, requestedhost) != 0)
4176 open_listen_match_streamlocal(struct permission *allowed_open,
4177 const char *requestedpath)
4179 if (allowed_open->host_to_connect == NULL)
4181 if (allowed_open->listen_port != PORT_STREAMLOCAL)
4183 if (allowed_open->listen_path == NULL ||
4184 strcmp(allowed_open->listen_path, requestedpath) != 0)
4190 * Request cancellation of remote forwarding of connection host:port from
4194 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4195 const char *host, u_short port)
4197 struct ssh_channels *sc = ssh->chanctxt;
4198 struct permission_set *pset = &sc->local_perms;
4201 struct permission *perm = NULL;
4203 for (i = 0; i < pset->num_permitted_user; i++) {
4204 perm = &pset->permitted_user[i];
4205 if (open_listen_match_tcpip(perm, host, port, 0))
4210 debug_f("requested forward not found");
4213 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4214 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4215 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4216 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4217 (r = sshpkt_put_u32(ssh, port)) != 0 ||
4218 (r = sshpkt_send(ssh)) != 0)
4219 fatal_fr(r, "send cancel");
4221 fwd_perm_clear(perm); /* unregister */
4227 * Request cancellation of remote forwarding of Unix domain socket
4228 * path from local side.
4231 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4233 struct ssh_channels *sc = ssh->chanctxt;
4234 struct permission_set *pset = &sc->local_perms;
4237 struct permission *perm = NULL;
4239 for (i = 0; i < pset->num_permitted_user; i++) {
4240 perm = &pset->permitted_user[i];
4241 if (open_listen_match_streamlocal(perm, path))
4246 debug_f("requested forward not found");
4249 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4250 (r = sshpkt_put_cstring(ssh,
4251 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4252 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4253 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4254 (r = sshpkt_send(ssh)) != 0)
4255 fatal_fr(r, "send cancel");
4257 fwd_perm_clear(perm); /* unregister */
4263 * Request cancellation of remote forwarding of a connection from local side.
4266 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4268 if (fwd->listen_path != NULL) {
4269 return channel_request_rforward_cancel_streamlocal(ssh,
4272 return channel_request_rforward_cancel_tcpip(ssh,
4274 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4279 * Permits opening to any host/port if permitted_user[] is empty. This is
4280 * usually called by the server, because the user could connect to any port
4281 * anyway, and the server has no way to know but to trust the client anyway.
4284 channel_permit_all(struct ssh *ssh, int where)
4286 struct permission_set *pset = permission_set_get(ssh, where);
4288 if (pset->num_permitted_user == 0)
4289 pset->all_permitted = 1;
4293 * Permit the specified host/port for forwarding.
4296 channel_add_permission(struct ssh *ssh, int who, int where,
4297 char *host, int port)
4299 int local = where == FORWARD_LOCAL;
4300 struct permission_set *pset = permission_set_get(ssh, where);
4302 debug("allow %s forwarding to host %s port %d",
4303 fwd_ident(who, where), host, port);
4305 * Remote forwards set listen_host/port, local forwards set
4306 * host/port_to_connect.
4308 permission_set_add(ssh, who, where,
4309 local ? host : 0, local ? port : 0,
4310 local ? NULL : host, NULL, local ? 0 : port, NULL);
4311 pset->all_permitted = 0;
4315 * Administratively disable forwarding.
4318 channel_disable_admin(struct ssh *ssh, int where)
4320 channel_clear_permission(ssh, FORWARD_ADM, where);
4321 permission_set_add(ssh, FORWARD_ADM, where,
4322 NULL, 0, NULL, NULL, 0, NULL);
4326 * Clear a list of permitted opens.
4329 channel_clear_permission(struct ssh *ssh, int who, int where)
4331 struct permission **permp;
4334 permission_set_get_array(ssh, who, where, &permp, &npermp);
4335 *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4340 * Update the listen port for a dynamic remote forward, after
4341 * the actual 'newport' has been allocated. If 'newport' < 0 is
4342 * passed then they entry will be invalidated.
4345 channel_update_permission(struct ssh *ssh, int idx, int newport)
4347 struct permission_set *pset = &ssh->chanctxt->local_perms;
4349 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4350 debug_f("index out of range: %d num_permitted_user %d",
4351 idx, pset->num_permitted_user);
4354 debug("%s allowed port %d for forwarding to host %s port %d",
4355 newport > 0 ? "Updating" : "Removing",
4357 pset->permitted_user[idx].host_to_connect,
4358 pset->permitted_user[idx].port_to_connect);
4360 fwd_perm_clear(&pset->permitted_user[idx]);
4362 pset->permitted_user[idx].listen_port =
4363 (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4367 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4369 permitopen_port(const char *p)
4373 if (strcmp(p, "*") == 0)
4374 return FWD_PERMIT_ANY_PORT;
4375 if ((port = a2port(p)) > 0)
4380 /* Try to start non-blocking connect to next host in cctx list */
4382 connect_next(struct channel_connect *cctx)
4384 int sock, saved_errno;
4385 struct sockaddr_un *sunaddr;
4386 char ntop[NI_MAXHOST];
4387 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4389 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4390 switch (cctx->ai->ai_family) {
4392 /* unix:pathname instead of host:port */
4393 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4394 strlcpy(ntop, "unix", sizeof(ntop));
4395 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4399 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4400 ntop, sizeof(ntop), strport, sizeof(strport),
4401 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4402 error("connect_next: getnameinfo failed");
4409 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4410 cctx->ai->ai_protocol)) == -1) {
4411 if (cctx->ai->ai_next == NULL)
4412 error("socket: %.100s", strerror(errno));
4414 verbose("socket: %.100s", strerror(errno));
4417 if (set_nonblock(sock) == -1)
4418 fatal_f("set_nonblock(%d)", sock);
4419 if (connect(sock, cctx->ai->ai_addr,
4420 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4421 debug("connect_next: host %.100s ([%.100s]:%s): "
4422 "%.100s", cctx->host, ntop, strport,
4424 saved_errno = errno;
4426 errno = saved_errno;
4427 continue; /* fail -- try next */
4429 if (cctx->ai->ai_family != AF_UNIX)
4431 debug("connect_next: host %.100s ([%.100s]:%s) "
4432 "in progress, fd=%d", cctx->host, ntop, strport, sock);
4433 cctx->ai = cctx->ai->ai_next;
4440 channel_connect_ctx_free(struct channel_connect *cctx)
4444 if (cctx->aitop->ai_family == AF_UNIX)
4447 freeaddrinfo(cctx->aitop);
4449 memset(cctx, 0, sizeof(*cctx));
4453 * Return connecting socket to remote host:port or local socket path,
4454 * passing back the failure reason if appropriate.
4457 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4458 char *ctype, char *rname, struct channel_connect *cctx,
4459 int *reason, const char **errmsg)
4461 struct addrinfo hints;
4464 char strport[NI_MAXSERV];
4466 if (port == PORT_STREAMLOCAL) {
4467 struct sockaddr_un *sunaddr;
4468 struct addrinfo *ai;
4470 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4471 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4476 * Fake up a struct addrinfo for AF_UNIX connections.
4477 * channel_connect_ctx_free() must check ai_family
4478 * and use free() not freeaddirinfo() for AF_UNIX.
4480 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4481 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4482 ai->ai_addr = (struct sockaddr *)(ai + 1);
4483 ai->ai_addrlen = sizeof(*sunaddr);
4484 ai->ai_family = AF_UNIX;
4485 ai->ai_socktype = socktype;
4486 ai->ai_protocol = PF_UNSPEC;
4487 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4488 sunaddr->sun_family = AF_UNIX;
4489 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4492 memset(&hints, 0, sizeof(hints));
4493 hints.ai_family = ssh->chanctxt->IPv4or6;
4494 hints.ai_socktype = socktype;
4495 snprintf(strport, sizeof strport, "%d", port);
4496 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4499 *errmsg = ssh_gai_strerror(gaierr);
4501 *reason = SSH2_OPEN_CONNECT_FAILED;
4502 error("connect_to %.100s: unknown host (%s)", name,
4503 ssh_gai_strerror(gaierr));
4508 cctx->host = xstrdup(name);
4510 cctx->ai = cctx->aitop;
4512 if ((sock = connect_next(cctx)) == -1) {
4513 error("connect to %.100s port %d failed: %s",
4514 name, port, strerror(errno));
4521 /* Return CONNECTING channel to remote host:port or local socket path */
4523 connect_to(struct ssh *ssh, const char *host, int port,
4524 char *ctype, char *rname)
4526 struct channel_connect cctx;
4530 memset(&cctx, 0, sizeof(cctx));
4531 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4534 channel_connect_ctx_free(&cctx);
4537 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4538 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4539 c->host_port = port;
4540 c->path = xstrdup(host);
4541 c->connect_ctx = cctx;
4547 * returns either the newly connected channel or the downstream channel
4548 * that needs to deal with this connection.
4551 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4552 u_short listen_port, char *ctype, char *rname)
4554 struct ssh_channels *sc = ssh->chanctxt;
4555 struct permission_set *pset = &sc->local_perms;
4557 struct permission *perm;
4559 for (i = 0; i < pset->num_permitted_user; i++) {
4560 perm = &pset->permitted_user[i];
4561 if (open_listen_match_tcpip(perm,
4562 listen_host, listen_port, 1)) {
4563 if (perm->downstream)
4564 return perm->downstream;
4565 if (perm->port_to_connect == 0)
4566 return rdynamic_connect_prepare(ssh,
4568 return connect_to(ssh,
4569 perm->host_to_connect, perm->port_to_connect,
4573 error("WARNING: Server requests forwarding for unknown listen_port %d",
4579 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4580 char *ctype, char *rname)
4582 struct ssh_channels *sc = ssh->chanctxt;
4583 struct permission_set *pset = &sc->local_perms;
4585 struct permission *perm;
4587 for (i = 0; i < pset->num_permitted_user; i++) {
4588 perm = &pset->permitted_user[i];
4589 if (open_listen_match_streamlocal(perm, path)) {
4590 return connect_to(ssh,
4591 perm->host_to_connect, perm->port_to_connect,
4595 error("WARNING: Server requests forwarding for unknown path %.100s",
4600 /* Check if connecting to that port is permitted and connect. */
4602 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4603 char *ctype, char *rname, int *reason, const char **errmsg)
4605 struct ssh_channels *sc = ssh->chanctxt;
4606 struct permission_set *pset = &sc->local_perms;
4607 struct channel_connect cctx;
4609 u_int i, permit, permit_adm = 1;
4611 struct permission *perm;
4613 permit = pset->all_permitted;
4615 for (i = 0; i < pset->num_permitted_user; i++) {
4616 perm = &pset->permitted_user[i];
4617 if (open_match(perm, host, port)) {
4624 if (pset->num_permitted_admin > 0) {
4626 for (i = 0; i < pset->num_permitted_admin; i++) {
4627 perm = &pset->permitted_admin[i];
4628 if (open_match(perm, host, port)) {
4635 if (!permit || !permit_adm) {
4636 logit("Received request from %.100s port %d to connect to "
4637 "host %.100s port %d, but the request was denied.",
4638 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4640 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4644 memset(&cctx, 0, sizeof(cctx));
4645 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4646 &cctx, reason, errmsg);
4648 channel_connect_ctx_free(&cctx);
4652 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4653 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4654 c->host_port = port;
4655 c->path = xstrdup(host);
4656 c->connect_ctx = cctx;
4661 /* Check if connecting to that path is permitted and connect. */
4663 channel_connect_to_path(struct ssh *ssh, const char *path,
4664 char *ctype, char *rname)
4666 struct ssh_channels *sc = ssh->chanctxt;
4667 struct permission_set *pset = &sc->local_perms;
4668 u_int i, permit, permit_adm = 1;
4669 struct permission *perm;
4671 permit = pset->all_permitted;
4673 for (i = 0; i < pset->num_permitted_user; i++) {
4674 perm = &pset->permitted_user[i];
4675 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4682 if (pset->num_permitted_admin > 0) {
4684 for (i = 0; i < pset->num_permitted_admin; i++) {
4685 perm = &pset->permitted_admin[i];
4686 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4693 if (!permit || !permit_adm) {
4694 logit("Received request to connect to path %.100s, "
4695 "but the request was denied.", path);
4698 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4702 channel_send_window_changes(struct ssh *ssh)
4704 struct ssh_channels *sc = ssh->chanctxt;
4709 for (i = 0; i < sc->channels_alloc; i++) {
4710 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4711 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4713 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4715 channel_request_start(ssh, i, "window-change", 0);
4716 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4717 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4718 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4719 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4720 (r = sshpkt_send(ssh)) != 0)
4721 fatal_fr(r, "channel %u; send window-change", i);
4725 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4727 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4732 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4733 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4738 * We need to open the channel before we have a FD,
4739 * so that we can get SOCKS header from peer.
4741 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4742 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4743 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4744 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4745 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4746 fatal_fr(r, "channel %i; confirm", c->self);
4750 /* Return CONNECTING socket to remote host:port or local socket path */
4752 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4754 struct ssh_channels *sc = ssh->chanctxt;
4755 struct permission_set *pset = &sc->local_perms;
4756 struct permission *perm;
4757 struct channel_connect cctx;
4758 u_int i, permit_adm = 1;
4761 if (pset->num_permitted_admin > 0) {
4763 for (i = 0; i < pset->num_permitted_admin; i++) {
4764 perm = &pset->permitted_admin[i];
4765 if (open_match(perm, c->path, c->host_port)) {
4772 debug_f("requested forward not permitted");
4776 memset(&cctx, 0, sizeof(cctx));
4777 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4778 NULL, &cctx, NULL, NULL);
4780 channel_connect_ctx_free(&cctx);
4782 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4783 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4784 c->connect_ctx = cctx;
4785 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4790 /* -- X11 forwarding */
4793 * Creates an internet domain socket for listening for X11 connections.
4794 * Returns 0 and a suitable display number for the DISPLAY variable
4795 * stored in display_numberp , or -1 if an error occurs.
4798 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4799 int x11_use_localhost, int single_connection,
4800 u_int *display_numberp, int **chanids)
4803 int display_number, sock;
4805 struct addrinfo hints, *ai, *aitop;
4806 char strport[NI_MAXSERV];
4807 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4809 if (chanids == NULL)
4812 for (display_number = x11_display_offset;
4813 display_number < MAX_DISPLAYS;
4815 port = 6000 + display_number;
4816 memset(&hints, 0, sizeof(hints));
4817 hints.ai_family = ssh->chanctxt->IPv4or6;
4818 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4819 hints.ai_socktype = SOCK_STREAM;
4820 snprintf(strport, sizeof strport, "%d", port);
4821 if ((gaierr = getaddrinfo(NULL, strport,
4822 &hints, &aitop)) != 0) {
4823 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4826 for (ai = aitop; ai; ai = ai->ai_next) {
4827 if (ai->ai_family != AF_INET &&
4828 ai->ai_family != AF_INET6)
4830 sock = socket(ai->ai_family, ai->ai_socktype,
4833 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4835 && (errno != EPFNOSUPPORT)
4838 error("socket: %.100s", strerror(errno));
4839 freeaddrinfo(aitop);
4842 debug("x11_create_display_inet: Socket family %d not supported",
4847 if (ai->ai_family == AF_INET6)
4848 sock_set_v6only(sock);
4849 if (x11_use_localhost)
4850 set_reuseaddr(sock);
4851 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4852 debug2_f("bind port %d: %.100s", port,
4855 for (n = 0; n < num_socks; n++)
4860 socks[num_socks++] = sock;
4861 if (num_socks == NUM_SOCKS)
4864 freeaddrinfo(aitop);
4868 if (display_number >= MAX_DISPLAYS) {
4869 error("Failed to allocate internet-domain X11 display socket.");
4872 /* Start listening for connections on the socket. */
4873 for (n = 0; n < num_socks; n++) {
4875 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4876 error("listen: %.100s", strerror(errno));
4882 /* Allocate a channel for each socket. */
4883 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4884 for (n = 0; n < num_socks; n++) {
4886 nc = channel_new(ssh, "x11 listener",
4887 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4888 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4889 0, "X11 inet listener", 1);
4890 nc->single_connection = single_connection;
4891 (*chanids)[n] = nc->self;
4895 /* Return the display number for the DISPLAY environment variable. */
4896 *display_numberp = display_number;
4901 connect_local_xsocket_path(const char *pathname)
4904 struct sockaddr_un addr;
4906 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4908 error("socket: %.100s", strerror(errno));
4909 memset(&addr, 0, sizeof(addr));
4910 addr.sun_family = AF_UNIX;
4911 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4912 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4915 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4920 connect_local_xsocket(u_int dnr)
4923 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4924 return connect_local_xsocket_path(buf);
4929 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4933 if (strlcpy(path, display, pathlen) >= pathlen) {
4934 error("%s: display path too long", __func__);
4937 if (display[0] != '/')
4939 if (stat(path, &sbuf) == 0) {
4942 char *dot = strrchr(path, '.');
4945 if (stat(path, &sbuf) == 0) {
4955 x11_connect_display(struct ssh *ssh)
4957 u_int display_number;
4958 const char *display;
4959 char buf[1024], *cp;
4960 struct addrinfo hints, *ai, *aitop;
4961 char strport[NI_MAXSERV];
4962 int gaierr, sock = 0;
4964 /* Try to open a socket for the local X server. */
4965 display = getenv("DISPLAY");
4967 error("DISPLAY not set.");
4971 * Now we decode the value of the DISPLAY variable and make a
4972 * connection to the real X server.
4976 /* Check if display is a path to a socket (as set by launchd). */
4978 char path[PATH_MAX];
4980 if (is_path_to_xsocket(display, path, sizeof(path))) {
4981 debug("x11_connect_display: $DISPLAY is launchd");
4983 /* Create a socket. */
4984 sock = connect_local_xsocket_path(path);
4988 /* OK, we now have a connection to the display. */
4994 * Check if it is a unix domain socket. Unix domain displays are in
4995 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4997 if (strncmp(display, "unix:", 5) == 0 ||
4998 display[0] == ':') {
4999 /* Connect to the unix domain socket. */
5000 if (sscanf(strrchr(display, ':') + 1, "%u",
5001 &display_number) != 1) {
5002 error("Could not parse display number from DISPLAY: "
5006 /* Create a socket. */
5007 sock = connect_local_xsocket(display_number);
5011 /* OK, we now have a connection to the display. */
5015 * Connect to an inet socket. The DISPLAY value is supposedly
5016 * hostname:d[.s], where hostname may also be numeric IP address.
5018 strlcpy(buf, display, sizeof(buf));
5019 cp = strchr(buf, ':');
5021 error("Could not find ':' in DISPLAY: %.100s", display);
5026 * buf now contains the host name. But first we parse the
5029 if (sscanf(cp + 1, "%u", &display_number) != 1) {
5030 error("Could not parse display number from DISPLAY: %.100s",
5035 /* Look up the host address */
5036 memset(&hints, 0, sizeof(hints));
5037 hints.ai_family = ssh->chanctxt->IPv4or6;
5038 hints.ai_socktype = SOCK_STREAM;
5039 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5040 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5041 error("%.100s: unknown host. (%s)", buf,
5042 ssh_gai_strerror(gaierr));
5045 for (ai = aitop; ai; ai = ai->ai_next) {
5046 /* Create a socket. */
5047 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5049 debug2("socket: %.100s", strerror(errno));
5052 /* Connect it to the display. */
5053 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5054 debug2("connect %.100s port %u: %.100s", buf,
5055 6000 + display_number, strerror(errno));
5062 freeaddrinfo(aitop);
5064 error("connect %.100s port %u: %.100s", buf,
5065 6000 + display_number, strerror(errno));
5073 * Requests forwarding of X11 connections, generates fake authentication
5074 * data, and enables authentication spoofing.
5075 * This should be called in the client only.
5078 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5079 const char *disp, const char *proto, const char *data, int want_reply)
5081 struct ssh_channels *sc = ssh->chanctxt;
5082 u_int data_len = (u_int) strlen(data) / 2;
5086 int r, screen_number;
5088 if (sc->x11_saved_display == NULL)
5089 sc->x11_saved_display = xstrdup(disp);
5090 else if (strcmp(disp, sc->x11_saved_display) != 0) {
5091 error("x11_request_forwarding_with_spoofing: different "
5092 "$DISPLAY already forwarded");
5096 cp = strchr(disp, ':');
5098 cp = strchr(cp, '.');
5100 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5104 if (sc->x11_saved_proto == NULL) {
5105 /* Save protocol name. */
5106 sc->x11_saved_proto = xstrdup(proto);
5108 /* Extract real authentication data. */
5109 sc->x11_saved_data = xmalloc(data_len);
5110 for (i = 0; i < data_len; i++) {
5111 if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5112 fatal("x11_request_forwarding: bad "
5113 "authentication data: %.100s", data);
5115 sc->x11_saved_data[i] = value;
5117 sc->x11_saved_data_len = data_len;
5119 /* Generate fake data of the same length. */
5120 sc->x11_fake_data = xmalloc(data_len);
5121 arc4random_buf(sc->x11_fake_data, data_len);
5122 sc->x11_fake_data_len = data_len;
5125 /* Convert the fake data into hex. */
5126 new_data = tohex(sc->x11_fake_data, data_len);
5128 /* Send the request packet. */
5129 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5130 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5131 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5132 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5133 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5134 (r = sshpkt_send(ssh)) != 0 ||
5135 (r = ssh_packet_write_wait(ssh)) != 0)
5136 fatal_fr(r, "send x11-req");