1 /* $OpenBSD: channels.c,v 1.407 2021/05/19 01:24:05 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>
70 #include "openbsd-compat/sys-queue.h"
84 #include "pathnames.h"
87 /* -- agent forwarding */
90 /* -- tcp forwarding */
91 /* special-case port number meaning allow any port */
92 #define FWD_PERMIT_ANY_PORT 0
94 /* special-case wildcard meaning allow any host */
95 #define FWD_PERMIT_ANY_HOST "*"
97 /* -- X11 forwarding */
98 /* Maximum number of fake X11 displays to try. */
99 #define MAX_DISPLAYS 1000
101 /* Per-channel callback for pre/post select() actions */
102 typedef void chan_fn(struct ssh *, Channel *c,
103 fd_set *readset, fd_set *writeset);
106 * Data structure for storing which hosts are permitted for forward requests.
107 * The local sides of any remote forwards are stored in this array to prevent
108 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109 * network (which might be behind a firewall).
111 /* XXX: streamlocal wants a path instead of host:port */
112 /* Overload host_to_connect; we could just make this match Forward */
113 /* XXX - can we use listen_host instead of listen_path? */
115 char *host_to_connect; /* Connect to 'host'. */
116 int port_to_connect; /* Connect to 'port'. */
117 char *listen_host; /* Remote side should listen address. */
118 char *listen_path; /* Remote side should listen path. */
119 int listen_port; /* Remote side should listen port. */
120 Channel *downstream; /* Downstream mux*/
124 * Stores the forwarding permission state for a single direction (local or
127 struct permission_set {
129 * List of all local permitted host/port pairs to allow for the
132 u_int num_permitted_user;
133 struct permission *permitted_user;
136 * List of all permitted host/port pairs to allow for the admin.
138 u_int num_permitted_admin;
139 struct permission *permitted_admin;
142 * If this is true, all opens/listens are permitted. This is the
143 * case on the server on which we have to trust the client anyway,
144 * and the user could do anything after logging in.
149 /* Master structure for channels state */
150 struct ssh_channels {
152 * Pointer to an array containing all allocated channels. The array
153 * is dynamically extended as needed.
158 * Size of the channel array. All slots of the array must always be
159 * initialized (at least the type field); unused slots set to NULL
161 u_int channels_alloc;
164 * Maximum file descriptor value used in any of the channels. This is
165 * updated in channel_new.
170 * 'channel_pre*' are called just before select() to add any bits
171 * relevant to channels in the select bitmasks.
173 * 'channel_post*': perform any appropriate operations for
174 * channels which have events pending.
176 chan_fn **channel_pre;
177 chan_fn **channel_post;
179 /* -- tcp forwarding */
180 struct permission_set local_perms;
181 struct permission_set remote_perms;
183 /* -- X11 forwarding */
185 /* Saved X11 local (client) display. */
186 char *x11_saved_display;
188 /* Saved X11 authentication protocol name. */
189 char *x11_saved_proto;
191 /* Saved X11 authentication data. This is the real data. */
192 char *x11_saved_data;
193 u_int x11_saved_data_len;
195 /* Deadline after which all X11 connections are refused */
196 u_int x11_refuse_time;
199 * Fake X11 authentication data. This is what the server will be
200 * sending us; we should replace any occurrences of this by the
203 u_char *x11_fake_data;
204 u_int x11_fake_data_len;
206 /* AF_UNSPEC or AF_INET or AF_INET6 */
211 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212 static const char *channel_rfwd_bind_host(const char *listen_host);
214 /* non-blocking connect helpers */
215 static int connect_next(struct channel_connect *);
216 static void channel_connect_ctx_free(struct channel_connect *);
217 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218 static int rdynamic_connect_finish(struct ssh *, Channel *);
221 static void channel_handler_init(struct ssh_channels *sc);
223 /* -- channel core */
226 channel_init_channels(struct ssh *ssh)
228 struct ssh_channels *sc;
230 if ((sc = calloc(1, sizeof(*sc))) == NULL)
231 fatal_f("allocation failed");
232 sc->channels_alloc = 10;
233 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
234 sc->IPv4or6 = AF_UNSPEC;
235 channel_handler_init(sc);
241 channel_by_id(struct ssh *ssh, int id)
245 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
246 logit_f("%d: bad id", id);
249 c = ssh->chanctxt->channels[id];
251 logit_f("%d: bad id: channel free", id);
258 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
263 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
264 c = ssh->chanctxt->channels[i];
265 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
272 * Returns the channel if it is allowed to receive protocol messages.
273 * Private channels, like listening sockets, may not receive messages.
276 channel_lookup(struct ssh *ssh, int id)
280 if ((c = channel_by_id(ssh, id)) == NULL)
284 case SSH_CHANNEL_X11_OPEN:
285 case SSH_CHANNEL_LARVAL:
286 case SSH_CHANNEL_CONNECTING:
287 case SSH_CHANNEL_DYNAMIC:
288 case SSH_CHANNEL_RDYNAMIC_OPEN:
289 case SSH_CHANNEL_RDYNAMIC_FINISH:
290 case SSH_CHANNEL_OPENING:
291 case SSH_CHANNEL_OPEN:
292 case SSH_CHANNEL_ABANDONED:
293 case SSH_CHANNEL_MUX_PROXY:
296 logit("Non-public channel %d, type %d.", id, c->type);
301 * Register filedescriptors for a channel, used when allocating a channel or
302 * when the channel consumer/producer is ready, e.g. shell exec'd
305 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
306 int extusage, int nonblock, int is_tty)
308 struct ssh_channels *sc = ssh->chanctxt;
310 /* Update the maximum file descriptor value. */
311 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
312 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
313 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
316 fcntl(rfd, F_SETFD, FD_CLOEXEC);
317 if (wfd != -1 && wfd != rfd)
318 fcntl(wfd, F_SETFD, FD_CLOEXEC);
319 if (efd != -1 && efd != rfd && efd != wfd)
320 fcntl(efd, F_SETFD, FD_CLOEXEC);
324 c->sock = (rfd == wfd) ? rfd : -1;
326 c->extended_usage = extusage;
328 if ((c->isatty = is_tty) != 0)
329 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
331 /* XXX: Later AIX versions can't push as much data to tty */
332 c->wfd_isatty = is_tty || isatty(c->wfd);
335 /* enable nonblocking mode */
336 c->restore_block = 0;
337 if (nonblock == CHANNEL_NONBLOCK_STDIO) {
339 * Special handling for stdio file descriptors: do not set
340 * non-blocking mode if they are TTYs. Otherwise prepare to
341 * restore their blocking state on exit to avoid interfering
342 * with other programs that follow.
344 if (rfd != -1 && !isatty(rfd) && fcntl(rfd, F_GETFL) == 0) {
345 c->restore_block |= CHANNEL_RESTORE_RFD;
348 if (wfd != -1 && !isatty(wfd) && fcntl(wfd, F_GETFL) == 0) {
349 c->restore_block |= CHANNEL_RESTORE_WFD;
352 if (efd != -1 && !isatty(efd) && fcntl(efd, F_GETFL) == 0) {
353 c->restore_block |= CHANNEL_RESTORE_EFD;
356 } else if (nonblock) {
367 * Allocate a new channel object and set its type and socket. This will cause
368 * remote_name to be freed.
371 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
372 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
374 struct ssh_channels *sc = ssh->chanctxt;
379 /* Try to find a free slot where to put the new channel. */
380 for (i = 0; i < sc->channels_alloc; i++) {
381 if (sc->channels[i] == NULL) {
382 /* Found a free slot. */
387 if (i >= sc->channels_alloc) {
389 * There are no free slots. Take last+1 slot and expand
392 found = sc->channels_alloc;
393 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
394 fatal_f("internal error: channels_alloc %d too big",
396 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
397 sc->channels_alloc + 10, sizeof(*sc->channels));
398 sc->channels_alloc += 10;
399 debug2("channel: expanding %d", sc->channels_alloc);
401 /* Initialize and return new channel. */
402 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
403 if ((c->input = sshbuf_new()) == NULL ||
404 (c->output = sshbuf_new()) == NULL ||
405 (c->extended = sshbuf_new()) == NULL)
406 fatal_f("sshbuf_new failed");
407 if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
408 fatal_fr(r, "sshbuf_set_max_size");
409 c->ostate = CHAN_OUTPUT_OPEN;
410 c->istate = CHAN_INPUT_OPEN;
411 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
415 c->local_window = window;
416 c->local_window_max = window;
417 c->local_maxpacket = maxpack;
418 c->remote_name = xstrdup(remote_name);
420 c->delayed = 1; /* prevent call to channel_post handler */
421 TAILQ_INIT(&c->status_confirms);
422 debug("channel %d: new [%s]", found, remote_name);
427 channel_find_maxfd(struct ssh_channels *sc)
433 for (i = 0; i < sc->channels_alloc; i++) {
436 max = MAXIMUM(max, c->rfd);
437 max = MAXIMUM(max, c->wfd);
438 max = MAXIMUM(max, c->efd);
441 sc->channel_max_fd = max;
445 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
447 struct ssh_channels *sc = ssh->chanctxt;
453 if ((*fdp == c->rfd && (c->restore_block & CHANNEL_RESTORE_RFD) != 0) ||
454 (*fdp == c->wfd && (c->restore_block & CHANNEL_RESTORE_WFD) != 0) ||
455 (*fdp == c->efd && (c->restore_block & CHANNEL_RESTORE_EFD) != 0))
456 (void)fcntl(*fdp, F_SETFL, 0); /* restore blocking */
460 if (fd == sc->channel_max_fd)
461 channel_find_maxfd(sc);
465 /* Close all channel fd/socket. */
467 channel_close_fds(struct ssh *ssh, Channel *c)
469 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
471 channel_close_fd(ssh, c, &c->sock);
473 channel_close_fd(ssh, c, &c->rfd);
474 if (wfd != sock && wfd != rfd)
475 channel_close_fd(ssh, c, &c->wfd);
476 if (efd != sock && efd != rfd && efd != wfd)
477 channel_close_fd(ssh, c, &c->efd);
481 fwd_perm_clear(struct permission *perm)
483 free(perm->host_to_connect);
484 free(perm->listen_host);
485 free(perm->listen_path);
486 memset(perm, 0, sizeof(*perm));
489 /* Returns an printable name for the specified forwarding permission list */
491 fwd_ident(int who, int where)
493 if (who == FORWARD_ADM) {
494 if (where == FORWARD_LOCAL)
495 return "admin local";
496 else if (where == FORWARD_REMOTE)
497 return "admin remote";
498 } else if (who == FORWARD_USER) {
499 if (where == FORWARD_LOCAL)
501 else if (where == FORWARD_REMOTE)
502 return "user remote";
504 fatal("Unknown forward permission list %d/%d", who, where);
507 /* Returns the forwarding permission list for the specified direction */
508 static struct permission_set *
509 permission_set_get(struct ssh *ssh, int where)
511 struct ssh_channels *sc = ssh->chanctxt;
515 return &sc->local_perms;
518 return &sc->remote_perms;
521 fatal_f("invalid forwarding direction %d", where);
525 /* Returns pointers to the specified forwarding list and its element count */
527 permission_set_get_array(struct ssh *ssh, int who, int where,
528 struct permission ***permpp, u_int **npermpp)
530 struct permission_set *pset = permission_set_get(ssh, where);
534 *permpp = &pset->permitted_user;
535 *npermpp = &pset->num_permitted_user;
538 *permpp = &pset->permitted_admin;
539 *npermpp = &pset->num_permitted_admin;
542 fatal_f("invalid forwarding client %d", who);
546 /* Adds an entry to the spcified forwarding list */
548 permission_set_add(struct ssh *ssh, int who, int where,
549 const char *host_to_connect, int port_to_connect,
550 const char *listen_host, const char *listen_path, int listen_port,
553 struct permission **permp;
556 permission_set_get_array(ssh, who, where, &permp, &npermp);
558 if (*npermp >= INT_MAX)
559 fatal_f("%s overflow", fwd_ident(who, where));
561 *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
563 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
564 (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
565 (*permp)[n].port_to_connect = port_to_connect;
566 (*permp)[n].listen_host = MAYBE_DUP(listen_host);
567 (*permp)[n].listen_path = MAYBE_DUP(listen_path);
568 (*permp)[n].listen_port = listen_port;
569 (*permp)[n].downstream = downstream;
575 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
577 struct ssh_channels *sc = ssh->chanctxt;
578 struct permission_set *pset = &sc->local_perms;
579 struct permission *perm;
583 for (i = 0; i < pset->num_permitted_user; i++) {
584 perm = &pset->permitted_user[i];
585 if (perm->downstream != c)
588 /* cancel on the server, since mux client is gone */
589 debug("channel %d: cleanup remote forward for %s:%u",
590 c->self, perm->listen_host, perm->listen_port);
591 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
592 (r = sshpkt_put_cstring(ssh,
593 "cancel-tcpip-forward")) != 0 ||
594 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
595 (r = sshpkt_put_cstring(ssh,
596 channel_rfwd_bind_host(perm->listen_host))) != 0 ||
597 (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
598 (r = sshpkt_send(ssh)) != 0) {
599 fatal_fr(r, "channel %i", c->self);
601 fwd_perm_clear(perm); /* unregister */
605 /* Free the channel and close its fd/socket. */
607 channel_free(struct ssh *ssh, Channel *c)
609 struct ssh_channels *sc = ssh->chanctxt;
613 struct channel_confirm *cc;
615 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
616 if ((other = sc->channels[i]) == NULL)
619 /* detach from mux client and prepare for closing */
620 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
621 other->type == SSH_CHANNEL_MUX_PROXY &&
622 other->mux_ctx == c) {
623 other->mux_ctx = NULL;
624 other->type = SSH_CHANNEL_OPEN;
625 other->istate = CHAN_INPUT_CLOSED;
626 other->ostate = CHAN_OUTPUT_CLOSED;
629 debug("channel %d: free: %s, nchannels %u", c->self,
630 c->remote_name ? c->remote_name : "???", n);
632 if (c->type == SSH_CHANNEL_MUX_CLIENT)
633 mux_remove_remote_forwardings(ssh, c);
634 else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
639 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
640 s = channel_open_message(ssh);
641 debug3("channel %d: status: %s", c->self, s);
645 channel_close_fds(ssh, c);
646 sshbuf_free(c->input);
647 sshbuf_free(c->output);
648 sshbuf_free(c->extended);
649 c->input = c->output = c->extended = NULL;
650 free(c->remote_name);
651 c->remote_name = NULL;
654 free(c->listening_addr);
655 c->listening_addr = NULL;
656 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
657 if (cc->abandon_cb != NULL)
658 cc->abandon_cb(ssh, c, cc->ctx);
659 TAILQ_REMOVE(&c->status_confirms, cc, entry);
660 freezero(cc, sizeof(*cc));
662 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
663 c->filter_cleanup(ssh, c->self, c->filter_ctx);
664 sc->channels[c->self] = NULL;
665 freezero(c, sizeof(*c));
669 channel_free_all(struct ssh *ssh)
672 struct ssh_channels *sc = ssh->chanctxt;
674 for (i = 0; i < sc->channels_alloc; i++)
675 if (sc->channels[i] != NULL)
676 channel_free(ssh, sc->channels[i]);
680 sc->channels_alloc = 0;
681 sc->channel_max_fd = 0;
683 free(sc->x11_saved_display);
684 sc->x11_saved_display = NULL;
686 free(sc->x11_saved_proto);
687 sc->x11_saved_proto = NULL;
689 free(sc->x11_saved_data);
690 sc->x11_saved_data = NULL;
691 sc->x11_saved_data_len = 0;
693 free(sc->x11_fake_data);
694 sc->x11_fake_data = NULL;
695 sc->x11_fake_data_len = 0;
699 * Closes the sockets/fds of all channels. This is used to close extra file
700 * descriptors after a fork.
703 channel_close_all(struct ssh *ssh)
707 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
708 if (ssh->chanctxt->channels[i] != NULL)
709 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
713 * Stop listening to channels.
716 channel_stop_listening(struct ssh *ssh)
721 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
722 c = ssh->chanctxt->channels[i];
725 case SSH_CHANNEL_AUTH_SOCKET:
726 case SSH_CHANNEL_PORT_LISTENER:
727 case SSH_CHANNEL_RPORT_LISTENER:
728 case SSH_CHANNEL_X11_LISTENER:
729 case SSH_CHANNEL_UNIX_LISTENER:
730 case SSH_CHANNEL_RUNIX_LISTENER:
731 channel_close_fd(ssh, c, &c->sock);
732 channel_free(ssh, c);
740 * Returns true if no channel has too much buffered data, and false if one or
741 * more channel is overfull.
744 channel_not_very_much_buffered_data(struct ssh *ssh)
747 u_int maxsize = ssh_packet_get_maxsize(ssh);
750 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
751 c = ssh->chanctxt->channels[i];
752 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
754 if (sshbuf_len(c->output) > maxsize) {
755 debug2("channel %d: big output buffer %zu > %u",
756 c->self, sshbuf_len(c->output), maxsize);
763 /* Returns true if any channel is still open. */
765 channel_still_open(struct ssh *ssh)
770 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
771 c = ssh->chanctxt->channels[i];
775 case SSH_CHANNEL_X11_LISTENER:
776 case SSH_CHANNEL_PORT_LISTENER:
777 case SSH_CHANNEL_RPORT_LISTENER:
778 case SSH_CHANNEL_MUX_LISTENER:
779 case SSH_CHANNEL_CLOSED:
780 case SSH_CHANNEL_AUTH_SOCKET:
781 case SSH_CHANNEL_DYNAMIC:
782 case SSH_CHANNEL_RDYNAMIC_OPEN:
783 case SSH_CHANNEL_CONNECTING:
784 case SSH_CHANNEL_ZOMBIE:
785 case SSH_CHANNEL_ABANDONED:
786 case SSH_CHANNEL_UNIX_LISTENER:
787 case SSH_CHANNEL_RUNIX_LISTENER:
789 case SSH_CHANNEL_LARVAL:
791 case SSH_CHANNEL_OPENING:
792 case SSH_CHANNEL_OPEN:
793 case SSH_CHANNEL_RDYNAMIC_FINISH:
794 case SSH_CHANNEL_X11_OPEN:
795 case SSH_CHANNEL_MUX_CLIENT:
796 case SSH_CHANNEL_MUX_PROXY:
799 fatal_f("bad channel type %d", c->type);
806 /* Returns the id of an open channel suitable for keepaliving */
808 channel_find_open(struct ssh *ssh)
813 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
814 c = ssh->chanctxt->channels[i];
815 if (c == NULL || !c->have_remote_id)
818 case SSH_CHANNEL_CLOSED:
819 case SSH_CHANNEL_DYNAMIC:
820 case SSH_CHANNEL_RDYNAMIC_OPEN:
821 case SSH_CHANNEL_RDYNAMIC_FINISH:
822 case SSH_CHANNEL_X11_LISTENER:
823 case SSH_CHANNEL_PORT_LISTENER:
824 case SSH_CHANNEL_RPORT_LISTENER:
825 case SSH_CHANNEL_MUX_LISTENER:
826 case SSH_CHANNEL_MUX_CLIENT:
827 case SSH_CHANNEL_MUX_PROXY:
828 case SSH_CHANNEL_OPENING:
829 case SSH_CHANNEL_CONNECTING:
830 case SSH_CHANNEL_ZOMBIE:
831 case SSH_CHANNEL_ABANDONED:
832 case SSH_CHANNEL_UNIX_LISTENER:
833 case SSH_CHANNEL_RUNIX_LISTENER:
835 case SSH_CHANNEL_LARVAL:
836 case SSH_CHANNEL_AUTH_SOCKET:
837 case SSH_CHANNEL_OPEN:
838 case SSH_CHANNEL_X11_OPEN:
841 fatal_f("bad channel type %d", c->type);
848 /* Returns the state of the channel's extended usage flag */
850 channel_format_extended_usage(const Channel *c)
855 switch (c->extended_usage) {
856 case CHAN_EXTENDED_WRITE:
858 case CHAN_EXTENDED_READ:
860 case CHAN_EXTENDED_IGNORE:
868 channel_format_status(const Channel *c)
872 xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
873 "fd %d/%d/%d sock %d cc %d",
875 c->have_remote_id ? "r" : "nr", c->remote_id,
876 c->istate, sshbuf_len(c->input),
877 c->ostate, sshbuf_len(c->output),
878 channel_format_extended_usage(c), sshbuf_len(c->extended),
879 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
884 * Returns a message describing the currently open forwarded connections,
885 * suitable for sending to the client. The message contains crlf pairs for
889 channel_open_message(struct ssh *ssh)
897 if ((buf = sshbuf_new()) == NULL)
898 fatal_f("sshbuf_new");
899 if ((r = sshbuf_putf(buf,
900 "The following connections are open:\r\n")) != 0)
901 fatal_fr(r, "sshbuf_putf");
902 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
903 c = ssh->chanctxt->channels[i];
907 case SSH_CHANNEL_X11_LISTENER:
908 case SSH_CHANNEL_PORT_LISTENER:
909 case SSH_CHANNEL_RPORT_LISTENER:
910 case SSH_CHANNEL_CLOSED:
911 case SSH_CHANNEL_AUTH_SOCKET:
912 case SSH_CHANNEL_ZOMBIE:
913 case SSH_CHANNEL_ABANDONED:
914 case SSH_CHANNEL_MUX_LISTENER:
915 case SSH_CHANNEL_UNIX_LISTENER:
916 case SSH_CHANNEL_RUNIX_LISTENER:
918 case SSH_CHANNEL_LARVAL:
919 case SSH_CHANNEL_OPENING:
920 case SSH_CHANNEL_CONNECTING:
921 case SSH_CHANNEL_DYNAMIC:
922 case SSH_CHANNEL_RDYNAMIC_OPEN:
923 case SSH_CHANNEL_RDYNAMIC_FINISH:
924 case SSH_CHANNEL_OPEN:
925 case SSH_CHANNEL_X11_OPEN:
926 case SSH_CHANNEL_MUX_PROXY:
927 case SSH_CHANNEL_MUX_CLIENT:
928 cp = channel_format_status(c);
929 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
930 c->self, c->remote_name, cp)) != 0) {
932 fatal_fr(r, "sshbuf_putf");
937 fatal_f("bad channel type %d", c->type);
941 if ((ret = sshbuf_dup_string(buf)) == NULL)
942 fatal_f("sshbuf_dup_string");
948 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
952 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
953 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
954 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
955 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
956 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
957 fatal_r(r, "%s: channel %i: open", where, c->self);
962 channel_send_open(struct ssh *ssh, int id)
964 Channel *c = channel_lookup(ssh, id);
968 logit("channel_send_open: %d: bad id", id);
971 debug2("channel %d: send open", id);
972 open_preamble(ssh, __func__, c, c->ctype);
973 if ((r = sshpkt_send(ssh)) != 0)
974 fatal_fr(r, "channel %i", c->self);
978 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
980 Channel *c = channel_lookup(ssh, id);
984 logit_f("%d: unknown channel id", id);
987 if (!c->have_remote_id)
988 fatal_f("channel %d: no remote id", c->self);
990 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
991 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
992 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
993 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
994 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
995 fatal_fr(r, "channel %i", c->self);
1000 channel_register_status_confirm(struct ssh *ssh, int id,
1001 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1003 struct channel_confirm *cc;
1006 if ((c = channel_lookup(ssh, id)) == NULL)
1007 fatal_f("%d: bad id", id);
1009 cc = xcalloc(1, sizeof(*cc));
1011 cc->abandon_cb = abandon_cb;
1013 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1017 channel_register_open_confirm(struct ssh *ssh, int id,
1018 channel_open_fn *fn, void *ctx)
1020 Channel *c = channel_lookup(ssh, id);
1023 logit_f("%d: bad id", id);
1026 c->open_confirm = fn;
1027 c->open_confirm_ctx = ctx;
1031 channel_register_cleanup(struct ssh *ssh, int id,
1032 channel_callback_fn *fn, int do_close)
1034 Channel *c = channel_by_id(ssh, id);
1037 logit_f("%d: bad id", id);
1040 c->detach_user = fn;
1041 c->detach_close = do_close;
1045 channel_cancel_cleanup(struct ssh *ssh, int id)
1047 Channel *c = channel_by_id(ssh, id);
1050 logit_f("%d: bad id", id);
1053 c->detach_user = NULL;
1054 c->detach_close = 0;
1058 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1059 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1061 Channel *c = channel_lookup(ssh, id);
1064 logit_f("%d: bad id", id);
1067 c->input_filter = ifn;
1068 c->output_filter = ofn;
1069 c->filter_ctx = ctx;
1070 c->filter_cleanup = cfn;
1074 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1075 int extusage, int nonblock, int is_tty, u_int window_max)
1077 Channel *c = channel_lookup(ssh, id);
1080 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1081 fatal("channel_activate for non-larval channel %d.", id);
1082 if (!c->have_remote_id)
1083 fatal_f("channel %d: no remote id", c->self);
1085 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1086 c->type = SSH_CHANNEL_OPEN;
1087 c->local_window = c->local_window_max = window_max;
1089 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1090 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1091 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1092 (r = sshpkt_send(ssh)) != 0)
1093 fatal_fr(r, "channel %i", c->self);
1097 channel_pre_listener(struct ssh *ssh, Channel *c,
1098 fd_set *readset, fd_set *writeset)
1100 FD_SET(c->sock, readset);
1104 channel_pre_connecting(struct ssh *ssh, Channel *c,
1105 fd_set *readset, fd_set *writeset)
1107 debug3("channel %d: waiting for connection", c->self);
1108 FD_SET(c->sock, writeset);
1112 channel_pre_open(struct ssh *ssh, Channel *c,
1113 fd_set *readset, fd_set *writeset)
1115 if (c->istate == CHAN_INPUT_OPEN &&
1116 c->remote_window > 0 &&
1117 sshbuf_len(c->input) < c->remote_window &&
1118 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1119 FD_SET(c->rfd, readset);
1120 if (c->ostate == CHAN_OUTPUT_OPEN ||
1121 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1122 if (sshbuf_len(c->output) > 0) {
1123 FD_SET(c->wfd, writeset);
1124 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1125 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1126 debug2("channel %d: "
1127 "obuf_empty delayed efd %d/(%zu)", c->self,
1128 c->efd, sshbuf_len(c->extended));
1130 chan_obuf_empty(ssh, c);
1133 /** XXX check close conditions, too */
1134 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1135 c->ostate == CHAN_OUTPUT_CLOSED)) {
1136 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1137 sshbuf_len(c->extended) > 0)
1138 FD_SET(c->efd, writeset);
1139 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1140 (c->extended_usage == CHAN_EXTENDED_READ ||
1141 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1142 sshbuf_len(c->extended) < c->remote_window)
1143 FD_SET(c->efd, readset);
1145 /* XXX: What about efd? races? */
1149 * This is a special state for X11 authentication spoofing. An opened X11
1150 * connection (when authentication spoofing is being done) remains in this
1151 * state until the first packet has been completely read. The authentication
1152 * data in that packet is then substituted by the real data if it matches the
1153 * fake data, and the channel is put into normal mode.
1154 * XXX All this happens at the client side.
1155 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1158 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1160 struct ssh_channels *sc = ssh->chanctxt;
1162 u_int proto_len, data_len;
1164 /* Is this being called after the refusal deadline? */
1165 if (sc->x11_refuse_time != 0 &&
1166 (u_int)monotime() >= sc->x11_refuse_time) {
1167 verbose("Rejected X11 connection after ForwardX11Timeout "
1172 /* Check if the fixed size part of the packet is in buffer. */
1173 if (sshbuf_len(b) < 12)
1176 /* Parse the lengths of variable-length fields. */
1177 ucp = sshbuf_mutable_ptr(b);
1178 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1179 proto_len = 256 * ucp[6] + ucp[7];
1180 data_len = 256 * ucp[8] + ucp[9];
1181 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1182 proto_len = ucp[6] + 256 * ucp[7];
1183 data_len = ucp[8] + 256 * ucp[9];
1185 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1190 /* Check if the whole packet is in buffer. */
1192 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1195 /* Check if authentication protocol matches. */
1196 if (proto_len != strlen(sc->x11_saved_proto) ||
1197 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1198 debug2("X11 connection uses different authentication protocol.");
1201 /* Check if authentication data matches our fake data. */
1202 if (data_len != sc->x11_fake_data_len ||
1203 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1204 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1205 debug2("X11 auth data does not match fake data.");
1208 /* Check fake data length */
1209 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1210 error("X11 fake_data_len %d != saved_data_len %d",
1211 sc->x11_fake_data_len, sc->x11_saved_data_len);
1215 * Received authentication protocol and data match
1216 * our fake data. Substitute the fake data with real
1219 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1220 sc->x11_saved_data, sc->x11_saved_data_len);
1225 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1226 fd_set *readset, fd_set *writeset)
1228 int ret = x11_open_helper(ssh, c->output);
1230 /* c->force_drain = 1; */
1233 c->type = SSH_CHANNEL_OPEN;
1234 channel_pre_open(ssh, c, readset, writeset);
1235 } else if (ret == -1) {
1236 logit("X11 connection rejected because of wrong authentication.");
1237 debug2("X11 rejected %d i%d/o%d",
1238 c->self, c->istate, c->ostate);
1239 chan_read_failed(ssh, c);
1240 sshbuf_reset(c->input);
1241 chan_ibuf_empty(ssh, c);
1242 sshbuf_reset(c->output);
1243 chan_write_failed(ssh, c);
1244 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1249 channel_pre_mux_client(struct ssh *ssh,
1250 Channel *c, fd_set *readset, fd_set *writeset)
1252 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1253 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1254 FD_SET(c->rfd, readset);
1255 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1256 /* clear buffer immediately (discard any partial packet) */
1257 sshbuf_reset(c->input);
1258 chan_ibuf_empty(ssh, c);
1259 /* Start output drain. XXX just kill chan? */
1260 chan_rcvd_oclose(ssh, c);
1262 if (c->ostate == CHAN_OUTPUT_OPEN ||
1263 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1264 if (sshbuf_len(c->output) > 0)
1265 FD_SET(c->wfd, writeset);
1266 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1267 chan_obuf_empty(ssh, c);
1271 /* try to decode a socks4 header */
1273 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1277 u_int len, have, i, found, need;
1282 u_int16_t dest_port;
1283 struct in_addr dest_addr;
1287 debug2("channel %d: decode socks4", c->self);
1289 have = sshbuf_len(input);
1290 len = sizeof(s4_req);
1293 p = sshbuf_ptr(input);
1296 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1297 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1298 debug2("channel %d: socks4a request", c->self);
1299 /* ... and needs an extra string (the hostname) */
1302 /* Check for terminating NUL on the string(s) */
1303 for (found = 0, i = len; i < have; i++) {
1310 /* the peer is probably sending garbage */
1311 debug("channel %d: decode socks4: too long",
1318 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1319 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1320 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1321 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1322 debug_r(r, "channels %d: decode socks4", c->self);
1325 have = sshbuf_len(input);
1326 p = sshbuf_ptr(input);
1327 if (memchr(p, '\0', have) == NULL) {
1328 error("channel %d: decode socks4: unterminated user", c->self);
1332 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1333 len++; /* trailing '\0' */
1334 strlcpy(username, p, sizeof(username));
1335 if ((r = sshbuf_consume(input, len)) != 0)
1336 fatal_fr(r, "channel %d: consume", c->self);
1339 if (need == 1) { /* SOCKS4: one string */
1340 host = inet_ntoa(s4_req.dest_addr);
1341 c->path = xstrdup(host);
1342 } else { /* SOCKS4A: two strings */
1343 have = sshbuf_len(input);
1344 p = sshbuf_ptr(input);
1345 if (memchr(p, '\0', have) == NULL) {
1346 error("channel %d: decode socks4a: host not nul "
1347 "terminated", c->self);
1351 debug2("channel %d: decode socks4a: host %s/%d",
1353 len++; /* trailing '\0' */
1354 if (len > NI_MAXHOST) {
1355 error("channel %d: hostname \"%.100s\" too long",
1359 c->path = xstrdup(p);
1360 if ((r = sshbuf_consume(input, len)) != 0)
1361 fatal_fr(r, "channel %d: consume", c->self);
1363 c->host_port = ntohs(s4_req.dest_port);
1365 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1366 c->self, c->path, c->host_port, s4_req.command);
1368 if (s4_req.command != 1) {
1369 debug("channel %d: cannot handle: %s cn %d",
1370 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1373 s4_rsp.version = 0; /* vn: 0 for reply */
1374 s4_rsp.command = 90; /* cd: req granted */
1375 s4_rsp.dest_port = 0; /* ignored */
1376 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1377 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1378 fatal_fr(r, "channel %d: append reply", c->self);
1382 /* try to decode a socks5 header */
1383 #define SSH_SOCKS5_AUTHDONE 0x1000
1384 #define SSH_SOCKS5_NOAUTH 0x00
1385 #define SSH_SOCKS5_IPV4 0x01
1386 #define SSH_SOCKS5_DOMAIN 0x03
1387 #define SSH_SOCKS5_IPV6 0x04
1388 #define SSH_SOCKS5_CONNECT 0x01
1389 #define SSH_SOCKS5_SUCCESS 0x00
1392 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1394 /* XXX use get/put_u8 instead of trusting struct padding */
1401 u_int16_t dest_port;
1402 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1404 u_int have, need, i, found, nmethods, addrlen, af;
1407 debug2("channel %d: decode socks5", c->self);
1408 p = sshbuf_ptr(input);
1411 have = sshbuf_len(input);
1412 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1413 /* format: ver | nmethods | methods */
1417 if (have < nmethods + 2)
1419 /* look for method: "NO AUTHENTICATION REQUIRED" */
1420 for (found = 0, i = 2; i < nmethods + 2; i++) {
1421 if (p[i] == SSH_SOCKS5_NOAUTH) {
1427 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1431 if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1432 fatal_fr(r, "channel %d: consume", c->self);
1433 /* version, method */
1434 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1435 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1436 fatal_fr(r, "channel %d: append reply", c->self);
1437 c->flags |= SSH_SOCKS5_AUTHDONE;
1438 debug2("channel %d: socks5 auth done", c->self);
1439 return 0; /* need more */
1441 debug2("channel %d: socks5 post auth", c->self);
1442 if (have < sizeof(s5_req)+1)
1443 return 0; /* need more */
1444 memcpy(&s5_req, p, sizeof(s5_req));
1445 if (s5_req.version != 0x05 ||
1446 s5_req.command != SSH_SOCKS5_CONNECT ||
1447 s5_req.reserved != 0x00) {
1448 debug2("channel %d: only socks5 connect supported", c->self);
1451 switch (s5_req.atyp){
1452 case SSH_SOCKS5_IPV4:
1456 case SSH_SOCKS5_DOMAIN:
1457 addrlen = p[sizeof(s5_req)];
1460 case SSH_SOCKS5_IPV6:
1465 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1468 need = sizeof(s5_req) + addrlen + 2;
1469 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1473 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1474 fatal_fr(r, "channel %d: consume", c->self);
1475 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1476 /* host string length */
1477 if ((r = sshbuf_consume(input, 1)) != 0)
1478 fatal_fr(r, "channel %d: consume", c->self);
1480 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1481 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1482 debug_r(r, "channel %d: parse addr/port", c->self);
1485 dest_addr[addrlen] = '\0';
1488 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1489 if (addrlen >= NI_MAXHOST) {
1490 error("channel %d: dynamic request: socks5 hostname "
1491 "\"%.100s\" too long", c->self, dest_addr);
1494 c->path = xstrdup(dest_addr);
1496 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1498 c->path = xstrdup(ntop);
1500 c->host_port = ntohs(dest_port);
1502 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1503 c->self, c->path, c->host_port, s5_req.command);
1505 s5_rsp.version = 0x05;
1506 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1507 s5_rsp.reserved = 0; /* ignored */
1508 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1509 dest_port = 0; /* ignored */
1511 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1512 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1513 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1514 fatal_fr(r, "channel %d: append reply", c->self);
1519 channel_connect_stdio_fwd(struct ssh *ssh,
1520 const char *host_to_connect, u_short port_to_connect,
1521 int in, int out, int nonblock)
1525 debug_f("%s:%d", host_to_connect, port_to_connect);
1527 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1528 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1529 0, "stdio-forward", nonblock);
1531 c->path = xstrdup(host_to_connect);
1532 c->host_port = port_to_connect;
1533 c->listening_port = 0;
1536 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1537 port_open_helper(ssh, c, "direct-tcpip");
1542 /* dynamic port forwarding */
1544 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1545 fd_set *readset, fd_set *writeset)
1551 have = sshbuf_len(c->input);
1552 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1553 /* sshbuf_dump(c->input, stderr); */
1554 /* check if the fixed size part of the packet is in buffer. */
1557 FD_SET(c->sock, readset);
1560 /* try to guess the protocol */
1561 p = sshbuf_ptr(c->input);
1562 /* XXX sshbuf_peek_u8? */
1565 ret = channel_decode_socks4(c, c->input, c->output);
1568 ret = channel_decode_socks5(c, c->input, c->output);
1575 chan_mark_dead(ssh, c);
1576 } else if (ret == 0) {
1577 debug2("channel %d: pre_dynamic: need more", c->self);
1579 FD_SET(c->sock, readset);
1580 if (sshbuf_len(c->output))
1581 FD_SET(c->sock, writeset);
1583 /* switch to the next state */
1584 c->type = SSH_CHANNEL_OPENING;
1585 port_open_helper(ssh, c, "direct-tcpip");
1589 /* simulate read-error */
1591 rdynamic_close(struct ssh *ssh, Channel *c)
1593 c->type = SSH_CHANNEL_OPEN;
1594 chan_read_failed(ssh, c);
1595 sshbuf_reset(c->input);
1596 chan_ibuf_empty(ssh, c);
1597 sshbuf_reset(c->output);
1598 chan_write_failed(ssh, c);
1601 /* reverse dynamic port forwarding */
1603 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1609 have = sshbuf_len(c->output);
1610 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1611 /* sshbuf_dump(c->output, stderr); */
1613 if (c->flags & CHAN_EOF_RCVD) {
1614 if ((r = sshbuf_consume(c->output, have)) != 0)
1615 fatal_fr(r, "channel %d: consume", c->self);
1616 rdynamic_close(ssh, c);
1619 /* check if the fixed size part of the packet is in buffer. */
1622 /* try to guess the protocol */
1623 p = sshbuf_ptr(c->output);
1626 /* switch input/output for reverse forwarding */
1627 ret = channel_decode_socks4(c, c->output, c->input);
1630 ret = channel_decode_socks5(c, c->output, c->input);
1637 rdynamic_close(ssh, c);
1638 } else if (ret == 0) {
1639 debug2("channel %d: pre_rdynamic: need more", c->self);
1640 /* send socks request to peer */
1641 len = sshbuf_len(c->input);
1642 if (len > 0 && len < c->remote_window) {
1643 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1644 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1645 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1646 (r = sshpkt_send(ssh)) != 0) {
1647 fatal_fr(r, "channel %i: rdynamic", c->self);
1649 if ((r = sshbuf_consume(c->input, len)) != 0)
1650 fatal_fr(r, "channel %d: consume", c->self);
1651 c->remote_window -= len;
1653 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1654 /* the connect failed */
1655 rdynamic_close(ssh, c);
1659 /* This is our fake X11 server socket. */
1661 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1662 fd_set *readset, fd_set *writeset)
1665 struct sockaddr_storage addr;
1666 int r, newsock, oerrno, remote_port;
1668 char buf[16384], *remote_ipaddr;
1670 if (!FD_ISSET(c->sock, readset))
1673 debug("X11 connection requested.");
1674 addrlen = sizeof(addr);
1675 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1676 if (c->single_connection) {
1678 debug2("single_connection: closing X11 listener.");
1679 channel_close_fd(ssh, c, &c->sock);
1680 chan_mark_dead(ssh, c);
1683 if (newsock == -1) {
1684 if (errno != EINTR && errno != EWOULDBLOCK &&
1685 errno != ECONNABORTED)
1686 error("accept: %.100s", strerror(errno));
1687 if (errno == EMFILE || errno == ENFILE)
1688 c->notbefore = monotime() + 1;
1691 set_nodelay(newsock);
1692 remote_ipaddr = get_peer_ipaddr(newsock);
1693 remote_port = get_peer_port(newsock);
1694 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1695 remote_ipaddr, remote_port);
1697 nc = channel_new(ssh, "accepted x11 socket",
1698 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1699 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1700 open_preamble(ssh, __func__, nc, "x11");
1701 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1702 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1703 fatal_fr(r, "channel %i: reply", c->self);
1705 if ((r = sshpkt_send(ssh)) != 0)
1706 fatal_fr(r, "channel %i: send", c->self);
1707 free(remote_ipaddr);
1711 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1713 char *local_ipaddr = get_local_ipaddr(c->sock);
1714 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1715 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1716 int remote_port = get_peer_port(c->sock);
1719 if (remote_port == -1) {
1720 /* Fake addr/port to appease peers that validate it (Tectia) */
1721 free(remote_ipaddr);
1722 remote_ipaddr = xstrdup("127.0.0.1");
1723 remote_port = 65535;
1726 free(c->remote_name);
1727 xasprintf(&c->remote_name,
1728 "%s: listening port %d for %.100s port %d, "
1729 "connect from %.200s port %d to %.100s port %d",
1730 rtype, c->listening_port, c->path, c->host_port,
1731 remote_ipaddr, remote_port, local_ipaddr, local_port);
1733 open_preamble(ssh, __func__, c, rtype);
1734 if (strcmp(rtype, "direct-tcpip") == 0) {
1735 /* target host, port */
1736 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1737 (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1738 fatal_fr(r, "channel %i: reply", c->self);
1739 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1741 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1742 fatal_fr(r, "channel %i: reply", c->self);
1743 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1745 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1746 fatal_fr(r, "channel %i: reply", c->self);
1748 /* listen address, port */
1749 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1750 (r = sshpkt_put_u32(ssh, local_port)) != 0)
1751 fatal_fr(r, "channel %i: reply", c->self);
1753 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1754 /* reserved for future owner/mode info */
1755 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1756 fatal_fr(r, "channel %i: reply", c->self);
1758 /* originator host and port */
1759 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1760 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1761 fatal_fr(r, "channel %i: reply", c->self);
1763 if ((r = sshpkt_send(ssh)) != 0)
1764 fatal_fr(r, "channel %i: send", c->self);
1765 free(remote_ipaddr);
1770 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1772 ssh->chanctxt->x11_refuse_time = refuse_time;
1776 * This socket is listening for connections to a forwarded TCP/IP port.
1779 channel_post_port_listener(struct ssh *ssh, Channel *c,
1780 fd_set *readset, fd_set *writeset)
1783 struct sockaddr_storage addr;
1784 int newsock, nextstate;
1788 if (!FD_ISSET(c->sock, readset))
1791 debug("Connection to port %d forwarding to %.100s port %d requested.",
1792 c->listening_port, c->path, c->host_port);
1794 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1795 nextstate = SSH_CHANNEL_OPENING;
1796 rtype = "forwarded-tcpip";
1797 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1798 nextstate = SSH_CHANNEL_OPENING;
1799 rtype = "forwarded-streamlocal@openssh.com";
1800 } else if (c->host_port == PORT_STREAMLOCAL) {
1801 nextstate = SSH_CHANNEL_OPENING;
1802 rtype = "direct-streamlocal@openssh.com";
1803 } else if (c->host_port == 0) {
1804 nextstate = SSH_CHANNEL_DYNAMIC;
1805 rtype = "dynamic-tcpip";
1807 nextstate = SSH_CHANNEL_OPENING;
1808 rtype = "direct-tcpip";
1811 addrlen = sizeof(addr);
1812 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1813 if (newsock == -1) {
1814 if (errno != EINTR && errno != EWOULDBLOCK &&
1815 errno != ECONNABORTED)
1816 error("accept: %.100s", strerror(errno));
1817 if (errno == EMFILE || errno == ENFILE)
1818 c->notbefore = monotime() + 1;
1821 if (c->host_port != PORT_STREAMLOCAL)
1822 set_nodelay(newsock);
1823 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1824 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1825 nc->listening_port = c->listening_port;
1826 nc->host_port = c->host_port;
1827 if (c->path != NULL)
1828 nc->path = xstrdup(c->path);
1830 if (nextstate != SSH_CHANNEL_DYNAMIC)
1831 port_open_helper(ssh, nc, rtype);
1835 * This is the authentication agent socket listening for connections from
1839 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1840 fd_set *readset, fd_set *writeset)
1844 struct sockaddr_storage addr;
1847 if (!FD_ISSET(c->sock, readset))
1850 addrlen = sizeof(addr);
1851 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1852 if (newsock == -1) {
1853 error("accept from auth socket: %.100s", strerror(errno));
1854 if (errno == EMFILE || errno == ENFILE)
1855 c->notbefore = monotime() + 1;
1858 nc = channel_new(ssh, "accepted auth socket",
1859 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1860 c->local_window_max, c->local_maxpacket,
1861 0, "accepted auth socket", 1);
1862 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1863 if ((r = sshpkt_send(ssh)) != 0)
1864 fatal_fr(r, "channel %i", c->self);
1868 channel_post_connecting(struct ssh *ssh, Channel *c,
1869 fd_set *readset, fd_set *writeset)
1871 int err = 0, sock, isopen, r;
1872 socklen_t sz = sizeof(err);
1874 if (!FD_ISSET(c->sock, writeset))
1876 if (!c->have_remote_id)
1877 fatal_f("channel %d: no remote id", c->self);
1878 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1879 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1880 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1882 error("getsockopt SO_ERROR failed");
1885 debug("channel %d: connected to %s port %d",
1886 c->self, c->connect_ctx.host, c->connect_ctx.port);
1887 channel_connect_ctx_free(&c->connect_ctx);
1888 c->type = SSH_CHANNEL_OPEN;
1890 /* no message necessary */
1892 if ((r = sshpkt_start(ssh,
1893 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1894 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1895 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1896 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1897 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1898 (r = sshpkt_send(ssh)) != 0)
1899 fatal_fr(r, "channel %i open confirm", c->self);
1902 debug("channel %d: connection failed: %s",
1903 c->self, strerror(err));
1904 /* Try next address, if any */
1905 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1907 c->sock = c->rfd = c->wfd = sock;
1908 channel_find_maxfd(ssh->chanctxt);
1911 /* Exhausted all addresses */
1912 error("connect_to %.100s port %d: failed.",
1913 c->connect_ctx.host, c->connect_ctx.port);
1914 channel_connect_ctx_free(&c->connect_ctx);
1916 rdynamic_close(ssh, c);
1918 if ((r = sshpkt_start(ssh,
1919 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1920 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1921 (r = sshpkt_put_u32(ssh,
1922 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1923 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1924 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1925 (r = sshpkt_send(ssh)) != 0)
1926 fatal_fr(r, "channel %i: failure", c->self);
1927 chan_mark_dead(ssh, c);
1933 channel_handle_rfd(struct ssh *ssh, Channel *c,
1934 fd_set *readset, fd_set *writeset)
1936 char buf[CHAN_RBUF];
1940 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1942 if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1946 len = read(c->rfd, buf, sizeof(buf));
1947 if (len == -1 && (errno == EINTR ||
1948 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1950 #ifndef PTY_ZEROREAD
1953 if ((!c->isatty && len <= 0) ||
1954 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1956 debug2("channel %d: read<=0 rfd %d len %zd",
1957 c->self, c->rfd, len);
1958 if (c->type != SSH_CHANNEL_OPEN) {
1959 debug2("channel %d: not open", c->self);
1960 chan_mark_dead(ssh, c);
1963 chan_read_failed(ssh, c);
1967 if (c->input_filter != NULL) {
1968 if (c->input_filter(ssh, c, buf, len) == -1) {
1969 debug2("channel %d: filter stops", c->self);
1970 chan_read_failed(ssh, c);
1972 } else if (c->datagram) {
1973 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1974 fatal_fr(r, "channel %i: put datagram", c->self);
1975 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
1976 fatal_fr(r, "channel %i: put data", c->self);
1981 channel_handle_wfd(struct ssh *ssh, Channel *c,
1982 fd_set *readset, fd_set *writeset)
1985 u_char *data = NULL, *buf; /* XXX const; need filter API change */
1986 size_t dlen, olen = 0;
1989 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1990 sshbuf_len(c->output) == 0)
1993 /* Send buffered output data to the socket. */
1994 olen = sshbuf_len(c->output);
1995 if (c->output_filter != NULL) {
1996 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1997 debug2("channel %d: filter stops", c->self);
1998 if (c->type != SSH_CHANNEL_OPEN)
1999 chan_mark_dead(ssh, c);
2001 chan_write_failed(ssh, c);
2004 } else if (c->datagram) {
2005 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2006 fatal_fr(r, "channel %i: get datagram", c->self);
2009 buf = data = sshbuf_mutable_ptr(c->output);
2010 dlen = sshbuf_len(c->output);
2014 /* ignore truncated writes, datagrams might get lost */
2015 len = write(c->wfd, buf, dlen);
2017 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2018 errno == EWOULDBLOCK))
2026 /* XXX: Later AIX versions can't push as much data to tty */
2028 dlen = MIN(dlen, 8*1024);
2031 len = write(c->wfd, buf, dlen);
2033 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2037 if (c->type != SSH_CHANNEL_OPEN) {
2038 debug2("channel %d: not open", c->self);
2039 chan_mark_dead(ssh, c);
2042 chan_write_failed(ssh, c);
2046 #ifndef BROKEN_TCGETATTR_ICANON
2047 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2048 if (tcgetattr(c->wfd, &tio) == 0 &&
2049 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2051 * Simulate echo to reduce the impact of
2052 * traffic analysis. We need to match the
2053 * size of a SSH2_MSG_CHANNEL_DATA message
2054 * (4 byte channel id + buf)
2056 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2057 (r = sshpkt_send(ssh)) != 0)
2058 fatal_fr(r, "channel %i: ignore", c->self);
2061 #endif /* BROKEN_TCGETATTR_ICANON */
2062 if ((r = sshbuf_consume(c->output, len)) != 0)
2063 fatal_fr(r, "channel %i: consume", c->self);
2065 c->local_consumed += olen - sshbuf_len(c->output);
2071 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2072 fd_set *readset, fd_set *writeset)
2077 if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2080 len = write(c->efd, sshbuf_ptr(c->extended),
2081 sshbuf_len(c->extended));
2082 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2083 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2084 errno == EWOULDBLOCK))
2087 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2088 channel_close_fd(ssh, c, &c->efd);
2090 if ((r = sshbuf_consume(c->extended, len)) != 0)
2091 fatal_fr(r, "channel %i: consume", c->self);
2092 c->local_consumed += len;
2098 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2099 fd_set *readset, fd_set *writeset)
2101 char buf[CHAN_RBUF];
2105 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2107 if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
2110 len = read(c->efd, buf, sizeof(buf));
2111 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2112 if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2113 errno == EWOULDBLOCK) && !force)))
2116 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2117 channel_close_fd(ssh, c, &c->efd);
2118 } else if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2119 debug3("channel %d: discard efd", c->self);
2120 else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2121 fatal_fr(r, "channel %i: append", c->self);
2126 channel_handle_efd(struct ssh *ssh, Channel *c,
2127 fd_set *readset, fd_set *writeset)
2132 /** XXX handle drain efd, too */
2134 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2135 return channel_handle_efd_write(ssh, c, readset, writeset);
2136 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2137 c->extended_usage == CHAN_EXTENDED_IGNORE)
2138 return channel_handle_efd_read(ssh, c, readset, writeset);
2144 channel_check_window(struct ssh *ssh, Channel *c)
2148 if (c->type == SSH_CHANNEL_OPEN &&
2149 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2150 ((c->local_window_max - c->local_window >
2151 c->local_maxpacket*3) ||
2152 c->local_window < c->local_window_max/2) &&
2153 c->local_consumed > 0) {
2154 if (!c->have_remote_id)
2155 fatal_f("channel %d: no remote id", c->self);
2156 if ((r = sshpkt_start(ssh,
2157 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2158 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2159 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2160 (r = sshpkt_send(ssh)) != 0) {
2161 fatal_fr(r, "channel %i", c->self);
2163 debug2("channel %d: window %d sent adjust %d", c->self,
2164 c->local_window, c->local_consumed);
2165 c->local_window += c->local_consumed;
2166 c->local_consumed = 0;
2172 channel_post_open(struct ssh *ssh, Channel *c,
2173 fd_set *readset, fd_set *writeset)
2175 channel_handle_rfd(ssh, c, readset, writeset);
2176 channel_handle_wfd(ssh, c, readset, writeset);
2177 channel_handle_efd(ssh, c, readset, writeset);
2178 channel_check_window(ssh, c);
2182 read_mux(struct ssh *ssh, Channel *c, u_int need)
2184 char buf[CHAN_RBUF];
2189 if (sshbuf_len(c->input) < need) {
2190 rlen = need - sshbuf_len(c->input);
2191 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2192 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2193 return sshbuf_len(c->input);
2195 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2196 c->self, c->rfd, len);
2197 chan_read_failed(ssh, c);
2199 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2200 fatal_fr(r, "channel %i: append", c->self);
2202 return sshbuf_len(c->input);
2206 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2207 fd_set *readset, fd_set *writeset)
2211 if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2213 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2219 * Don't not read past the precise end of packets to
2220 * avoid disrupting fd passing.
2222 if (read_mux(ssh, c, 4) < 4) /* read header */
2224 /* XXX sshbuf_peek_u32 */
2225 need = PEEK_U32(sshbuf_ptr(c->input));
2226 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2227 if (need > CHANNEL_MUX_MAX_PACKET) {
2228 debug2("channel %d: packet too big %u > %u",
2229 c->self, CHANNEL_MUX_MAX_PACKET, need);
2230 chan_rcvd_oclose(ssh, c);
2233 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2235 if (c->mux_rcb(ssh, c) != 0) {
2236 debug("channel %d: mux_rcb failed", c->self);
2237 chan_mark_dead(ssh, c);
2243 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2244 fd_set *readset, fd_set *writeset)
2249 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2250 sshbuf_len(c->output) == 0)
2253 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2254 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2257 chan_mark_dead(ssh, c);
2260 if ((r = sshbuf_consume(c->output, len)) != 0)
2261 fatal_fr(r, "channel %i: consume", c->self);
2265 channel_post_mux_client(struct ssh *ssh, Channel *c,
2266 fd_set *readset, fd_set *writeset)
2268 channel_post_mux_client_read(ssh, c, readset, writeset);
2269 channel_post_mux_client_write(ssh, c, readset, writeset);
2273 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2274 fd_set *readset, fd_set *writeset)
2277 struct sockaddr_storage addr;
2283 if (!FD_ISSET(c->sock, readset))
2286 debug("multiplexing control connection");
2289 * Accept connection on control socket
2291 memset(&addr, 0, sizeof(addr));
2292 addrlen = sizeof(addr);
2293 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2295 error_f("accept: %s", strerror(errno));
2296 if (errno == EMFILE || errno == ENFILE)
2297 c->notbefore = monotime() + 1;
2301 if (getpeereid(newsock, &euid, &egid) == -1) {
2302 error_f("getpeereid failed: %s", strerror(errno));
2306 if ((euid != 0) && (getuid() != euid)) {
2307 error("multiplex uid mismatch: peer euid %u != uid %u",
2308 (u_int)euid, (u_int)getuid());
2312 nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2313 newsock, newsock, -1, c->local_window_max,
2314 c->local_maxpacket, 0, "mux-control", 1);
2315 nc->mux_rcb = c->mux_rcb;
2316 debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2317 /* establish state */
2318 nc->mux_rcb(ssh, nc);
2319 /* mux state transitions must not elicit protocol messages */
2320 nc->flags |= CHAN_LOCAL;
2324 channel_handler_init(struct ssh_channels *sc)
2326 chan_fn **pre, **post;
2328 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2329 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2330 fatal_f("allocation failed");
2332 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2333 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2334 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2335 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2336 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2337 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2338 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2339 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2340 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2341 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2342 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2343 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2344 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2346 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2347 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2348 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2349 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2350 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2351 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2352 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2353 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2354 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2355 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2356 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2357 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2359 sc->channel_pre = pre;
2360 sc->channel_post = post;
2363 /* gc dead channels */
2365 channel_garbage_collect(struct ssh *ssh, Channel *c)
2369 if (c->detach_user != NULL) {
2370 if (!chan_is_dead(ssh, c, c->detach_close))
2373 debug2("channel %d: gc: notify user", c->self);
2374 c->detach_user(ssh, c->self, NULL);
2375 /* if we still have a callback */
2376 if (c->detach_user != NULL)
2378 debug2("channel %d: gc: user detached", c->self);
2380 if (!chan_is_dead(ssh, c, 1))
2382 debug2("channel %d: garbage collecting", c->self);
2383 channel_free(ssh, c);
2386 enum channel_table { CHAN_PRE, CHAN_POST };
2389 channel_handler(struct ssh *ssh, int table,
2390 fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2392 struct ssh_channels *sc = ssh->chanctxt;
2393 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2399 if (unpause_secs != NULL)
2401 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2402 c = sc->channels[i];
2406 if (table == CHAN_PRE)
2411 if (ftab[c->type] != NULL) {
2413 * Run handlers that are not paused.
2415 if (c->notbefore <= now)
2416 (*ftab[c->type])(ssh, c, readset, writeset);
2417 else if (unpause_secs != NULL) {
2419 * Collect the time that the earliest
2420 * channel comes off pause.
2422 debug3_f("chan %d: skip for %d more "
2424 (int)(c->notbefore - now));
2425 if (*unpause_secs == 0 ||
2426 (c->notbefore - now) < *unpause_secs)
2427 *unpause_secs = c->notbefore - now;
2430 channel_garbage_collect(ssh, c);
2432 if (unpause_secs != NULL && *unpause_secs != 0)
2433 debug3_f("first channel unpauses in %d seconds",
2434 (int)*unpause_secs);
2438 * Create sockets before allocating the select bitmasks.
2439 * This is necessary for things that need to happen after reading
2440 * the network-input but before channel_prepare_select().
2443 channel_before_prepare_select(struct ssh *ssh)
2445 struct ssh_channels *sc = ssh->chanctxt;
2449 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2450 c = sc->channels[i];
2453 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2454 channel_before_prepare_select_rdynamic(ssh, c);
2459 * Allocate/update select bitmasks and add any bits relevant to channels in
2463 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2464 int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2466 u_int n, sz, nfdset;
2468 channel_before_prepare_select(ssh); /* might update channel_max_fd */
2470 n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2472 nfdset = howmany(n+1, NFDBITS);
2473 /* Explicitly test here, because xrealloc isn't always called */
2474 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2475 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2476 sz = nfdset * sizeof(fd_mask);
2478 /* perhaps check sz < nalloc/2 and shrink? */
2479 if (*readsetp == NULL || sz > *nallocp) {
2480 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2481 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2485 memset(*readsetp, 0, sz);
2486 memset(*writesetp, 0, sz);
2488 if (!ssh_packet_is_rekeying(ssh))
2489 channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2494 * After select, perform any appropriate operations for channels which have
2498 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2500 channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2504 * Enqueue data for channels with open or draining c->input.
2507 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2513 if ((len = sshbuf_len(c->input)) == 0) {
2514 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2516 * input-buffer is empty and read-socket shutdown:
2517 * tell peer, that we will not send more data:
2519 * hack for extended data: delay EOF if EFD still
2522 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2523 debug2("channel %d: "
2524 "ibuf_empty delayed efd %d/(%zu)",
2525 c->self, c->efd, sshbuf_len(c->extended));
2527 chan_ibuf_empty(ssh, c);
2532 if (!c->have_remote_id)
2533 fatal_f("channel %d: no remote id", c->self);
2536 /* Check datagram will fit; drop if not */
2537 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2538 fatal_fr(r, "channel %i: get datagram", c->self);
2540 * XXX this does tail-drop on the datagram queue which is
2541 * usually suboptimal compared to head-drop. Better to have
2542 * backpressure at read time? (i.e. read + discard)
2544 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2545 debug("channel %d: datagram too big", c->self);
2549 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2550 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2551 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2552 (r = sshpkt_send(ssh)) != 0)
2553 fatal_fr(r, "channel %i: send datagram", c->self);
2554 c->remote_window -= plen;
2558 /* Enqueue packet for buffered data. */
2559 if (len > c->remote_window)
2560 len = c->remote_window;
2561 if (len > c->remote_maxpacket)
2562 len = c->remote_maxpacket;
2565 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2566 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2567 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2568 (r = sshpkt_send(ssh)) != 0)
2569 fatal_fr(r, "channel %i: send data", c->self);
2570 if ((r = sshbuf_consume(c->input, len)) != 0)
2571 fatal_fr(r, "channel %i: consume", c->self);
2572 c->remote_window -= len;
2576 * Enqueue data for channels with open c->extended in read mode.
2579 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2584 if ((len = sshbuf_len(c->extended)) == 0)
2587 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2588 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2589 if (len > c->remote_window)
2590 len = c->remote_window;
2591 if (len > c->remote_maxpacket)
2592 len = c->remote_maxpacket;
2595 if (!c->have_remote_id)
2596 fatal_f("channel %d: no remote id", c->self);
2597 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2598 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2599 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2600 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2601 (r = sshpkt_send(ssh)) != 0)
2602 fatal_fr(r, "channel %i: data", c->self);
2603 if ((r = sshbuf_consume(c->extended, len)) != 0)
2604 fatal_fr(r, "channel %i: consume", c->self);
2605 c->remote_window -= len;
2606 debug2("channel %d: sent ext data %zu", c->self, len);
2609 /* If there is data to send to the connection, enqueue some of it now. */
2611 channel_output_poll(struct ssh *ssh)
2613 struct ssh_channels *sc = ssh->chanctxt;
2617 for (i = 0; i < sc->channels_alloc; i++) {
2618 c = sc->channels[i];
2623 * We are only interested in channels that can have buffered
2626 if (c->type != SSH_CHANNEL_OPEN)
2628 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2629 /* XXX is this true? */
2630 debug3("channel %d: will not send data after close",
2635 /* Get the amount of buffered data for this channel. */
2636 if (c->istate == CHAN_INPUT_OPEN ||
2637 c->istate == CHAN_INPUT_WAIT_DRAIN)
2638 channel_output_poll_input_open(ssh, c);
2639 /* Send extended data, i.e. stderr */
2640 if (!(c->flags & CHAN_EOF_SENT) &&
2641 c->extended_usage == CHAN_EXTENDED_READ)
2642 channel_output_poll_extended_read(ssh, c);
2646 /* -- mux proxy support */
2649 * When multiplexing channel messages for mux clients we have to deal
2650 * with downstream messages from the mux client and upstream messages
2651 * from the ssh server:
2652 * 1) Handling downstream messages is straightforward and happens
2653 * in channel_proxy_downstream():
2654 * - We forward all messages (mostly) unmodified to the server.
2655 * - However, in order to route messages from upstream to the correct
2656 * downstream client, we have to replace the channel IDs used by the
2657 * mux clients with a unique channel ID because the mux clients might
2658 * use conflicting channel IDs.
2659 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2660 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2661 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2662 * with the newly allocated channel ID.
2663 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2664 * channels and processed by channel_proxy_upstream(). The local channel ID
2665 * is then translated back to the original mux client ID.
2666 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2667 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2668 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2669 * downstream mux client are removed.
2670 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2671 * requires more work, because they are not addressed to a specific
2672 * channel. E.g. client_request_forwarded_tcpip() needs to figure
2673 * out whether the request is addressed to the local client or a
2674 * specific downstream client based on the listen-address/port.
2675 * 6) Agent and X11-Forwarding have a similar problem and are currently
2676 * not supported as the matching session/channel cannot be identified
2681 * receive packets from downstream mux clients:
2682 * channel callback fired on read from mux client, creates
2683 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2684 * on channel creation.
2687 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2690 struct sshbuf *original = NULL, *modified = NULL;
2692 char *ctype = NULL, *listen_host = NULL;
2696 u_int id, remote_id, listen_port;
2698 /* sshbuf_dump(downstream->input, stderr); */
2699 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2701 error_fr(r, "parse");
2705 error_f("short message");
2709 /* skip padlen + type */
2712 if (ssh_packet_log_type(type))
2713 debug3_f("channel %u: down->up: type %u",
2714 downstream->self, type);
2717 case SSH2_MSG_CHANNEL_OPEN:
2718 if ((original = sshbuf_from(cp, have)) == NULL ||
2719 (modified = sshbuf_new()) == NULL) {
2723 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2724 (r = sshbuf_get_u32(original, &id)) != 0) {
2725 error_fr(r, "parse");
2728 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2729 -1, -1, -1, 0, 0, 0, ctype, 1);
2730 c->mux_ctx = downstream; /* point to mux client */
2731 c->mux_downstream_id = id; /* original downstream id */
2732 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2733 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2734 (r = sshbuf_putb(modified, original)) != 0) {
2735 error_fr(r, "compose");
2736 channel_free(ssh, c);
2740 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2742 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2743 * need to parse 'remote_id' instead of 'ctype'.
2745 if ((original = sshbuf_from(cp, have)) == NULL ||
2746 (modified = sshbuf_new()) == NULL) {
2750 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2751 (r = sshbuf_get_u32(original, &id)) != 0) {
2752 error_fr(r, "parse");
2755 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2756 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2757 c->mux_ctx = downstream; /* point to mux client */
2758 c->mux_downstream_id = id;
2759 c->remote_id = remote_id;
2760 c->have_remote_id = 1;
2761 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2762 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2763 (r = sshbuf_putb(modified, original)) != 0) {
2764 error_fr(r, "compose");
2765 channel_free(ssh, c);
2769 case SSH2_MSG_GLOBAL_REQUEST:
2770 if ((original = sshbuf_from(cp, have)) == NULL) {
2774 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2775 error_fr(r, "parse");
2778 if (strcmp(ctype, "tcpip-forward") != 0) {
2779 error_f("unsupported request %s", ctype);
2782 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2783 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2784 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2785 error_fr(r, "parse");
2788 if (listen_port > 65535) {
2789 error_f("tcpip-forward for %s: bad port %u",
2790 listen_host, listen_port);
2793 /* Record that connection to this host/port is permitted. */
2794 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
2795 listen_host, NULL, (int)listen_port, downstream);
2798 case SSH2_MSG_CHANNEL_CLOSE:
2801 remote_id = PEEK_U32(cp);
2802 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2803 if (c->flags & CHAN_CLOSE_RCVD)
2804 channel_free(ssh, c);
2806 c->flags |= CHAN_CLOSE_SENT;
2811 if ((r = sshpkt_start(ssh, type)) != 0 ||
2812 (r = sshpkt_putb(ssh, modified)) != 0 ||
2813 (r = sshpkt_send(ssh)) != 0) {
2814 error_fr(r, "send");
2818 if ((r = sshpkt_start(ssh, type)) != 0 ||
2819 (r = sshpkt_put(ssh, cp, have)) != 0 ||
2820 (r = sshpkt_send(ssh)) != 0) {
2821 error_fr(r, "send");
2829 sshbuf_free(original);
2830 sshbuf_free(modified);
2835 * receive packets from upstream server and de-multiplex packets
2836 * to correct downstream:
2837 * implemented as a helper for channel input handlers,
2838 * replaces local (proxy) channel ID with downstream channel ID.
2841 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2843 struct sshbuf *b = NULL;
2844 Channel *downstream;
2845 const u_char *cp = NULL;
2850 * When receiving packets from the peer we need to check whether we
2851 * need to forward the packets to the mux client. In this case we
2852 * restore the original channel id and keep track of CLOSE messages,
2853 * so we can cleanup the channel.
2855 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2857 if ((downstream = c->mux_ctx) == NULL)
2860 case SSH2_MSG_CHANNEL_CLOSE:
2861 case SSH2_MSG_CHANNEL_DATA:
2862 case SSH2_MSG_CHANNEL_EOF:
2863 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
2864 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2865 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
2866 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2867 case SSH2_MSG_CHANNEL_SUCCESS:
2868 case SSH2_MSG_CHANNEL_FAILURE:
2869 case SSH2_MSG_CHANNEL_REQUEST:
2872 debug2_f("channel %u: unsupported type %u", c->self, type);
2875 if ((b = sshbuf_new()) == NULL) {
2876 error_f("alloc reply");
2879 /* get remaining payload (after id) */
2880 cp = sshpkt_ptr(ssh, &len);
2882 error_f("no packet");
2885 /* translate id and send to muxclient */
2886 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
2887 (r = sshbuf_put_u8(b, type)) != 0 ||
2888 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
2889 (r = sshbuf_put(b, cp, len)) != 0 ||
2890 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
2891 error_fr(r, "compose muxclient");
2894 /* sshbuf_dump(b, stderr); */
2895 if (ssh_packet_log_type(type))
2896 debug3_f("channel %u: up->down: type %u", c->self, type);
2900 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2901 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
2902 if (cp && len > 4) {
2903 c->remote_id = PEEK_U32(cp);
2904 c->have_remote_id = 1;
2907 case SSH2_MSG_CHANNEL_CLOSE:
2908 if (c->flags & CHAN_CLOSE_SENT)
2909 channel_free(ssh, c);
2911 c->flags |= CHAN_CLOSE_RCVD;
2918 /* -- protocol input */
2920 /* Parse a channel ID from the current packet */
2922 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
2927 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
2928 error_r(r, "%s: parse id", where);
2929 ssh_packet_disconnect(ssh, "Invalid %s message", what);
2932 error_r(r, "%s: bad channel id %u", where, id);
2933 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
2938 /* Lookup a channel from an ID in the current packet */
2940 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
2942 int id = channel_parse_id(ssh, where, what);
2945 if ((c = channel_lookup(ssh, id)) == NULL) {
2946 ssh_packet_disconnect(ssh,
2947 "%s packet referred to nonexistent channel %d", what, id);
2953 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
2956 size_t data_len, win_len;
2957 Channel *c = channel_from_packet_id(ssh, __func__, "data");
2960 if (channel_proxy_upstream(c, type, seq, ssh))
2963 /* Ignore any data for non-open channels (might happen on close) */
2964 if (c->type != SSH_CHANNEL_OPEN &&
2965 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
2966 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
2967 c->type != SSH_CHANNEL_X11_OPEN)
2971 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
2972 (r = sshpkt_get_end(ssh)) != 0)
2973 fatal_fr(r, "channel %i: get data", c->self);
2977 win_len += 4; /* string length header */
2980 * The sending side reduces its window as it sends data, so we
2981 * must 'fake' consumption of the data in order to ensure that window
2982 * updates are sent back. Otherwise the connection might deadlock.
2984 if (c->ostate != CHAN_OUTPUT_OPEN) {
2985 c->local_window -= win_len;
2986 c->local_consumed += win_len;
2990 if (win_len > c->local_maxpacket) {
2991 logit("channel %d: rcvd big packet %zu, maxpack %u",
2992 c->self, win_len, c->local_maxpacket);
2995 if (win_len > c->local_window) {
2996 logit("channel %d: rcvd too much data %zu, win %u",
2997 c->self, win_len, c->local_window);
3000 c->local_window -= win_len;
3003 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3004 fatal_fr(r, "channel %i: append datagram", c->self);
3005 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3006 fatal_fr(r, "channel %i: append data", c->self);
3012 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3017 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3020 if (channel_proxy_upstream(c, type, seq, ssh))
3022 if (c->type != SSH_CHANNEL_OPEN) {
3023 logit("channel %d: ext data for non open", c->self);
3026 if (c->flags & CHAN_EOF_RCVD) {
3027 if (ssh->compat & SSH_BUG_EXTEOF)
3028 debug("channel %d: accepting ext data after eof",
3031 ssh_packet_disconnect(ssh, "Received extended_data "
3032 "after EOF on channel %d.", c->self);
3035 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3036 error_fr(r, "parse tcode");
3037 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3040 c->extended_usage != CHAN_EXTENDED_WRITE ||
3041 tcode != SSH2_EXTENDED_DATA_STDERR) {
3042 logit("channel %d: bad ext data", c->self);
3045 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3046 (r = sshpkt_get_end(ssh)) != 0) {
3047 error_fr(r, "parse data");
3048 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3051 if (data_len > c->local_window) {
3052 logit("channel %d: rcvd too much extended_data %zu, win %u",
3053 c->self, data_len, c->local_window);
3056 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3057 /* XXX sshpkt_getb? */
3058 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3059 error_fr(r, "append");
3060 c->local_window -= data_len;
3065 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3067 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3070 if ((r = sshpkt_get_end(ssh)) != 0) {
3071 error_fr(r, "parse data");
3072 ssh_packet_disconnect(ssh, "Invalid ieof message");
3075 if (channel_proxy_upstream(c, type, seq, ssh))
3077 chan_rcvd_ieof(ssh, c);
3079 /* XXX force input close */
3080 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3081 debug("channel %d: FORCE input drain", c->self);
3082 c->istate = CHAN_INPUT_WAIT_DRAIN;
3083 if (sshbuf_len(c->input) == 0)
3084 chan_ibuf_empty(ssh, c);
3090 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3092 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3095 if (channel_proxy_upstream(c, type, seq, ssh))
3097 if ((r = sshpkt_get_end(ssh)) != 0) {
3098 error_fr(r, "parse data");
3099 ssh_packet_disconnect(ssh, "Invalid oclose message");
3101 chan_rcvd_oclose(ssh, c);
3106 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3108 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3109 u_int32_t remote_window, remote_maxpacket;
3112 if (channel_proxy_upstream(c, type, seq, ssh))
3114 if (c->type != SSH_CHANNEL_OPENING)
3115 ssh_packet_disconnect(ssh, "Received open confirmation for "
3116 "non-opening channel %d.", c->self);
3118 * Record the remote channel number and mark that the channel
3121 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3122 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3123 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3124 (r = sshpkt_get_end(ssh)) != 0) {
3125 error_fr(r, "window/maxpacket");
3126 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3129 c->have_remote_id = 1;
3130 c->remote_window = remote_window;
3131 c->remote_maxpacket = remote_maxpacket;
3132 c->type = SSH_CHANNEL_OPEN;
3133 if (c->open_confirm) {
3134 debug2_f("channel %d: callback start", c->self);
3135 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3136 debug2_f("channel %d: callback done", c->self);
3138 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3139 c->remote_window, c->remote_maxpacket);
3144 reason2txt(int reason)
3147 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3148 return "administratively prohibited";
3149 case SSH2_OPEN_CONNECT_FAILED:
3150 return "connect failed";
3151 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3152 return "unknown channel type";
3153 case SSH2_OPEN_RESOURCE_SHORTAGE:
3154 return "resource shortage";
3156 return "unknown reason";
3160 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3162 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3167 if (channel_proxy_upstream(c, type, seq, ssh))
3169 if (c->type != SSH_CHANNEL_OPENING)
3170 ssh_packet_disconnect(ssh, "Received open failure for "
3171 "non-opening channel %d.", c->self);
3172 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3173 error_fr(r, "parse reason");
3174 ssh_packet_disconnect(ssh, "Invalid open failure message");
3177 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3178 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3179 (r = sshpkt_get_end(ssh)) != 0) {
3180 error_fr(r, "parse msg/lang");
3181 ssh_packet_disconnect(ssh, "Invalid open failure message");
3183 logit("channel %d: open failed: %s%s%s", c->self,
3184 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3186 if (c->open_confirm) {
3187 debug2_f("channel %d: callback start", c->self);
3188 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3189 debug2_f("channel %d: callback done", c->self);
3191 /* Schedule the channel for cleanup/deletion. */
3192 chan_mark_dead(ssh, c);
3197 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3199 int id = channel_parse_id(ssh, __func__, "window adjust");
3205 if ((c = channel_lookup(ssh, id)) == NULL) {
3206 logit("Received window adjust for non-open channel %d.", id);
3210 if (channel_proxy_upstream(c, type, seq, ssh))
3212 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3213 (r = sshpkt_get_end(ssh)) != 0) {
3214 error_fr(r, "parse adjust");
3215 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3217 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3218 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3219 fatal("channel %d: adjust %u overflows remote window %u",
3220 c->self, adjust, c->remote_window);
3222 c->remote_window = new_rwin;
3227 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3229 int id = channel_parse_id(ssh, __func__, "status confirm");
3231 struct channel_confirm *cc;
3233 /* Reset keepalive timeout */
3234 ssh_packet_set_alive_timeouts(ssh, 0);
3236 debug2_f("type %d id %d", type, id);
3238 if ((c = channel_lookup(ssh, id)) == NULL) {
3239 logit_f("%d: unknown", id);
3242 if (channel_proxy_upstream(c, type, seq, ssh))
3244 if (sshpkt_get_end(ssh) != 0)
3245 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3246 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3248 cc->cb(ssh, type, c, cc->ctx);
3249 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3250 freezero(cc, sizeof(*cc));
3254 /* -- tcp forwarding */
3257 channel_set_af(struct ssh *ssh, int af)
3259 ssh->chanctxt->IPv4or6 = af;
3264 * Determine whether or not a port forward listens to loopback, the
3265 * specified address or wildcard. On the client, a specified bind
3266 * address will always override gateway_ports. On the server, a
3267 * gateway_ports of 1 (``yes'') will override the client's specification
3268 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3269 * will bind to whatever address the client asked for.
3271 * Special-case listen_addrs are:
3273 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3274 * "" (empty string), "*" -> wildcard v4/v6
3275 * "localhost" -> loopback v4/v6
3276 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3279 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3280 int is_client, struct ForwardOptions *fwd_opts)
3282 const char *addr = NULL;
3285 if (listen_addr == NULL) {
3286 /* No address specified: default to gateway_ports setting */
3287 if (fwd_opts->gateway_ports)
3289 } else if (fwd_opts->gateway_ports || is_client) {
3290 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3291 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3292 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3293 (!is_client && fwd_opts->gateway_ports == 1)) {
3296 * Notify client if they requested a specific listen
3297 * address and it was overridden.
3299 if (*listen_addr != '\0' &&
3300 strcmp(listen_addr, "0.0.0.0") != 0 &&
3301 strcmp(listen_addr, "*") != 0) {
3302 ssh_packet_send_debug(ssh,
3303 "Forwarding listen address "
3304 "\"%s\" overridden by server "
3305 "GatewayPorts", listen_addr);
3307 } else if (strcmp(listen_addr, "localhost") != 0 ||
3308 strcmp(listen_addr, "127.0.0.1") == 0 ||
3309 strcmp(listen_addr, "::1") == 0) {
3311 * Accept explicit localhost address when
3312 * GatewayPorts=yes. The "localhost" hostname is
3313 * deliberately skipped here so it will listen on all
3314 * available local address families.
3318 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3319 strcmp(listen_addr, "::1") == 0) {
3321 * If a specific IPv4/IPv6 localhost address has been
3322 * requested then accept it even if gateway_ports is in
3323 * effect. This allows the client to prefer IPv4 or IPv6.
3327 if (wildcardp != NULL)
3328 *wildcardp = wildcard;
3333 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3334 struct Forward *fwd, int *allocated_listen_port,
3335 struct ForwardOptions *fwd_opts)
3338 int sock, r, success = 0, wildcard = 0, is_client;
3339 struct addrinfo hints, *ai, *aitop;
3340 const char *host, *addr;
3341 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3344 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3346 if (is_client && fwd->connect_path != NULL) {
3347 host = fwd->connect_path;
3349 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3350 fwd->listen_host : fwd->connect_host;
3352 error("No forward host name.");
3355 if (strlen(host) >= NI_MAXHOST) {
3356 error("Forward host name too long.");
3361 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3362 addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3363 is_client, fwd_opts);
3364 debug3_f("type %d wildcard %d addr %s", type, wildcard,
3365 (addr == NULL) ? "NULL" : addr);
3368 * getaddrinfo returns a loopback address if the hostname is
3369 * set to NULL and hints.ai_flags is not AI_PASSIVE
3371 memset(&hints, 0, sizeof(hints));
3372 hints.ai_family = ssh->chanctxt->IPv4or6;
3373 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3374 hints.ai_socktype = SOCK_STREAM;
3375 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3376 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3378 /* This really shouldn't happen */
3379 ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3380 ssh_gai_strerror(r));
3382 error_f("getaddrinfo(%.64s): %s", addr,
3383 ssh_gai_strerror(r));
3387 if (allocated_listen_port != NULL)
3388 *allocated_listen_port = 0;
3389 for (ai = aitop; ai; ai = ai->ai_next) {
3390 switch (ai->ai_family) {
3392 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3396 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3403 * If allocating a port for -R forwards, then use the
3404 * same port for all address families.
3406 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3407 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3408 *allocated_listen_port > 0)
3409 *lport_p = htons(*allocated_listen_port);
3411 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3412 strport, sizeof(strport),
3413 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3414 error_f("getnameinfo failed");
3417 /* Create a port to listen for the host. */
3418 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3420 /* this is no error since kernel may not support ipv6 */
3421 verbose("socket [%s]:%s: %.100s", ntop, strport,
3426 set_reuseaddr(sock);
3427 if (ai->ai_family == AF_INET6)
3428 sock_set_v6only(sock);
3430 debug("Local forwarding listening on %s port %s.",
3433 /* Bind the socket to the address. */
3434 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3436 * address can be in if use ipv6 address is
3440 error("bind [%s]:%s: %.100s",
3441 ntop, strport, strerror(errno));
3443 verbose("bind [%s]:%s: %.100s",
3444 ntop, strport, strerror(errno));
3449 /* Start listening for connections on the socket. */
3450 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3451 error("listen [%s]:%s: %.100s", ntop, strport,
3458 * fwd->listen_port == 0 requests a dynamically allocated port -
3459 * record what we got.
3461 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3462 fwd->listen_port == 0 &&
3463 allocated_listen_port != NULL &&
3464 *allocated_listen_port == 0) {
3465 *allocated_listen_port = get_local_port(sock);
3466 debug("Allocated listen port %d",
3467 *allocated_listen_port);
3470 /* Allocate a channel number for the socket. */
3471 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3472 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3473 0, "port listener", 1);
3474 c->path = xstrdup(host);
3475 c->host_port = fwd->connect_port;
3476 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3477 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3478 !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3479 c->listening_port = *allocated_listen_port;
3481 c->listening_port = fwd->listen_port;
3485 error_f("cannot listen to port: %d", fwd->listen_port);
3486 freeaddrinfo(aitop);
3491 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3492 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3494 struct sockaddr_un sunaddr;
3501 case SSH_CHANNEL_UNIX_LISTENER:
3502 if (fwd->connect_path != NULL) {
3503 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3504 error("Local connecting path too long: %s",
3508 path = fwd->connect_path;
3509 port = PORT_STREAMLOCAL;
3511 if (fwd->connect_host == NULL) {
3512 error("No forward host name.");
3515 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3516 error("Forward host name too long.");
3519 path = fwd->connect_host;
3520 port = fwd->connect_port;
3523 case SSH_CHANNEL_RUNIX_LISTENER:
3524 path = fwd->listen_path;
3525 port = PORT_STREAMLOCAL;
3528 error_f("unexpected channel type %d", type);
3532 if (fwd->listen_path == NULL) {
3533 error("No forward path name.");
3536 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3537 error("Local listening path too long: %s", fwd->listen_path);
3541 debug3_f("type %d path %s", type, fwd->listen_path);
3543 /* Start a Unix domain listener. */
3544 omask = umask(fwd_opts->streamlocal_bind_mask);
3545 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3546 fwd_opts->streamlocal_bind_unlink);
3551 debug("Local forwarding listening on path %s.", fwd->listen_path);
3553 /* Allocate a channel number for the socket. */
3554 c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3555 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3556 0, "unix listener", 1);
3557 c->path = xstrdup(path);
3558 c->host_port = port;
3559 c->listening_port = PORT_STREAMLOCAL;
3560 c->listening_addr = xstrdup(fwd->listen_path);
3565 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3566 const char *host, u_short port)
3571 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3572 Channel *c = ssh->chanctxt->channels[i];
3573 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3575 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3576 debug2_f("close channel %d", i);
3577 channel_free(ssh, c);
3586 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3591 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3592 Channel *c = ssh->chanctxt->channels[i];
3593 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3595 if (c->path == NULL)
3597 if (strcmp(c->path, path) == 0) {
3598 debug2_f("close channel %d", i);
3599 channel_free(ssh, c);
3608 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3610 if (fwd->listen_path != NULL) {
3611 return channel_cancel_rport_listener_streamlocal(ssh,
3614 return channel_cancel_rport_listener_tcpip(ssh,
3615 fwd->listen_host, fwd->listen_port);
3620 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3621 const char *lhost, u_short lport, int cport,
3622 struct ForwardOptions *fwd_opts)
3626 const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3628 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3629 Channel *c = ssh->chanctxt->channels[i];
3630 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3632 if (c->listening_port != lport)
3634 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3635 /* skip dynamic forwardings */
3636 if (c->host_port == 0)
3639 if (c->host_port != cport)
3642 if ((c->listening_addr == NULL && addr != NULL) ||
3643 (c->listening_addr != NULL && addr == NULL))
3645 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3646 debug2_f("close channel %d", i);
3647 channel_free(ssh, c);
3656 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3662 error_f("no path specified.");
3666 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3667 Channel *c = ssh->chanctxt->channels[i];
3668 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3670 if (c->listening_addr == NULL)
3672 if (strcmp(c->listening_addr, path) == 0) {
3673 debug2_f("close channel %d", i);
3674 channel_free(ssh, c);
3683 channel_cancel_lport_listener(struct ssh *ssh,
3684 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3686 if (fwd->listen_path != NULL) {
3687 return channel_cancel_lport_listener_streamlocal(ssh,
3690 return channel_cancel_lport_listener_tcpip(ssh,
3691 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3695 /* protocol local port fwd, used by ssh */
3697 channel_setup_local_fwd_listener(struct ssh *ssh,
3698 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3700 if (fwd->listen_path != NULL) {
3701 return channel_setup_fwd_listener_streamlocal(ssh,
3702 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3704 return channel_setup_fwd_listener_tcpip(ssh,
3705 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3709 /* Matches a remote forwarding permission against a requested forwarding */
3711 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3716 /* XXX add ACLs for streamlocal */
3717 if (fwd->listen_path != NULL)
3720 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3723 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3724 allowed_open->listen_port != fwd->listen_port)
3727 /* Match hostnames case-insensitively */
3728 lhost = xstrdup(fwd->listen_host);
3730 ret = match_pattern(lhost, allowed_open->listen_host);
3736 /* Checks whether a requested remote forwarding is permitted */
3738 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3740 struct ssh_channels *sc = ssh->chanctxt;
3741 struct permission_set *pset = &sc->remote_perms;
3742 u_int i, permit, permit_adm = 1;
3743 struct permission *perm;
3745 /* XXX apply GatewayPorts override before checking? */
3747 permit = pset->all_permitted;
3749 for (i = 0; i < pset->num_permitted_user; i++) {
3750 perm = &pset->permitted_user[i];
3751 if (remote_open_match(perm, fwd)) {
3758 if (pset->num_permitted_admin > 0) {
3760 for (i = 0; i < pset->num_permitted_admin; i++) {
3761 perm = &pset->permitted_admin[i];
3762 if (remote_open_match(perm, fwd)) {
3769 return permit && permit_adm;
3772 /* protocol v2 remote port fwd, used by sshd */
3774 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
3775 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3777 if (!check_rfwd_permission(ssh, fwd)) {
3778 ssh_packet_send_debug(ssh, "port forwarding refused");
3779 if (fwd->listen_path != NULL)
3780 /* XXX always allowed, see remote_open_match() */
3781 logit("Received request from %.100s port %d to "
3782 "remote forward to path \"%.100s\", "
3783 "but the request was denied.",
3784 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3786 else if(fwd->listen_host != NULL)
3787 logit("Received request from %.100s port %d to "
3788 "remote forward to host %.100s port %d, "
3789 "but the request was denied.",
3790 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3791 fwd->listen_host, fwd->listen_port );
3793 logit("Received request from %.100s port %d to remote "
3794 "forward, but the request was denied.",
3795 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
3798 if (fwd->listen_path != NULL) {
3799 return channel_setup_fwd_listener_streamlocal(ssh,
3800 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3802 return channel_setup_fwd_listener_tcpip(ssh,
3803 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3809 * Translate the requested rfwd listen host to something usable for
3813 channel_rfwd_bind_host(const char *listen_host)
3815 if (listen_host == NULL) {
3817 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3824 * Initiate forwarding of connections to port "port" on remote host through
3825 * the secure channel to host:port from local side.
3826 * Returns handle (index) for updating the dynamic listen port with
3827 * channel_update_permission().
3830 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
3832 int r, success = 0, idx = -1;
3833 char *host_to_connect, *listen_host, *listen_path;
3834 int port_to_connect, listen_port;
3836 /* Send the forward request to the remote side. */
3837 if (fwd->listen_path != NULL) {
3838 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3839 (r = sshpkt_put_cstring(ssh,
3840 "streamlocal-forward@openssh.com")) != 0 ||
3841 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3842 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
3843 (r = sshpkt_send(ssh)) != 0 ||
3844 (r = ssh_packet_write_wait(ssh)) != 0)
3845 fatal_fr(r, "request streamlocal");
3847 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3848 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
3849 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3850 (r = sshpkt_put_cstring(ssh,
3851 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
3852 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
3853 (r = sshpkt_send(ssh)) != 0 ||
3854 (r = ssh_packet_write_wait(ssh)) != 0)
3855 fatal_fr(r, "request tcpip-forward");
3857 /* Assume that server accepts the request */
3860 /* Record that connection to this host/port is permitted. */
3861 host_to_connect = listen_host = listen_path = NULL;
3862 port_to_connect = listen_port = 0;
3863 if (fwd->connect_path != NULL) {
3864 host_to_connect = xstrdup(fwd->connect_path);
3865 port_to_connect = PORT_STREAMLOCAL;
3867 host_to_connect = xstrdup(fwd->connect_host);
3868 port_to_connect = fwd->connect_port;
3870 if (fwd->listen_path != NULL) {
3871 listen_path = xstrdup(fwd->listen_path);
3872 listen_port = PORT_STREAMLOCAL;
3874 if (fwd->listen_host != NULL)
3875 listen_host = xstrdup(fwd->listen_host);
3876 listen_port = fwd->listen_port;
3878 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
3879 host_to_connect, port_to_connect,
3880 listen_host, listen_path, listen_port, NULL);
3886 open_match(struct permission *allowed_open, const char *requestedhost,
3889 if (allowed_open->host_to_connect == NULL)
3891 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3892 allowed_open->port_to_connect != requestedport)
3894 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3895 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3901 * Note that in the listen host/port case
3902 * we don't support FWD_PERMIT_ANY_PORT and
3903 * need to translate between the configured-host (listen_host)
3904 * and what we've sent to the remote server (channel_rfwd_bind_host)
3907 open_listen_match_tcpip(struct permission *allowed_open,
3908 const char *requestedhost, u_short requestedport, int translate)
3910 const char *allowed_host;
3912 if (allowed_open->host_to_connect == NULL)
3914 if (allowed_open->listen_port != requestedport)
3916 if (!translate && allowed_open->listen_host == NULL &&
3917 requestedhost == NULL)
3919 allowed_host = translate ?
3920 channel_rfwd_bind_host(allowed_open->listen_host) :
3921 allowed_open->listen_host;
3922 if (allowed_host == NULL || requestedhost == NULL ||
3923 strcmp(allowed_host, requestedhost) != 0)
3929 open_listen_match_streamlocal(struct permission *allowed_open,
3930 const char *requestedpath)
3932 if (allowed_open->host_to_connect == NULL)
3934 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3936 if (allowed_open->listen_path == NULL ||
3937 strcmp(allowed_open->listen_path, requestedpath) != 0)
3943 * Request cancellation of remote forwarding of connection host:port from
3947 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
3948 const char *host, u_short port)
3950 struct ssh_channels *sc = ssh->chanctxt;
3951 struct permission_set *pset = &sc->local_perms;
3954 struct permission *perm = NULL;
3956 for (i = 0; i < pset->num_permitted_user; i++) {
3957 perm = &pset->permitted_user[i];
3958 if (open_listen_match_tcpip(perm, host, port, 0))
3963 debug_f("requested forward not found");
3966 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3967 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
3968 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3969 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
3970 (r = sshpkt_put_u32(ssh, port)) != 0 ||
3971 (r = sshpkt_send(ssh)) != 0)
3972 fatal_fr(r, "send cancel");
3974 fwd_perm_clear(perm); /* unregister */
3980 * Request cancellation of remote forwarding of Unix domain socket
3981 * path from local side.
3984 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
3986 struct ssh_channels *sc = ssh->chanctxt;
3987 struct permission_set *pset = &sc->local_perms;
3990 struct permission *perm = NULL;
3992 for (i = 0; i < pset->num_permitted_user; i++) {
3993 perm = &pset->permitted_user[i];
3994 if (open_listen_match_streamlocal(perm, path))
3999 debug_f("requested forward not found");
4002 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4003 (r = sshpkt_put_cstring(ssh,
4004 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4005 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4006 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4007 (r = sshpkt_send(ssh)) != 0)
4008 fatal_fr(r, "send cancel");
4010 fwd_perm_clear(perm); /* unregister */
4016 * Request cancellation of remote forwarding of a connection from local side.
4019 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4021 if (fwd->listen_path != NULL) {
4022 return channel_request_rforward_cancel_streamlocal(ssh,
4025 return channel_request_rforward_cancel_tcpip(ssh,
4027 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4032 * Permits opening to any host/port if permitted_user[] is empty. This is
4033 * usually called by the server, because the user could connect to any port
4034 * anyway, and the server has no way to know but to trust the client anyway.
4037 channel_permit_all(struct ssh *ssh, int where)
4039 struct permission_set *pset = permission_set_get(ssh, where);
4041 if (pset->num_permitted_user == 0)
4042 pset->all_permitted = 1;
4046 * Permit the specified host/port for forwarding.
4049 channel_add_permission(struct ssh *ssh, int who, int where,
4050 char *host, int port)
4052 int local = where == FORWARD_LOCAL;
4053 struct permission_set *pset = permission_set_get(ssh, where);
4055 debug("allow %s forwarding to host %s port %d",
4056 fwd_ident(who, where), host, port);
4058 * Remote forwards set listen_host/port, local forwards set
4059 * host/port_to_connect.
4061 permission_set_add(ssh, who, where,
4062 local ? host : 0, local ? port : 0,
4063 local ? NULL : host, NULL, local ? 0 : port, NULL);
4064 pset->all_permitted = 0;
4068 * Administratively disable forwarding.
4071 channel_disable_admin(struct ssh *ssh, int where)
4073 channel_clear_permission(ssh, FORWARD_ADM, where);
4074 permission_set_add(ssh, FORWARD_ADM, where,
4075 NULL, 0, NULL, NULL, 0, NULL);
4079 * Clear a list of permitted opens.
4082 channel_clear_permission(struct ssh *ssh, int who, int where)
4084 struct permission **permp;
4087 permission_set_get_array(ssh, who, where, &permp, &npermp);
4088 *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4093 * Update the listen port for a dynamic remote forward, after
4094 * the actual 'newport' has been allocated. If 'newport' < 0 is
4095 * passed then they entry will be invalidated.
4098 channel_update_permission(struct ssh *ssh, int idx, int newport)
4100 struct permission_set *pset = &ssh->chanctxt->local_perms;
4102 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4103 debug_f("index out of range: %d num_permitted_user %d",
4104 idx, pset->num_permitted_user);
4107 debug("%s allowed port %d for forwarding to host %s port %d",
4108 newport > 0 ? "Updating" : "Removing",
4110 pset->permitted_user[idx].host_to_connect,
4111 pset->permitted_user[idx].port_to_connect);
4113 fwd_perm_clear(&pset->permitted_user[idx]);
4115 pset->permitted_user[idx].listen_port =
4116 (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4120 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4122 permitopen_port(const char *p)
4126 if (strcmp(p, "*") == 0)
4127 return FWD_PERMIT_ANY_PORT;
4128 if ((port = a2port(p)) > 0)
4133 /* Try to start non-blocking connect to next host in cctx list */
4135 connect_next(struct channel_connect *cctx)
4137 int sock, saved_errno;
4138 struct sockaddr_un *sunaddr;
4139 char ntop[NI_MAXHOST];
4140 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4142 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4143 switch (cctx->ai->ai_family) {
4145 /* unix:pathname instead of host:port */
4146 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4147 strlcpy(ntop, "unix", sizeof(ntop));
4148 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4152 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4153 ntop, sizeof(ntop), strport, sizeof(strport),
4154 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4155 error("connect_next: getnameinfo failed");
4162 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4163 cctx->ai->ai_protocol)) == -1) {
4164 if (cctx->ai->ai_next == NULL)
4165 error("socket: %.100s", strerror(errno));
4167 verbose("socket: %.100s", strerror(errno));
4170 if (set_nonblock(sock) == -1)
4171 fatal_f("set_nonblock(%d)", sock);
4172 if (connect(sock, cctx->ai->ai_addr,
4173 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4174 debug("connect_next: host %.100s ([%.100s]:%s): "
4175 "%.100s", cctx->host, ntop, strport,
4177 saved_errno = errno;
4179 errno = saved_errno;
4180 continue; /* fail -- try next */
4182 if (cctx->ai->ai_family != AF_UNIX)
4184 debug("connect_next: host %.100s ([%.100s]:%s) "
4185 "in progress, fd=%d", cctx->host, ntop, strport, sock);
4186 cctx->ai = cctx->ai->ai_next;
4193 channel_connect_ctx_free(struct channel_connect *cctx)
4197 if (cctx->aitop->ai_family == AF_UNIX)
4200 freeaddrinfo(cctx->aitop);
4202 memset(cctx, 0, sizeof(*cctx));
4206 * Return connecting socket to remote host:port or local socket path,
4207 * passing back the failure reason if appropriate.
4210 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4211 char *ctype, char *rname, struct channel_connect *cctx,
4212 int *reason, const char **errmsg)
4214 struct addrinfo hints;
4217 char strport[NI_MAXSERV];
4219 if (port == PORT_STREAMLOCAL) {
4220 struct sockaddr_un *sunaddr;
4221 struct addrinfo *ai;
4223 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4224 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4229 * Fake up a struct addrinfo for AF_UNIX connections.
4230 * channel_connect_ctx_free() must check ai_family
4231 * and use free() not freeaddirinfo() for AF_UNIX.
4233 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4234 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4235 ai->ai_addr = (struct sockaddr *)(ai + 1);
4236 ai->ai_addrlen = sizeof(*sunaddr);
4237 ai->ai_family = AF_UNIX;
4238 ai->ai_socktype = socktype;
4239 ai->ai_protocol = PF_UNSPEC;
4240 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4241 sunaddr->sun_family = AF_UNIX;
4242 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4245 memset(&hints, 0, sizeof(hints));
4246 hints.ai_family = ssh->chanctxt->IPv4or6;
4247 hints.ai_socktype = socktype;
4248 snprintf(strport, sizeof strport, "%d", port);
4249 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4252 *errmsg = ssh_gai_strerror(gaierr);
4254 *reason = SSH2_OPEN_CONNECT_FAILED;
4255 error("connect_to %.100s: unknown host (%s)", name,
4256 ssh_gai_strerror(gaierr));
4261 cctx->host = xstrdup(name);
4263 cctx->ai = cctx->aitop;
4265 if ((sock = connect_next(cctx)) == -1) {
4266 error("connect to %.100s port %d failed: %s",
4267 name, port, strerror(errno));
4274 /* Return CONNECTING channel to remote host:port or local socket path */
4276 connect_to(struct ssh *ssh, const char *host, int port,
4277 char *ctype, char *rname)
4279 struct channel_connect cctx;
4283 memset(&cctx, 0, sizeof(cctx));
4284 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4287 channel_connect_ctx_free(&cctx);
4290 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4291 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4292 c->host_port = port;
4293 c->path = xstrdup(host);
4294 c->connect_ctx = cctx;
4300 * returns either the newly connected channel or the downstream channel
4301 * that needs to deal with this connection.
4304 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4305 u_short listen_port, char *ctype, char *rname)
4307 struct ssh_channels *sc = ssh->chanctxt;
4308 struct permission_set *pset = &sc->local_perms;
4310 struct permission *perm;
4312 for (i = 0; i < pset->num_permitted_user; i++) {
4313 perm = &pset->permitted_user[i];
4314 if (open_listen_match_tcpip(perm,
4315 listen_host, listen_port, 1)) {
4316 if (perm->downstream)
4317 return perm->downstream;
4318 if (perm->port_to_connect == 0)
4319 return rdynamic_connect_prepare(ssh,
4321 return connect_to(ssh,
4322 perm->host_to_connect, perm->port_to_connect,
4326 error("WARNING: Server requests forwarding for unknown listen_port %d",
4332 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4333 char *ctype, char *rname)
4335 struct ssh_channels *sc = ssh->chanctxt;
4336 struct permission_set *pset = &sc->local_perms;
4338 struct permission *perm;
4340 for (i = 0; i < pset->num_permitted_user; i++) {
4341 perm = &pset->permitted_user[i];
4342 if (open_listen_match_streamlocal(perm, path)) {
4343 return connect_to(ssh,
4344 perm->host_to_connect, perm->port_to_connect,
4348 error("WARNING: Server requests forwarding for unknown path %.100s",
4353 /* Check if connecting to that port is permitted and connect. */
4355 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4356 char *ctype, char *rname, int *reason, const char **errmsg)
4358 struct ssh_channels *sc = ssh->chanctxt;
4359 struct permission_set *pset = &sc->local_perms;
4360 struct channel_connect cctx;
4362 u_int i, permit, permit_adm = 1;
4364 struct permission *perm;
4366 permit = pset->all_permitted;
4368 for (i = 0; i < pset->num_permitted_user; i++) {
4369 perm = &pset->permitted_user[i];
4370 if (open_match(perm, host, port)) {
4377 if (pset->num_permitted_admin > 0) {
4379 for (i = 0; i < pset->num_permitted_admin; i++) {
4380 perm = &pset->permitted_admin[i];
4381 if (open_match(perm, host, port)) {
4388 if (!permit || !permit_adm) {
4389 logit("Received request from %.100s port %d to connect to "
4390 "host %.100s port %d, but the request was denied.",
4391 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4393 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4397 memset(&cctx, 0, sizeof(cctx));
4398 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4399 &cctx, reason, errmsg);
4401 channel_connect_ctx_free(&cctx);
4405 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4406 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4407 c->host_port = port;
4408 c->path = xstrdup(host);
4409 c->connect_ctx = cctx;
4414 /* Check if connecting to that path is permitted and connect. */
4416 channel_connect_to_path(struct ssh *ssh, const char *path,
4417 char *ctype, char *rname)
4419 struct ssh_channels *sc = ssh->chanctxt;
4420 struct permission_set *pset = &sc->local_perms;
4421 u_int i, permit, permit_adm = 1;
4422 struct permission *perm;
4424 permit = pset->all_permitted;
4426 for (i = 0; i < pset->num_permitted_user; i++) {
4427 perm = &pset->permitted_user[i];
4428 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4435 if (pset->num_permitted_admin > 0) {
4437 for (i = 0; i < pset->num_permitted_admin; i++) {
4438 perm = &pset->permitted_admin[i];
4439 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4446 if (!permit || !permit_adm) {
4447 logit("Received request to connect to path %.100s, "
4448 "but the request was denied.", path);
4451 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4455 channel_send_window_changes(struct ssh *ssh)
4457 struct ssh_channels *sc = ssh->chanctxt;
4462 for (i = 0; i < sc->channels_alloc; i++) {
4463 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4464 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4466 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4468 channel_request_start(ssh, i, "window-change", 0);
4469 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4470 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4471 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4472 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4473 (r = sshpkt_send(ssh)) != 0)
4474 fatal_fr(r, "channel %u; send window-change", i);
4478 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4480 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4485 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4486 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4491 * We need to open the channel before we have a FD,
4492 * so that we can get SOCKS header from peer.
4494 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4495 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4496 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4497 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4498 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4499 fatal_fr(r, "channel %i; confirm", c->self);
4503 /* Return CONNECTING socket to remote host:port or local socket path */
4505 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4507 struct ssh_channels *sc = ssh->chanctxt;
4508 struct permission_set *pset = &sc->local_perms;
4509 struct permission *perm;
4510 struct channel_connect cctx;
4511 u_int i, permit_adm = 1;
4514 if (pset->num_permitted_admin > 0) {
4516 for (i = 0; i < pset->num_permitted_admin; i++) {
4517 perm = &pset->permitted_admin[i];
4518 if (open_match(perm, c->path, c->host_port)) {
4525 debug_f("requested forward not permitted");
4529 memset(&cctx, 0, sizeof(cctx));
4530 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4531 NULL, &cctx, NULL, NULL);
4533 channel_connect_ctx_free(&cctx);
4535 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4536 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4537 c->connect_ctx = cctx;
4538 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4543 /* -- X11 forwarding */
4546 * Creates an internet domain socket for listening for X11 connections.
4547 * Returns 0 and a suitable display number for the DISPLAY variable
4548 * stored in display_numberp , or -1 if an error occurs.
4551 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4552 int x11_use_localhost, int single_connection,
4553 u_int *display_numberp, int **chanids)
4556 int display_number, sock;
4558 struct addrinfo hints, *ai, *aitop;
4559 char strport[NI_MAXSERV];
4560 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4562 if (chanids == NULL)
4565 for (display_number = x11_display_offset;
4566 display_number < MAX_DISPLAYS;
4568 port = 6000 + display_number;
4569 memset(&hints, 0, sizeof(hints));
4570 hints.ai_family = ssh->chanctxt->IPv4or6;
4571 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4572 hints.ai_socktype = SOCK_STREAM;
4573 snprintf(strport, sizeof strport, "%d", port);
4574 if ((gaierr = getaddrinfo(NULL, strport,
4575 &hints, &aitop)) != 0) {
4576 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4579 for (ai = aitop; ai; ai = ai->ai_next) {
4580 if (ai->ai_family != AF_INET &&
4581 ai->ai_family != AF_INET6)
4583 sock = socket(ai->ai_family, ai->ai_socktype,
4586 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4588 && (errno != EPFNOSUPPORT)
4591 error("socket: %.100s", strerror(errno));
4592 freeaddrinfo(aitop);
4595 debug("x11_create_display_inet: Socket family %d not supported",
4600 if (ai->ai_family == AF_INET6)
4601 sock_set_v6only(sock);
4602 if (x11_use_localhost)
4603 set_reuseaddr(sock);
4604 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4605 debug2_f("bind port %d: %.100s", port,
4608 for (n = 0; n < num_socks; n++)
4613 socks[num_socks++] = sock;
4614 if (num_socks == NUM_SOCKS)
4617 freeaddrinfo(aitop);
4621 if (display_number >= MAX_DISPLAYS) {
4622 error("Failed to allocate internet-domain X11 display socket.");
4625 /* Start listening for connections on the socket. */
4626 for (n = 0; n < num_socks; n++) {
4628 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4629 error("listen: %.100s", strerror(errno));
4635 /* Allocate a channel for each socket. */
4636 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4637 for (n = 0; n < num_socks; n++) {
4639 nc = channel_new(ssh, "x11 listener",
4640 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4641 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4642 0, "X11 inet listener", 1);
4643 nc->single_connection = single_connection;
4644 (*chanids)[n] = nc->self;
4648 /* Return the display number for the DISPLAY environment variable. */
4649 *display_numberp = display_number;
4654 connect_local_xsocket_path(const char *pathname)
4657 struct sockaddr_un addr;
4659 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4661 error("socket: %.100s", strerror(errno));
4662 memset(&addr, 0, sizeof(addr));
4663 addr.sun_family = AF_UNIX;
4664 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4665 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4668 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4673 connect_local_xsocket(u_int dnr)
4676 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4677 return connect_local_xsocket_path(buf);
4682 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4686 if (strlcpy(path, display, pathlen) >= pathlen) {
4687 error("%s: display path too long", __func__);
4690 if (display[0] != '/')
4692 if (stat(path, &sbuf) == 0) {
4695 char *dot = strrchr(path, '.');
4698 if (stat(path, &sbuf) == 0) {
4708 x11_connect_display(struct ssh *ssh)
4710 u_int display_number;
4711 const char *display;
4712 char buf[1024], *cp;
4713 struct addrinfo hints, *ai, *aitop;
4714 char strport[NI_MAXSERV];
4715 int gaierr, sock = 0;
4717 /* Try to open a socket for the local X server. */
4718 display = getenv("DISPLAY");
4720 error("DISPLAY not set.");
4724 * Now we decode the value of the DISPLAY variable and make a
4725 * connection to the real X server.
4729 /* Check if display is a path to a socket (as set by launchd). */
4731 char path[PATH_MAX];
4733 if (is_path_to_xsocket(display, path, sizeof(path))) {
4734 debug("x11_connect_display: $DISPLAY is launchd");
4736 /* Create a socket. */
4737 sock = connect_local_xsocket_path(path);
4741 /* OK, we now have a connection to the display. */
4747 * Check if it is a unix domain socket. Unix domain displays are in
4748 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4750 if (strncmp(display, "unix:", 5) == 0 ||
4751 display[0] == ':') {
4752 /* Connect to the unix domain socket. */
4753 if (sscanf(strrchr(display, ':') + 1, "%u",
4754 &display_number) != 1) {
4755 error("Could not parse display number from DISPLAY: "
4759 /* Create a socket. */
4760 sock = connect_local_xsocket(display_number);
4764 /* OK, we now have a connection to the display. */
4768 * Connect to an inet socket. The DISPLAY value is supposedly
4769 * hostname:d[.s], where hostname may also be numeric IP address.
4771 strlcpy(buf, display, sizeof(buf));
4772 cp = strchr(buf, ':');
4774 error("Could not find ':' in DISPLAY: %.100s", display);
4779 * buf now contains the host name. But first we parse the
4782 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4783 error("Could not parse display number from DISPLAY: %.100s",
4788 /* Look up the host address */
4789 memset(&hints, 0, sizeof(hints));
4790 hints.ai_family = ssh->chanctxt->IPv4or6;
4791 hints.ai_socktype = SOCK_STREAM;
4792 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4793 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4794 error("%.100s: unknown host. (%s)", buf,
4795 ssh_gai_strerror(gaierr));
4798 for (ai = aitop; ai; ai = ai->ai_next) {
4799 /* Create a socket. */
4800 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4802 debug2("socket: %.100s", strerror(errno));
4805 /* Connect it to the display. */
4806 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4807 debug2("connect %.100s port %u: %.100s", buf,
4808 6000 + display_number, strerror(errno));
4815 freeaddrinfo(aitop);
4817 error("connect %.100s port %u: %.100s", buf,
4818 6000 + display_number, strerror(errno));
4826 * Requests forwarding of X11 connections, generates fake authentication
4827 * data, and enables authentication spoofing.
4828 * This should be called in the client only.
4831 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
4832 const char *disp, const char *proto, const char *data, int want_reply)
4834 struct ssh_channels *sc = ssh->chanctxt;
4835 u_int data_len = (u_int) strlen(data) / 2;
4839 int r, screen_number;
4841 if (sc->x11_saved_display == NULL)
4842 sc->x11_saved_display = xstrdup(disp);
4843 else if (strcmp(disp, sc->x11_saved_display) != 0) {
4844 error("x11_request_forwarding_with_spoofing: different "
4845 "$DISPLAY already forwarded");
4849 cp = strchr(disp, ':');
4851 cp = strchr(cp, '.');
4853 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4857 if (sc->x11_saved_proto == NULL) {
4858 /* Save protocol name. */
4859 sc->x11_saved_proto = xstrdup(proto);
4861 /* Extract real authentication data. */
4862 sc->x11_saved_data = xmalloc(data_len);
4863 for (i = 0; i < data_len; i++) {
4864 if (sscanf(data + 2 * i, "%2x", &value) != 1) {
4865 fatal("x11_request_forwarding: bad "
4866 "authentication data: %.100s", data);
4868 sc->x11_saved_data[i] = value;
4870 sc->x11_saved_data_len = data_len;
4872 /* Generate fake data of the same length. */
4873 sc->x11_fake_data = xmalloc(data_len);
4874 arc4random_buf(sc->x11_fake_data, data_len);
4875 sc->x11_fake_data_len = data_len;
4878 /* Convert the fake data into hex. */
4879 new_data = tohex(sc->x11_fake_data, data_len);
4881 /* Send the request packet. */
4882 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
4883 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
4884 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
4885 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
4886 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
4887 (r = sshpkt_send(ssh)) != 0 ||
4888 (r = ssh_packet_write_wait(ssh)) != 0)
4889 fatal_fr(r, "send x11-req");