1 /* $OpenBSD: channels.c,v 1.408 2021/09/14 11:04:21 mbuhl 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);
636 } else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
641 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
642 s = channel_open_message(ssh);
643 debug3("channel %d: status: %s", c->self, s);
647 channel_close_fds(ssh, c);
648 sshbuf_free(c->input);
649 sshbuf_free(c->output);
650 sshbuf_free(c->extended);
651 c->input = c->output = c->extended = NULL;
652 free(c->remote_name);
653 c->remote_name = NULL;
656 free(c->listening_addr);
657 c->listening_addr = NULL;
658 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
659 if (cc->abandon_cb != NULL)
660 cc->abandon_cb(ssh, c, cc->ctx);
661 TAILQ_REMOVE(&c->status_confirms, cc, entry);
662 freezero(cc, sizeof(*cc));
664 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
665 c->filter_cleanup(ssh, c->self, c->filter_ctx);
666 sc->channels[c->self] = NULL;
667 freezero(c, sizeof(*c));
671 channel_free_all(struct ssh *ssh)
674 struct ssh_channels *sc = ssh->chanctxt;
676 for (i = 0; i < sc->channels_alloc; i++)
677 if (sc->channels[i] != NULL)
678 channel_free(ssh, sc->channels[i]);
682 sc->channels_alloc = 0;
683 sc->channel_max_fd = 0;
685 free(sc->x11_saved_display);
686 sc->x11_saved_display = NULL;
688 free(sc->x11_saved_proto);
689 sc->x11_saved_proto = NULL;
691 free(sc->x11_saved_data);
692 sc->x11_saved_data = NULL;
693 sc->x11_saved_data_len = 0;
695 free(sc->x11_fake_data);
696 sc->x11_fake_data = NULL;
697 sc->x11_fake_data_len = 0;
701 * Closes the sockets/fds of all channels. This is used to close extra file
702 * descriptors after a fork.
705 channel_close_all(struct ssh *ssh)
709 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
710 if (ssh->chanctxt->channels[i] != NULL)
711 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
715 * Stop listening to channels.
718 channel_stop_listening(struct ssh *ssh)
723 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
724 c = ssh->chanctxt->channels[i];
727 case SSH_CHANNEL_AUTH_SOCKET:
728 case SSH_CHANNEL_PORT_LISTENER:
729 case SSH_CHANNEL_RPORT_LISTENER:
730 case SSH_CHANNEL_X11_LISTENER:
731 case SSH_CHANNEL_UNIX_LISTENER:
732 case SSH_CHANNEL_RUNIX_LISTENER:
733 channel_close_fd(ssh, c, &c->sock);
734 channel_free(ssh, c);
742 * Returns true if no channel has too much buffered data, and false if one or
743 * more channel is overfull.
746 channel_not_very_much_buffered_data(struct ssh *ssh)
749 u_int maxsize = ssh_packet_get_maxsize(ssh);
752 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
753 c = ssh->chanctxt->channels[i];
754 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
756 if (sshbuf_len(c->output) > maxsize) {
757 debug2("channel %d: big output buffer %zu > %u",
758 c->self, sshbuf_len(c->output), maxsize);
765 /* Returns true if any channel is still open. */
767 channel_still_open(struct ssh *ssh)
772 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
773 c = ssh->chanctxt->channels[i];
777 case SSH_CHANNEL_X11_LISTENER:
778 case SSH_CHANNEL_PORT_LISTENER:
779 case SSH_CHANNEL_RPORT_LISTENER:
780 case SSH_CHANNEL_MUX_LISTENER:
781 case SSH_CHANNEL_CLOSED:
782 case SSH_CHANNEL_AUTH_SOCKET:
783 case SSH_CHANNEL_DYNAMIC:
784 case SSH_CHANNEL_RDYNAMIC_OPEN:
785 case SSH_CHANNEL_CONNECTING:
786 case SSH_CHANNEL_ZOMBIE:
787 case SSH_CHANNEL_ABANDONED:
788 case SSH_CHANNEL_UNIX_LISTENER:
789 case SSH_CHANNEL_RUNIX_LISTENER:
791 case SSH_CHANNEL_LARVAL:
793 case SSH_CHANNEL_OPENING:
794 case SSH_CHANNEL_OPEN:
795 case SSH_CHANNEL_RDYNAMIC_FINISH:
796 case SSH_CHANNEL_X11_OPEN:
797 case SSH_CHANNEL_MUX_CLIENT:
798 case SSH_CHANNEL_MUX_PROXY:
801 fatal_f("bad channel type %d", c->type);
808 /* Returns the id of an open channel suitable for keepaliving */
810 channel_find_open(struct ssh *ssh)
815 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
816 c = ssh->chanctxt->channels[i];
817 if (c == NULL || !c->have_remote_id)
820 case SSH_CHANNEL_CLOSED:
821 case SSH_CHANNEL_DYNAMIC:
822 case SSH_CHANNEL_RDYNAMIC_OPEN:
823 case SSH_CHANNEL_RDYNAMIC_FINISH:
824 case SSH_CHANNEL_X11_LISTENER:
825 case SSH_CHANNEL_PORT_LISTENER:
826 case SSH_CHANNEL_RPORT_LISTENER:
827 case SSH_CHANNEL_MUX_LISTENER:
828 case SSH_CHANNEL_MUX_CLIENT:
829 case SSH_CHANNEL_MUX_PROXY:
830 case SSH_CHANNEL_OPENING:
831 case SSH_CHANNEL_CONNECTING:
832 case SSH_CHANNEL_ZOMBIE:
833 case SSH_CHANNEL_ABANDONED:
834 case SSH_CHANNEL_UNIX_LISTENER:
835 case SSH_CHANNEL_RUNIX_LISTENER:
837 case SSH_CHANNEL_LARVAL:
838 case SSH_CHANNEL_AUTH_SOCKET:
839 case SSH_CHANNEL_OPEN:
840 case SSH_CHANNEL_X11_OPEN:
843 fatal_f("bad channel type %d", c->type);
850 /* Returns the state of the channel's extended usage flag */
852 channel_format_extended_usage(const Channel *c)
857 switch (c->extended_usage) {
858 case CHAN_EXTENDED_WRITE:
860 case CHAN_EXTENDED_READ:
862 case CHAN_EXTENDED_IGNORE:
870 channel_format_status(const Channel *c)
874 xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
875 "fd %d/%d/%d sock %d cc %d",
877 c->have_remote_id ? "r" : "nr", c->remote_id,
878 c->istate, sshbuf_len(c->input),
879 c->ostate, sshbuf_len(c->output),
880 channel_format_extended_usage(c), sshbuf_len(c->extended),
881 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
886 * Returns a message describing the currently open forwarded connections,
887 * suitable for sending to the client. The message contains crlf pairs for
891 channel_open_message(struct ssh *ssh)
899 if ((buf = sshbuf_new()) == NULL)
900 fatal_f("sshbuf_new");
901 if ((r = sshbuf_putf(buf,
902 "The following connections are open:\r\n")) != 0)
903 fatal_fr(r, "sshbuf_putf");
904 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
905 c = ssh->chanctxt->channels[i];
909 case SSH_CHANNEL_X11_LISTENER:
910 case SSH_CHANNEL_PORT_LISTENER:
911 case SSH_CHANNEL_RPORT_LISTENER:
912 case SSH_CHANNEL_CLOSED:
913 case SSH_CHANNEL_AUTH_SOCKET:
914 case SSH_CHANNEL_ZOMBIE:
915 case SSH_CHANNEL_ABANDONED:
916 case SSH_CHANNEL_MUX_LISTENER:
917 case SSH_CHANNEL_UNIX_LISTENER:
918 case SSH_CHANNEL_RUNIX_LISTENER:
920 case SSH_CHANNEL_LARVAL:
921 case SSH_CHANNEL_OPENING:
922 case SSH_CHANNEL_CONNECTING:
923 case SSH_CHANNEL_DYNAMIC:
924 case SSH_CHANNEL_RDYNAMIC_OPEN:
925 case SSH_CHANNEL_RDYNAMIC_FINISH:
926 case SSH_CHANNEL_OPEN:
927 case SSH_CHANNEL_X11_OPEN:
928 case SSH_CHANNEL_MUX_PROXY:
929 case SSH_CHANNEL_MUX_CLIENT:
930 cp = channel_format_status(c);
931 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
932 c->self, c->remote_name, cp)) != 0) {
934 fatal_fr(r, "sshbuf_putf");
939 fatal_f("bad channel type %d", c->type);
943 if ((ret = sshbuf_dup_string(buf)) == NULL)
944 fatal_f("sshbuf_dup_string");
950 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
954 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
955 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
956 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
957 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
958 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
959 fatal_r(r, "%s: channel %i: open", where, c->self);
964 channel_send_open(struct ssh *ssh, int id)
966 Channel *c = channel_lookup(ssh, id);
970 logit("channel_send_open: %d: bad id", id);
973 debug2("channel %d: send open", id);
974 open_preamble(ssh, __func__, c, c->ctype);
975 if ((r = sshpkt_send(ssh)) != 0)
976 fatal_fr(r, "channel %i", c->self);
980 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
982 Channel *c = channel_lookup(ssh, id);
986 logit_f("%d: unknown channel id", id);
989 if (!c->have_remote_id)
990 fatal_f("channel %d: no remote id", c->self);
992 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
993 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
994 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
995 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
996 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
997 fatal_fr(r, "channel %i", c->self);
1002 channel_register_status_confirm(struct ssh *ssh, int id,
1003 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1005 struct channel_confirm *cc;
1008 if ((c = channel_lookup(ssh, id)) == NULL)
1009 fatal_f("%d: bad id", id);
1011 cc = xcalloc(1, sizeof(*cc));
1013 cc->abandon_cb = abandon_cb;
1015 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1019 channel_register_open_confirm(struct ssh *ssh, int id,
1020 channel_open_fn *fn, void *ctx)
1022 Channel *c = channel_lookup(ssh, id);
1025 logit_f("%d: bad id", id);
1028 c->open_confirm = fn;
1029 c->open_confirm_ctx = ctx;
1033 channel_register_cleanup(struct ssh *ssh, int id,
1034 channel_callback_fn *fn, int do_close)
1036 Channel *c = channel_by_id(ssh, id);
1039 logit_f("%d: bad id", id);
1042 c->detach_user = fn;
1043 c->detach_close = do_close;
1047 channel_cancel_cleanup(struct ssh *ssh, int id)
1049 Channel *c = channel_by_id(ssh, id);
1052 logit_f("%d: bad id", id);
1055 c->detach_user = NULL;
1056 c->detach_close = 0;
1060 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1061 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1063 Channel *c = channel_lookup(ssh, id);
1066 logit_f("%d: bad id", id);
1069 c->input_filter = ifn;
1070 c->output_filter = ofn;
1071 c->filter_ctx = ctx;
1072 c->filter_cleanup = cfn;
1076 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1077 int extusage, int nonblock, int is_tty, u_int window_max)
1079 Channel *c = channel_lookup(ssh, id);
1082 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1083 fatal("channel_activate for non-larval channel %d.", id);
1084 if (!c->have_remote_id)
1085 fatal_f("channel %d: no remote id", c->self);
1087 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1088 c->type = SSH_CHANNEL_OPEN;
1089 c->local_window = c->local_window_max = window_max;
1091 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1092 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1093 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1094 (r = sshpkt_send(ssh)) != 0)
1095 fatal_fr(r, "channel %i", c->self);
1099 channel_pre_listener(struct ssh *ssh, Channel *c,
1100 fd_set *readset, fd_set *writeset)
1102 FD_SET(c->sock, readset);
1106 channel_pre_connecting(struct ssh *ssh, Channel *c,
1107 fd_set *readset, fd_set *writeset)
1109 debug3("channel %d: waiting for connection", c->self);
1110 FD_SET(c->sock, writeset);
1114 channel_pre_open(struct ssh *ssh, Channel *c,
1115 fd_set *readset, fd_set *writeset)
1117 if (c->istate == CHAN_INPUT_OPEN &&
1118 c->remote_window > 0 &&
1119 sshbuf_len(c->input) < c->remote_window &&
1120 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1121 FD_SET(c->rfd, readset);
1122 if (c->ostate == CHAN_OUTPUT_OPEN ||
1123 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1124 if (sshbuf_len(c->output) > 0) {
1125 FD_SET(c->wfd, writeset);
1126 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1127 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1128 debug2("channel %d: "
1129 "obuf_empty delayed efd %d/(%zu)", c->self,
1130 c->efd, sshbuf_len(c->extended));
1132 chan_obuf_empty(ssh, c);
1135 /** XXX check close conditions, too */
1136 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1137 c->ostate == CHAN_OUTPUT_CLOSED)) {
1138 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1139 sshbuf_len(c->extended) > 0)
1140 FD_SET(c->efd, writeset);
1141 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1142 (c->extended_usage == CHAN_EXTENDED_READ ||
1143 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1144 sshbuf_len(c->extended) < c->remote_window)
1145 FD_SET(c->efd, readset);
1147 /* XXX: What about efd? races? */
1151 * This is a special state for X11 authentication spoofing. An opened X11
1152 * connection (when authentication spoofing is being done) remains in this
1153 * state until the first packet has been completely read. The authentication
1154 * data in that packet is then substituted by the real data if it matches the
1155 * fake data, and the channel is put into normal mode.
1156 * XXX All this happens at the client side.
1157 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1160 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1162 struct ssh_channels *sc = ssh->chanctxt;
1164 u_int proto_len, data_len;
1166 /* Is this being called after the refusal deadline? */
1167 if (sc->x11_refuse_time != 0 &&
1168 (u_int)monotime() >= sc->x11_refuse_time) {
1169 verbose("Rejected X11 connection after ForwardX11Timeout "
1174 /* Check if the fixed size part of the packet is in buffer. */
1175 if (sshbuf_len(b) < 12)
1178 /* Parse the lengths of variable-length fields. */
1179 ucp = sshbuf_mutable_ptr(b);
1180 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1181 proto_len = 256 * ucp[6] + ucp[7];
1182 data_len = 256 * ucp[8] + ucp[9];
1183 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1184 proto_len = ucp[6] + 256 * ucp[7];
1185 data_len = ucp[8] + 256 * ucp[9];
1187 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1192 /* Check if the whole packet is in buffer. */
1194 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1197 /* Check if authentication protocol matches. */
1198 if (proto_len != strlen(sc->x11_saved_proto) ||
1199 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1200 debug2("X11 connection uses different authentication protocol.");
1203 /* Check if authentication data matches our fake data. */
1204 if (data_len != sc->x11_fake_data_len ||
1205 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1206 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1207 debug2("X11 auth data does not match fake data.");
1210 /* Check fake data length */
1211 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1212 error("X11 fake_data_len %d != saved_data_len %d",
1213 sc->x11_fake_data_len, sc->x11_saved_data_len);
1217 * Received authentication protocol and data match
1218 * our fake data. Substitute the fake data with real
1221 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1222 sc->x11_saved_data, sc->x11_saved_data_len);
1227 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1228 fd_set *readset, fd_set *writeset)
1230 int ret = x11_open_helper(ssh, c->output);
1232 /* c->force_drain = 1; */
1235 c->type = SSH_CHANNEL_OPEN;
1236 channel_pre_open(ssh, c, readset, writeset);
1237 } else if (ret == -1) {
1238 logit("X11 connection rejected because of wrong authentication.");
1239 debug2("X11 rejected %d i%d/o%d",
1240 c->self, c->istate, c->ostate);
1241 chan_read_failed(ssh, c);
1242 sshbuf_reset(c->input);
1243 chan_ibuf_empty(ssh, c);
1244 sshbuf_reset(c->output);
1245 chan_write_failed(ssh, c);
1246 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1251 channel_pre_mux_client(struct ssh *ssh,
1252 Channel *c, fd_set *readset, fd_set *writeset)
1254 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1255 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1256 FD_SET(c->rfd, readset);
1257 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1258 /* clear buffer immediately (discard any partial packet) */
1259 sshbuf_reset(c->input);
1260 chan_ibuf_empty(ssh, c);
1261 /* Start output drain. XXX just kill chan? */
1262 chan_rcvd_oclose(ssh, c);
1264 if (c->ostate == CHAN_OUTPUT_OPEN ||
1265 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1266 if (sshbuf_len(c->output) > 0)
1267 FD_SET(c->wfd, writeset);
1268 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1269 chan_obuf_empty(ssh, c);
1273 /* try to decode a socks4 header */
1275 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1279 u_int len, have, i, found, need;
1284 u_int16_t dest_port;
1285 struct in_addr dest_addr;
1289 debug2("channel %d: decode socks4", c->self);
1291 have = sshbuf_len(input);
1292 len = sizeof(s4_req);
1295 p = sshbuf_ptr(input);
1298 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1299 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1300 debug2("channel %d: socks4a request", c->self);
1301 /* ... and needs an extra string (the hostname) */
1304 /* Check for terminating NUL on the string(s) */
1305 for (found = 0, i = len; i < have; i++) {
1312 /* the peer is probably sending garbage */
1313 debug("channel %d: decode socks4: too long",
1320 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1321 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1322 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1323 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1324 debug_r(r, "channels %d: decode socks4", c->self);
1327 have = sshbuf_len(input);
1328 p = sshbuf_ptr(input);
1329 if (memchr(p, '\0', have) == NULL) {
1330 error("channel %d: decode socks4: unterminated user", c->self);
1334 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1335 len++; /* trailing '\0' */
1336 strlcpy(username, p, sizeof(username));
1337 if ((r = sshbuf_consume(input, len)) != 0)
1338 fatal_fr(r, "channel %d: consume", c->self);
1341 if (need == 1) { /* SOCKS4: one string */
1342 host = inet_ntoa(s4_req.dest_addr);
1343 c->path = xstrdup(host);
1344 } else { /* SOCKS4A: two strings */
1345 have = sshbuf_len(input);
1346 p = sshbuf_ptr(input);
1347 if (memchr(p, '\0', have) == NULL) {
1348 error("channel %d: decode socks4a: host not nul "
1349 "terminated", c->self);
1353 debug2("channel %d: decode socks4a: host %s/%d",
1355 len++; /* trailing '\0' */
1356 if (len > NI_MAXHOST) {
1357 error("channel %d: hostname \"%.100s\" too long",
1361 c->path = xstrdup(p);
1362 if ((r = sshbuf_consume(input, len)) != 0)
1363 fatal_fr(r, "channel %d: consume", c->self);
1365 c->host_port = ntohs(s4_req.dest_port);
1367 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1368 c->self, c->path, c->host_port, s4_req.command);
1370 if (s4_req.command != 1) {
1371 debug("channel %d: cannot handle: %s cn %d",
1372 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1375 s4_rsp.version = 0; /* vn: 0 for reply */
1376 s4_rsp.command = 90; /* cd: req granted */
1377 s4_rsp.dest_port = 0; /* ignored */
1378 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1379 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1380 fatal_fr(r, "channel %d: append reply", c->self);
1384 /* try to decode a socks5 header */
1385 #define SSH_SOCKS5_AUTHDONE 0x1000
1386 #define SSH_SOCKS5_NOAUTH 0x00
1387 #define SSH_SOCKS5_IPV4 0x01
1388 #define SSH_SOCKS5_DOMAIN 0x03
1389 #define SSH_SOCKS5_IPV6 0x04
1390 #define SSH_SOCKS5_CONNECT 0x01
1391 #define SSH_SOCKS5_SUCCESS 0x00
1394 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1396 /* XXX use get/put_u8 instead of trusting struct padding */
1403 u_int16_t dest_port;
1404 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1406 u_int have, need, i, found, nmethods, addrlen, af;
1409 debug2("channel %d: decode socks5", c->self);
1410 p = sshbuf_ptr(input);
1413 have = sshbuf_len(input);
1414 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1415 /* format: ver | nmethods | methods */
1419 if (have < nmethods + 2)
1421 /* look for method: "NO AUTHENTICATION REQUIRED" */
1422 for (found = 0, i = 2; i < nmethods + 2; i++) {
1423 if (p[i] == SSH_SOCKS5_NOAUTH) {
1429 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1433 if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1434 fatal_fr(r, "channel %d: consume", c->self);
1435 /* version, method */
1436 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1437 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1438 fatal_fr(r, "channel %d: append reply", c->self);
1439 c->flags |= SSH_SOCKS5_AUTHDONE;
1440 debug2("channel %d: socks5 auth done", c->self);
1441 return 0; /* need more */
1443 debug2("channel %d: socks5 post auth", c->self);
1444 if (have < sizeof(s5_req)+1)
1445 return 0; /* need more */
1446 memcpy(&s5_req, p, sizeof(s5_req));
1447 if (s5_req.version != 0x05 ||
1448 s5_req.command != SSH_SOCKS5_CONNECT ||
1449 s5_req.reserved != 0x00) {
1450 debug2("channel %d: only socks5 connect supported", c->self);
1453 switch (s5_req.atyp){
1454 case SSH_SOCKS5_IPV4:
1458 case SSH_SOCKS5_DOMAIN:
1459 addrlen = p[sizeof(s5_req)];
1462 case SSH_SOCKS5_IPV6:
1467 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1470 need = sizeof(s5_req) + addrlen + 2;
1471 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1475 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1476 fatal_fr(r, "channel %d: consume", c->self);
1477 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1478 /* host string length */
1479 if ((r = sshbuf_consume(input, 1)) != 0)
1480 fatal_fr(r, "channel %d: consume", c->self);
1482 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1483 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1484 debug_r(r, "channel %d: parse addr/port", c->self);
1487 dest_addr[addrlen] = '\0';
1490 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1491 if (addrlen >= NI_MAXHOST) {
1492 error("channel %d: dynamic request: socks5 hostname "
1493 "\"%.100s\" too long", c->self, dest_addr);
1496 c->path = xstrdup(dest_addr);
1498 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1500 c->path = xstrdup(ntop);
1502 c->host_port = ntohs(dest_port);
1504 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1505 c->self, c->path, c->host_port, s5_req.command);
1507 s5_rsp.version = 0x05;
1508 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1509 s5_rsp.reserved = 0; /* ignored */
1510 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1511 dest_port = 0; /* ignored */
1513 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1514 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1515 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1516 fatal_fr(r, "channel %d: append reply", c->self);
1521 channel_connect_stdio_fwd(struct ssh *ssh,
1522 const char *host_to_connect, u_short port_to_connect,
1523 int in, int out, int nonblock)
1527 debug_f("%s:%d", host_to_connect, port_to_connect);
1529 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1530 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1531 0, "stdio-forward", nonblock);
1533 c->path = xstrdup(host_to_connect);
1534 c->host_port = port_to_connect;
1535 c->listening_port = 0;
1538 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1539 port_open_helper(ssh, c, "direct-tcpip");
1544 /* dynamic port forwarding */
1546 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1547 fd_set *readset, fd_set *writeset)
1553 have = sshbuf_len(c->input);
1554 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1555 /* sshbuf_dump(c->input, stderr); */
1556 /* check if the fixed size part of the packet is in buffer. */
1559 FD_SET(c->sock, readset);
1562 /* try to guess the protocol */
1563 p = sshbuf_ptr(c->input);
1564 /* XXX sshbuf_peek_u8? */
1567 ret = channel_decode_socks4(c, c->input, c->output);
1570 ret = channel_decode_socks5(c, c->input, c->output);
1577 chan_mark_dead(ssh, c);
1578 } else if (ret == 0) {
1579 debug2("channel %d: pre_dynamic: need more", c->self);
1581 FD_SET(c->sock, readset);
1582 if (sshbuf_len(c->output))
1583 FD_SET(c->sock, writeset);
1585 /* switch to the next state */
1586 c->type = SSH_CHANNEL_OPENING;
1587 port_open_helper(ssh, c, "direct-tcpip");
1591 /* simulate read-error */
1593 rdynamic_close(struct ssh *ssh, Channel *c)
1595 c->type = SSH_CHANNEL_OPEN;
1596 chan_read_failed(ssh, c);
1597 sshbuf_reset(c->input);
1598 chan_ibuf_empty(ssh, c);
1599 sshbuf_reset(c->output);
1600 chan_write_failed(ssh, c);
1603 /* reverse dynamic port forwarding */
1605 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1611 have = sshbuf_len(c->output);
1612 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1613 /* sshbuf_dump(c->output, stderr); */
1615 if (c->flags & CHAN_EOF_RCVD) {
1616 if ((r = sshbuf_consume(c->output, have)) != 0)
1617 fatal_fr(r, "channel %d: consume", c->self);
1618 rdynamic_close(ssh, c);
1621 /* check if the fixed size part of the packet is in buffer. */
1624 /* try to guess the protocol */
1625 p = sshbuf_ptr(c->output);
1628 /* switch input/output for reverse forwarding */
1629 ret = channel_decode_socks4(c, c->output, c->input);
1632 ret = channel_decode_socks5(c, c->output, c->input);
1639 rdynamic_close(ssh, c);
1640 } else if (ret == 0) {
1641 debug2("channel %d: pre_rdynamic: need more", c->self);
1642 /* send socks request to peer */
1643 len = sshbuf_len(c->input);
1644 if (len > 0 && len < c->remote_window) {
1645 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1646 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1647 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1648 (r = sshpkt_send(ssh)) != 0) {
1649 fatal_fr(r, "channel %i: rdynamic", c->self);
1651 if ((r = sshbuf_consume(c->input, len)) != 0)
1652 fatal_fr(r, "channel %d: consume", c->self);
1653 c->remote_window -= len;
1655 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1656 /* the connect failed */
1657 rdynamic_close(ssh, c);
1661 /* This is our fake X11 server socket. */
1663 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1664 fd_set *readset, fd_set *writeset)
1667 struct sockaddr_storage addr;
1668 int r, newsock, oerrno, remote_port;
1670 char buf[16384], *remote_ipaddr;
1672 if (!FD_ISSET(c->sock, readset))
1675 debug("X11 connection requested.");
1676 addrlen = sizeof(addr);
1677 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1678 if (c->single_connection) {
1680 debug2("single_connection: closing X11 listener.");
1681 channel_close_fd(ssh, c, &c->sock);
1682 chan_mark_dead(ssh, c);
1685 if (newsock == -1) {
1686 if (errno != EINTR && errno != EWOULDBLOCK &&
1687 errno != ECONNABORTED)
1688 error("accept: %.100s", strerror(errno));
1689 if (errno == EMFILE || errno == ENFILE)
1690 c->notbefore = monotime() + 1;
1693 set_nodelay(newsock);
1694 remote_ipaddr = get_peer_ipaddr(newsock);
1695 remote_port = get_peer_port(newsock);
1696 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1697 remote_ipaddr, remote_port);
1699 nc = channel_new(ssh, "accepted x11 socket",
1700 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1701 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1702 open_preamble(ssh, __func__, nc, "x11");
1703 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1704 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1705 fatal_fr(r, "channel %i: reply", c->self);
1707 if ((r = sshpkt_send(ssh)) != 0)
1708 fatal_fr(r, "channel %i: send", c->self);
1709 free(remote_ipaddr);
1713 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1715 char *local_ipaddr = get_local_ipaddr(c->sock);
1716 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1717 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1718 int remote_port = get_peer_port(c->sock);
1721 if (remote_port == -1) {
1722 /* Fake addr/port to appease peers that validate it (Tectia) */
1723 free(remote_ipaddr);
1724 remote_ipaddr = xstrdup("127.0.0.1");
1725 remote_port = 65535;
1728 free(c->remote_name);
1729 xasprintf(&c->remote_name,
1730 "%s: listening port %d for %.100s port %d, "
1731 "connect from %.200s port %d to %.100s port %d",
1732 rtype, c->listening_port, c->path, c->host_port,
1733 remote_ipaddr, remote_port, local_ipaddr, local_port);
1735 open_preamble(ssh, __func__, c, rtype);
1736 if (strcmp(rtype, "direct-tcpip") == 0) {
1737 /* target host, port */
1738 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1739 (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1740 fatal_fr(r, "channel %i: reply", c->self);
1741 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1743 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1744 fatal_fr(r, "channel %i: reply", c->self);
1745 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1747 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1748 fatal_fr(r, "channel %i: reply", c->self);
1750 /* listen address, port */
1751 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1752 (r = sshpkt_put_u32(ssh, local_port)) != 0)
1753 fatal_fr(r, "channel %i: reply", c->self);
1755 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1756 /* reserved for future owner/mode info */
1757 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1758 fatal_fr(r, "channel %i: reply", c->self);
1760 /* originator host and port */
1761 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1762 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1763 fatal_fr(r, "channel %i: reply", c->self);
1765 if ((r = sshpkt_send(ssh)) != 0)
1766 fatal_fr(r, "channel %i: send", c->self);
1767 free(remote_ipaddr);
1772 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1774 ssh->chanctxt->x11_refuse_time = refuse_time;
1778 * This socket is listening for connections to a forwarded TCP/IP port.
1781 channel_post_port_listener(struct ssh *ssh, Channel *c,
1782 fd_set *readset, fd_set *writeset)
1785 struct sockaddr_storage addr;
1786 int newsock, nextstate;
1790 if (!FD_ISSET(c->sock, readset))
1793 debug("Connection to port %d forwarding to %.100s port %d requested.",
1794 c->listening_port, c->path, c->host_port);
1796 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1797 nextstate = SSH_CHANNEL_OPENING;
1798 rtype = "forwarded-tcpip";
1799 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1800 nextstate = SSH_CHANNEL_OPENING;
1801 rtype = "forwarded-streamlocal@openssh.com";
1802 } else if (c->host_port == PORT_STREAMLOCAL) {
1803 nextstate = SSH_CHANNEL_OPENING;
1804 rtype = "direct-streamlocal@openssh.com";
1805 } else if (c->host_port == 0) {
1806 nextstate = SSH_CHANNEL_DYNAMIC;
1807 rtype = "dynamic-tcpip";
1809 nextstate = SSH_CHANNEL_OPENING;
1810 rtype = "direct-tcpip";
1813 addrlen = sizeof(addr);
1814 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1815 if (newsock == -1) {
1816 if (errno != EINTR && errno != EWOULDBLOCK &&
1817 errno != ECONNABORTED)
1818 error("accept: %.100s", strerror(errno));
1819 if (errno == EMFILE || errno == ENFILE)
1820 c->notbefore = monotime() + 1;
1823 if (c->host_port != PORT_STREAMLOCAL)
1824 set_nodelay(newsock);
1825 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1826 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1827 nc->listening_port = c->listening_port;
1828 nc->host_port = c->host_port;
1829 if (c->path != NULL)
1830 nc->path = xstrdup(c->path);
1832 if (nextstate != SSH_CHANNEL_DYNAMIC)
1833 port_open_helper(ssh, nc, rtype);
1837 * This is the authentication agent socket listening for connections from
1841 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1842 fd_set *readset, fd_set *writeset)
1846 struct sockaddr_storage addr;
1849 if (!FD_ISSET(c->sock, readset))
1852 addrlen = sizeof(addr);
1853 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1854 if (newsock == -1) {
1855 error("accept from auth socket: %.100s", strerror(errno));
1856 if (errno == EMFILE || errno == ENFILE)
1857 c->notbefore = monotime() + 1;
1860 nc = channel_new(ssh, "accepted auth socket",
1861 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1862 c->local_window_max, c->local_maxpacket,
1863 0, "accepted auth socket", 1);
1864 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1865 if ((r = sshpkt_send(ssh)) != 0)
1866 fatal_fr(r, "channel %i", c->self);
1870 channel_post_connecting(struct ssh *ssh, Channel *c,
1871 fd_set *readset, fd_set *writeset)
1873 int err = 0, sock, isopen, r;
1874 socklen_t sz = sizeof(err);
1876 if (!FD_ISSET(c->sock, writeset))
1878 if (!c->have_remote_id)
1879 fatal_f("channel %d: no remote id", c->self);
1880 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1881 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1882 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1884 error("getsockopt SO_ERROR failed");
1887 debug("channel %d: connected to %s port %d",
1888 c->self, c->connect_ctx.host, c->connect_ctx.port);
1889 channel_connect_ctx_free(&c->connect_ctx);
1890 c->type = SSH_CHANNEL_OPEN;
1892 /* no message necessary */
1894 if ((r = sshpkt_start(ssh,
1895 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1896 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1897 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1898 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1899 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1900 (r = sshpkt_send(ssh)) != 0)
1901 fatal_fr(r, "channel %i open confirm", c->self);
1904 debug("channel %d: connection failed: %s",
1905 c->self, strerror(err));
1906 /* Try next address, if any */
1907 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1909 c->sock = c->rfd = c->wfd = sock;
1910 channel_find_maxfd(ssh->chanctxt);
1913 /* Exhausted all addresses */
1914 error("connect_to %.100s port %d: failed.",
1915 c->connect_ctx.host, c->connect_ctx.port);
1916 channel_connect_ctx_free(&c->connect_ctx);
1918 rdynamic_close(ssh, c);
1920 if ((r = sshpkt_start(ssh,
1921 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1922 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1923 (r = sshpkt_put_u32(ssh,
1924 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1925 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1926 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1927 (r = sshpkt_send(ssh)) != 0)
1928 fatal_fr(r, "channel %i: failure", c->self);
1929 chan_mark_dead(ssh, c);
1935 channel_handle_rfd(struct ssh *ssh, Channel *c,
1936 fd_set *readset, fd_set *writeset)
1938 char buf[CHAN_RBUF];
1942 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1944 if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1948 len = read(c->rfd, buf, sizeof(buf));
1949 if (len == -1 && (errno == EINTR ||
1950 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1952 #ifndef PTY_ZEROREAD
1955 if ((!c->isatty && len <= 0) ||
1956 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1958 debug2("channel %d: read<=0 rfd %d len %zd",
1959 c->self, c->rfd, len);
1960 if (c->type != SSH_CHANNEL_OPEN) {
1961 debug2("channel %d: not open", c->self);
1962 chan_mark_dead(ssh, c);
1965 chan_read_failed(ssh, c);
1969 if (c->input_filter != NULL) {
1970 if (c->input_filter(ssh, c, buf, len) == -1) {
1971 debug2("channel %d: filter stops", c->self);
1972 chan_read_failed(ssh, c);
1974 } else if (c->datagram) {
1975 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1976 fatal_fr(r, "channel %i: put datagram", c->self);
1977 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
1978 fatal_fr(r, "channel %i: put data", c->self);
1983 channel_handle_wfd(struct ssh *ssh, Channel *c,
1984 fd_set *readset, fd_set *writeset)
1987 u_char *data = NULL, *buf; /* XXX const; need filter API change */
1988 size_t dlen, olen = 0;
1991 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1992 sshbuf_len(c->output) == 0)
1995 /* Send buffered output data to the socket. */
1996 olen = sshbuf_len(c->output);
1997 if (c->output_filter != NULL) {
1998 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1999 debug2("channel %d: filter stops", c->self);
2000 if (c->type != SSH_CHANNEL_OPEN)
2001 chan_mark_dead(ssh, c);
2003 chan_write_failed(ssh, c);
2006 } else if (c->datagram) {
2007 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2008 fatal_fr(r, "channel %i: get datagram", c->self);
2011 buf = data = sshbuf_mutable_ptr(c->output);
2012 dlen = sshbuf_len(c->output);
2016 /* ignore truncated writes, datagrams might get lost */
2017 len = write(c->wfd, buf, dlen);
2019 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2020 errno == EWOULDBLOCK))
2028 /* XXX: Later AIX versions can't push as much data to tty */
2030 dlen = MIN(dlen, 8*1024);
2033 len = write(c->wfd, buf, dlen);
2035 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2039 if (c->type != SSH_CHANNEL_OPEN) {
2040 debug2("channel %d: not open", c->self);
2041 chan_mark_dead(ssh, c);
2044 chan_write_failed(ssh, c);
2048 #ifndef BROKEN_TCGETATTR_ICANON
2049 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2050 if (tcgetattr(c->wfd, &tio) == 0 &&
2051 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2053 * Simulate echo to reduce the impact of
2054 * traffic analysis. We need to match the
2055 * size of a SSH2_MSG_CHANNEL_DATA message
2056 * (4 byte channel id + buf)
2058 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2059 (r = sshpkt_send(ssh)) != 0)
2060 fatal_fr(r, "channel %i: ignore", c->self);
2063 #endif /* BROKEN_TCGETATTR_ICANON */
2064 if ((r = sshbuf_consume(c->output, len)) != 0)
2065 fatal_fr(r, "channel %i: consume", c->self);
2067 c->local_consumed += olen - sshbuf_len(c->output);
2073 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2074 fd_set *readset, fd_set *writeset)
2079 if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2082 len = write(c->efd, sshbuf_ptr(c->extended),
2083 sshbuf_len(c->extended));
2084 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2085 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2086 errno == EWOULDBLOCK))
2089 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2090 channel_close_fd(ssh, c, &c->efd);
2092 if ((r = sshbuf_consume(c->extended, len)) != 0)
2093 fatal_fr(r, "channel %i: consume", c->self);
2094 c->local_consumed += len;
2100 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2101 fd_set *readset, fd_set *writeset)
2103 char buf[CHAN_RBUF];
2107 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2109 if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
2112 len = read(c->efd, buf, sizeof(buf));
2113 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2114 if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2115 errno == EWOULDBLOCK) && !force)))
2118 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2119 channel_close_fd(ssh, c, &c->efd);
2120 } else if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2121 debug3("channel %d: discard efd", c->self);
2122 else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2123 fatal_fr(r, "channel %i: append", c->self);
2128 channel_handle_efd(struct ssh *ssh, Channel *c,
2129 fd_set *readset, fd_set *writeset)
2134 /** XXX handle drain efd, too */
2136 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2137 return channel_handle_efd_write(ssh, c, readset, writeset);
2138 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2139 c->extended_usage == CHAN_EXTENDED_IGNORE)
2140 return channel_handle_efd_read(ssh, c, readset, writeset);
2146 channel_check_window(struct ssh *ssh, Channel *c)
2150 if (c->type == SSH_CHANNEL_OPEN &&
2151 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2152 ((c->local_window_max - c->local_window >
2153 c->local_maxpacket*3) ||
2154 c->local_window < c->local_window_max/2) &&
2155 c->local_consumed > 0) {
2156 if (!c->have_remote_id)
2157 fatal_f("channel %d: no remote id", c->self);
2158 if ((r = sshpkt_start(ssh,
2159 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2160 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2161 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2162 (r = sshpkt_send(ssh)) != 0) {
2163 fatal_fr(r, "channel %i", c->self);
2165 debug2("channel %d: window %d sent adjust %d", c->self,
2166 c->local_window, c->local_consumed);
2167 c->local_window += c->local_consumed;
2168 c->local_consumed = 0;
2174 channel_post_open(struct ssh *ssh, Channel *c,
2175 fd_set *readset, fd_set *writeset)
2177 channel_handle_rfd(ssh, c, readset, writeset);
2178 channel_handle_wfd(ssh, c, readset, writeset);
2179 channel_handle_efd(ssh, c, readset, writeset);
2180 channel_check_window(ssh, c);
2184 read_mux(struct ssh *ssh, Channel *c, u_int need)
2186 char buf[CHAN_RBUF];
2191 if (sshbuf_len(c->input) < need) {
2192 rlen = need - sshbuf_len(c->input);
2193 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2194 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2195 return sshbuf_len(c->input);
2197 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2198 c->self, c->rfd, len);
2199 chan_read_failed(ssh, c);
2201 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2202 fatal_fr(r, "channel %i: append", c->self);
2204 return sshbuf_len(c->input);
2208 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2209 fd_set *readset, fd_set *writeset)
2213 if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2215 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2221 * Don't not read past the precise end of packets to
2222 * avoid disrupting fd passing.
2224 if (read_mux(ssh, c, 4) < 4) /* read header */
2226 /* XXX sshbuf_peek_u32 */
2227 need = PEEK_U32(sshbuf_ptr(c->input));
2228 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2229 if (need > CHANNEL_MUX_MAX_PACKET) {
2230 debug2("channel %d: packet too big %u > %u",
2231 c->self, CHANNEL_MUX_MAX_PACKET, need);
2232 chan_rcvd_oclose(ssh, c);
2235 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2237 if (c->mux_rcb(ssh, c) != 0) {
2238 debug("channel %d: mux_rcb failed", c->self);
2239 chan_mark_dead(ssh, c);
2245 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2246 fd_set *readset, fd_set *writeset)
2251 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2252 sshbuf_len(c->output) == 0)
2255 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2256 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2259 chan_mark_dead(ssh, c);
2262 if ((r = sshbuf_consume(c->output, len)) != 0)
2263 fatal_fr(r, "channel %i: consume", c->self);
2267 channel_post_mux_client(struct ssh *ssh, Channel *c,
2268 fd_set *readset, fd_set *writeset)
2270 channel_post_mux_client_read(ssh, c, readset, writeset);
2271 channel_post_mux_client_write(ssh, c, readset, writeset);
2275 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2276 fd_set *readset, fd_set *writeset)
2279 struct sockaddr_storage addr;
2285 if (!FD_ISSET(c->sock, readset))
2288 debug("multiplexing control connection");
2291 * Accept connection on control socket
2293 memset(&addr, 0, sizeof(addr));
2294 addrlen = sizeof(addr);
2295 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2297 error_f("accept: %s", strerror(errno));
2298 if (errno == EMFILE || errno == ENFILE)
2299 c->notbefore = monotime() + 1;
2303 if (getpeereid(newsock, &euid, &egid) == -1) {
2304 error_f("getpeereid failed: %s", strerror(errno));
2308 if ((euid != 0) && (getuid() != euid)) {
2309 error("multiplex uid mismatch: peer euid %u != uid %u",
2310 (u_int)euid, (u_int)getuid());
2314 nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2315 newsock, newsock, -1, c->local_window_max,
2316 c->local_maxpacket, 0, "mux-control", 1);
2317 nc->mux_rcb = c->mux_rcb;
2318 debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2319 /* establish state */
2320 nc->mux_rcb(ssh, nc);
2321 /* mux state transitions must not elicit protocol messages */
2322 nc->flags |= CHAN_LOCAL;
2326 channel_handler_init(struct ssh_channels *sc)
2328 chan_fn **pre, **post;
2330 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2331 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2332 fatal_f("allocation failed");
2334 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2335 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2336 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2337 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2338 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2339 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2340 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2341 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2342 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2343 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2344 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2345 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2346 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2348 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2349 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2350 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2351 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2352 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2353 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2354 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2355 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2356 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2357 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2358 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2359 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2361 sc->channel_pre = pre;
2362 sc->channel_post = post;
2365 /* gc dead channels */
2367 channel_garbage_collect(struct ssh *ssh, Channel *c)
2371 if (c->detach_user != NULL) {
2372 if (!chan_is_dead(ssh, c, c->detach_close))
2375 debug2("channel %d: gc: notify user", c->self);
2376 c->detach_user(ssh, c->self, NULL);
2377 /* if we still have a callback */
2378 if (c->detach_user != NULL)
2380 debug2("channel %d: gc: user detached", c->self);
2382 if (!chan_is_dead(ssh, c, 1))
2384 debug2("channel %d: garbage collecting", c->self);
2385 channel_free(ssh, c);
2388 enum channel_table { CHAN_PRE, CHAN_POST };
2391 channel_handler(struct ssh *ssh, int table,
2392 fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2394 struct ssh_channels *sc = ssh->chanctxt;
2395 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2401 if (unpause_secs != NULL)
2403 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2404 c = sc->channels[i];
2408 if (table == CHAN_PRE)
2413 if (ftab[c->type] != NULL) {
2415 * Run handlers that are not paused.
2417 if (c->notbefore <= now)
2418 (*ftab[c->type])(ssh, c, readset, writeset);
2419 else if (unpause_secs != NULL) {
2421 * Collect the time that the earliest
2422 * channel comes off pause.
2424 debug3_f("chan %d: skip for %d more "
2426 (int)(c->notbefore - now));
2427 if (*unpause_secs == 0 ||
2428 (c->notbefore - now) < *unpause_secs)
2429 *unpause_secs = c->notbefore - now;
2432 channel_garbage_collect(ssh, c);
2434 if (unpause_secs != NULL && *unpause_secs != 0)
2435 debug3_f("first channel unpauses in %d seconds",
2436 (int)*unpause_secs);
2440 * Create sockets before allocating the select bitmasks.
2441 * This is necessary for things that need to happen after reading
2442 * the network-input but before channel_prepare_select().
2445 channel_before_prepare_select(struct ssh *ssh)
2447 struct ssh_channels *sc = ssh->chanctxt;
2451 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2452 c = sc->channels[i];
2455 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2456 channel_before_prepare_select_rdynamic(ssh, c);
2461 * Allocate/update select bitmasks and add any bits relevant to channels in
2465 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2466 int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2468 u_int n, sz, nfdset;
2470 channel_before_prepare_select(ssh); /* might update channel_max_fd */
2472 n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2474 nfdset = howmany(n+1, NFDBITS);
2475 /* Explicitly test here, because xrealloc isn't always called */
2476 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2477 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2478 sz = nfdset * sizeof(fd_mask);
2480 /* perhaps check sz < nalloc/2 and shrink? */
2481 if (*readsetp == NULL || sz > *nallocp) {
2482 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2483 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2487 memset(*readsetp, 0, sz);
2488 memset(*writesetp, 0, sz);
2490 if (!ssh_packet_is_rekeying(ssh))
2491 channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2496 * After select, perform any appropriate operations for channels which have
2500 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2502 channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2506 * Enqueue data for channels with open or draining c->input.
2509 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2515 if ((len = sshbuf_len(c->input)) == 0) {
2516 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2518 * input-buffer is empty and read-socket shutdown:
2519 * tell peer, that we will not send more data:
2521 * hack for extended data: delay EOF if EFD still
2524 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2525 debug2("channel %d: "
2526 "ibuf_empty delayed efd %d/(%zu)",
2527 c->self, c->efd, sshbuf_len(c->extended));
2529 chan_ibuf_empty(ssh, c);
2534 if (!c->have_remote_id)
2535 fatal_f("channel %d: no remote id", c->self);
2538 /* Check datagram will fit; drop if not */
2539 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2540 fatal_fr(r, "channel %i: get datagram", c->self);
2542 * XXX this does tail-drop on the datagram queue which is
2543 * usually suboptimal compared to head-drop. Better to have
2544 * backpressure at read time? (i.e. read + discard)
2546 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2547 debug("channel %d: datagram too big", c->self);
2551 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2552 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2553 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2554 (r = sshpkt_send(ssh)) != 0)
2555 fatal_fr(r, "channel %i: send datagram", c->self);
2556 c->remote_window -= plen;
2560 /* Enqueue packet for buffered data. */
2561 if (len > c->remote_window)
2562 len = c->remote_window;
2563 if (len > c->remote_maxpacket)
2564 len = c->remote_maxpacket;
2567 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2568 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2569 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2570 (r = sshpkt_send(ssh)) != 0)
2571 fatal_fr(r, "channel %i: send data", c->self);
2572 if ((r = sshbuf_consume(c->input, len)) != 0)
2573 fatal_fr(r, "channel %i: consume", c->self);
2574 c->remote_window -= len;
2578 * Enqueue data for channels with open c->extended in read mode.
2581 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2586 if ((len = sshbuf_len(c->extended)) == 0)
2589 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2590 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2591 if (len > c->remote_window)
2592 len = c->remote_window;
2593 if (len > c->remote_maxpacket)
2594 len = c->remote_maxpacket;
2597 if (!c->have_remote_id)
2598 fatal_f("channel %d: no remote id", c->self);
2599 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2600 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2601 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2602 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2603 (r = sshpkt_send(ssh)) != 0)
2604 fatal_fr(r, "channel %i: data", c->self);
2605 if ((r = sshbuf_consume(c->extended, len)) != 0)
2606 fatal_fr(r, "channel %i: consume", c->self);
2607 c->remote_window -= len;
2608 debug2("channel %d: sent ext data %zu", c->self, len);
2611 /* If there is data to send to the connection, enqueue some of it now. */
2613 channel_output_poll(struct ssh *ssh)
2615 struct ssh_channels *sc = ssh->chanctxt;
2619 for (i = 0; i < sc->channels_alloc; i++) {
2620 c = sc->channels[i];
2625 * We are only interested in channels that can have buffered
2628 if (c->type != SSH_CHANNEL_OPEN)
2630 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2631 /* XXX is this true? */
2632 debug3("channel %d: will not send data after close",
2637 /* Get the amount of buffered data for this channel. */
2638 if (c->istate == CHAN_INPUT_OPEN ||
2639 c->istate == CHAN_INPUT_WAIT_DRAIN)
2640 channel_output_poll_input_open(ssh, c);
2641 /* Send extended data, i.e. stderr */
2642 if (!(c->flags & CHAN_EOF_SENT) &&
2643 c->extended_usage == CHAN_EXTENDED_READ)
2644 channel_output_poll_extended_read(ssh, c);
2648 /* -- mux proxy support */
2651 * When multiplexing channel messages for mux clients we have to deal
2652 * with downstream messages from the mux client and upstream messages
2653 * from the ssh server:
2654 * 1) Handling downstream messages is straightforward and happens
2655 * in channel_proxy_downstream():
2656 * - We forward all messages (mostly) unmodified to the server.
2657 * - However, in order to route messages from upstream to the correct
2658 * downstream client, we have to replace the channel IDs used by the
2659 * mux clients with a unique channel ID because the mux clients might
2660 * use conflicting channel IDs.
2661 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2662 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2663 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2664 * with the newly allocated channel ID.
2665 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2666 * channels and processed by channel_proxy_upstream(). The local channel ID
2667 * is then translated back to the original mux client ID.
2668 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2669 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2670 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2671 * downstream mux client are removed.
2672 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2673 * requires more work, because they are not addressed to a specific
2674 * channel. E.g. client_request_forwarded_tcpip() needs to figure
2675 * out whether the request is addressed to the local client or a
2676 * specific downstream client based on the listen-address/port.
2677 * 6) Agent and X11-Forwarding have a similar problem and are currently
2678 * not supported as the matching session/channel cannot be identified
2683 * receive packets from downstream mux clients:
2684 * channel callback fired on read from mux client, creates
2685 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2686 * on channel creation.
2689 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2692 struct sshbuf *original = NULL, *modified = NULL;
2694 char *ctype = NULL, *listen_host = NULL;
2698 u_int id, remote_id, listen_port;
2700 /* sshbuf_dump(downstream->input, stderr); */
2701 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2703 error_fr(r, "parse");
2707 error_f("short message");
2711 /* skip padlen + type */
2714 if (ssh_packet_log_type(type))
2715 debug3_f("channel %u: down->up: type %u",
2716 downstream->self, type);
2719 case SSH2_MSG_CHANNEL_OPEN:
2720 if ((original = sshbuf_from(cp, have)) == NULL ||
2721 (modified = sshbuf_new()) == NULL) {
2725 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2726 (r = sshbuf_get_u32(original, &id)) != 0) {
2727 error_fr(r, "parse");
2730 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2731 -1, -1, -1, 0, 0, 0, ctype, 1);
2732 c->mux_ctx = downstream; /* point to mux client */
2733 c->mux_downstream_id = id; /* original downstream id */
2734 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2735 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2736 (r = sshbuf_putb(modified, original)) != 0) {
2737 error_fr(r, "compose");
2738 channel_free(ssh, c);
2742 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2744 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2745 * need to parse 'remote_id' instead of 'ctype'.
2747 if ((original = sshbuf_from(cp, have)) == NULL ||
2748 (modified = sshbuf_new()) == NULL) {
2752 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2753 (r = sshbuf_get_u32(original, &id)) != 0) {
2754 error_fr(r, "parse");
2757 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2758 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2759 c->mux_ctx = downstream; /* point to mux client */
2760 c->mux_downstream_id = id;
2761 c->remote_id = remote_id;
2762 c->have_remote_id = 1;
2763 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2764 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2765 (r = sshbuf_putb(modified, original)) != 0) {
2766 error_fr(r, "compose");
2767 channel_free(ssh, c);
2771 case SSH2_MSG_GLOBAL_REQUEST:
2772 if ((original = sshbuf_from(cp, have)) == NULL) {
2776 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2777 error_fr(r, "parse");
2780 if (strcmp(ctype, "tcpip-forward") != 0) {
2781 error_f("unsupported request %s", ctype);
2784 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2785 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2786 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2787 error_fr(r, "parse");
2790 if (listen_port > 65535) {
2791 error_f("tcpip-forward for %s: bad port %u",
2792 listen_host, listen_port);
2795 /* Record that connection to this host/port is permitted. */
2796 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
2797 listen_host, NULL, (int)listen_port, downstream);
2800 case SSH2_MSG_CHANNEL_CLOSE:
2803 remote_id = PEEK_U32(cp);
2804 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2805 if (c->flags & CHAN_CLOSE_RCVD)
2806 channel_free(ssh, c);
2808 c->flags |= CHAN_CLOSE_SENT;
2813 if ((r = sshpkt_start(ssh, type)) != 0 ||
2814 (r = sshpkt_putb(ssh, modified)) != 0 ||
2815 (r = sshpkt_send(ssh)) != 0) {
2816 error_fr(r, "send");
2820 if ((r = sshpkt_start(ssh, type)) != 0 ||
2821 (r = sshpkt_put(ssh, cp, have)) != 0 ||
2822 (r = sshpkt_send(ssh)) != 0) {
2823 error_fr(r, "send");
2831 sshbuf_free(original);
2832 sshbuf_free(modified);
2837 * receive packets from upstream server and de-multiplex packets
2838 * to correct downstream:
2839 * implemented as a helper for channel input handlers,
2840 * replaces local (proxy) channel ID with downstream channel ID.
2843 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2845 struct sshbuf *b = NULL;
2846 Channel *downstream;
2847 const u_char *cp = NULL;
2852 * When receiving packets from the peer we need to check whether we
2853 * need to forward the packets to the mux client. In this case we
2854 * restore the original channel id and keep track of CLOSE messages,
2855 * so we can cleanup the channel.
2857 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2859 if ((downstream = c->mux_ctx) == NULL)
2862 case SSH2_MSG_CHANNEL_CLOSE:
2863 case SSH2_MSG_CHANNEL_DATA:
2864 case SSH2_MSG_CHANNEL_EOF:
2865 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
2866 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2867 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
2868 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2869 case SSH2_MSG_CHANNEL_SUCCESS:
2870 case SSH2_MSG_CHANNEL_FAILURE:
2871 case SSH2_MSG_CHANNEL_REQUEST:
2874 debug2_f("channel %u: unsupported type %u", c->self, type);
2877 if ((b = sshbuf_new()) == NULL) {
2878 error_f("alloc reply");
2881 /* get remaining payload (after id) */
2882 cp = sshpkt_ptr(ssh, &len);
2884 error_f("no packet");
2887 /* translate id and send to muxclient */
2888 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
2889 (r = sshbuf_put_u8(b, type)) != 0 ||
2890 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
2891 (r = sshbuf_put(b, cp, len)) != 0 ||
2892 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
2893 error_fr(r, "compose muxclient");
2896 /* sshbuf_dump(b, stderr); */
2897 if (ssh_packet_log_type(type))
2898 debug3_f("channel %u: up->down: type %u", c->self, type);
2902 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2903 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
2904 if (cp && len > 4) {
2905 c->remote_id = PEEK_U32(cp);
2906 c->have_remote_id = 1;
2909 case SSH2_MSG_CHANNEL_CLOSE:
2910 if (c->flags & CHAN_CLOSE_SENT)
2911 channel_free(ssh, c);
2913 c->flags |= CHAN_CLOSE_RCVD;
2920 /* -- protocol input */
2922 /* Parse a channel ID from the current packet */
2924 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
2929 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
2930 error_r(r, "%s: parse id", where);
2931 ssh_packet_disconnect(ssh, "Invalid %s message", what);
2934 error_r(r, "%s: bad channel id %u", where, id);
2935 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
2940 /* Lookup a channel from an ID in the current packet */
2942 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
2944 int id = channel_parse_id(ssh, where, what);
2947 if ((c = channel_lookup(ssh, id)) == NULL) {
2948 ssh_packet_disconnect(ssh,
2949 "%s packet referred to nonexistent channel %d", what, id);
2955 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
2958 size_t data_len, win_len;
2959 Channel *c = channel_from_packet_id(ssh, __func__, "data");
2962 if (channel_proxy_upstream(c, type, seq, ssh))
2965 /* Ignore any data for non-open channels (might happen on close) */
2966 if (c->type != SSH_CHANNEL_OPEN &&
2967 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
2968 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
2969 c->type != SSH_CHANNEL_X11_OPEN)
2973 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
2974 (r = sshpkt_get_end(ssh)) != 0)
2975 fatal_fr(r, "channel %i: get data", c->self);
2979 win_len += 4; /* string length header */
2982 * The sending side reduces its window as it sends data, so we
2983 * must 'fake' consumption of the data in order to ensure that window
2984 * updates are sent back. Otherwise the connection might deadlock.
2986 if (c->ostate != CHAN_OUTPUT_OPEN) {
2987 c->local_window -= win_len;
2988 c->local_consumed += win_len;
2992 if (win_len > c->local_maxpacket) {
2993 logit("channel %d: rcvd big packet %zu, maxpack %u",
2994 c->self, win_len, c->local_maxpacket);
2997 if (win_len > c->local_window) {
2998 logit("channel %d: rcvd too much data %zu, win %u",
2999 c->self, win_len, c->local_window);
3002 c->local_window -= win_len;
3005 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3006 fatal_fr(r, "channel %i: append datagram", c->self);
3007 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3008 fatal_fr(r, "channel %i: append data", c->self);
3014 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3019 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3022 if (channel_proxy_upstream(c, type, seq, ssh))
3024 if (c->type != SSH_CHANNEL_OPEN) {
3025 logit("channel %d: ext data for non open", c->self);
3028 if (c->flags & CHAN_EOF_RCVD) {
3029 if (ssh->compat & SSH_BUG_EXTEOF)
3030 debug("channel %d: accepting ext data after eof",
3033 ssh_packet_disconnect(ssh, "Received extended_data "
3034 "after EOF on channel %d.", c->self);
3037 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3038 error_fr(r, "parse tcode");
3039 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3042 c->extended_usage != CHAN_EXTENDED_WRITE ||
3043 tcode != SSH2_EXTENDED_DATA_STDERR) {
3044 logit("channel %d: bad ext data", c->self);
3047 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3048 (r = sshpkt_get_end(ssh)) != 0) {
3049 error_fr(r, "parse data");
3050 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3053 if (data_len > c->local_window) {
3054 logit("channel %d: rcvd too much extended_data %zu, win %u",
3055 c->self, data_len, c->local_window);
3058 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3059 /* XXX sshpkt_getb? */
3060 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3061 error_fr(r, "append");
3062 c->local_window -= data_len;
3067 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3069 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3072 if ((r = sshpkt_get_end(ssh)) != 0) {
3073 error_fr(r, "parse data");
3074 ssh_packet_disconnect(ssh, "Invalid ieof message");
3077 if (channel_proxy_upstream(c, type, seq, ssh))
3079 chan_rcvd_ieof(ssh, c);
3081 /* XXX force input close */
3082 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3083 debug("channel %d: FORCE input drain", c->self);
3084 c->istate = CHAN_INPUT_WAIT_DRAIN;
3085 if (sshbuf_len(c->input) == 0)
3086 chan_ibuf_empty(ssh, c);
3092 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3094 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3097 if (channel_proxy_upstream(c, type, seq, ssh))
3099 if ((r = sshpkt_get_end(ssh)) != 0) {
3100 error_fr(r, "parse data");
3101 ssh_packet_disconnect(ssh, "Invalid oclose message");
3103 chan_rcvd_oclose(ssh, c);
3108 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3110 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3111 u_int32_t remote_window, remote_maxpacket;
3114 if (channel_proxy_upstream(c, type, seq, ssh))
3116 if (c->type != SSH_CHANNEL_OPENING)
3117 ssh_packet_disconnect(ssh, "Received open confirmation for "
3118 "non-opening channel %d.", c->self);
3120 * Record the remote channel number and mark that the channel
3123 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3124 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3125 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3126 (r = sshpkt_get_end(ssh)) != 0) {
3127 error_fr(r, "window/maxpacket");
3128 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3131 c->have_remote_id = 1;
3132 c->remote_window = remote_window;
3133 c->remote_maxpacket = remote_maxpacket;
3134 c->type = SSH_CHANNEL_OPEN;
3135 if (c->open_confirm) {
3136 debug2_f("channel %d: callback start", c->self);
3137 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3138 debug2_f("channel %d: callback done", c->self);
3140 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3141 c->remote_window, c->remote_maxpacket);
3146 reason2txt(int reason)
3149 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3150 return "administratively prohibited";
3151 case SSH2_OPEN_CONNECT_FAILED:
3152 return "connect failed";
3153 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3154 return "unknown channel type";
3155 case SSH2_OPEN_RESOURCE_SHORTAGE:
3156 return "resource shortage";
3158 return "unknown reason";
3162 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3164 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3169 if (channel_proxy_upstream(c, type, seq, ssh))
3171 if (c->type != SSH_CHANNEL_OPENING)
3172 ssh_packet_disconnect(ssh, "Received open failure for "
3173 "non-opening channel %d.", c->self);
3174 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3175 error_fr(r, "parse reason");
3176 ssh_packet_disconnect(ssh, "Invalid open failure message");
3179 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3180 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3181 (r = sshpkt_get_end(ssh)) != 0) {
3182 error_fr(r, "parse msg/lang");
3183 ssh_packet_disconnect(ssh, "Invalid open failure message");
3185 logit("channel %d: open failed: %s%s%s", c->self,
3186 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3188 if (c->open_confirm) {
3189 debug2_f("channel %d: callback start", c->self);
3190 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3191 debug2_f("channel %d: callback done", c->self);
3193 /* Schedule the channel for cleanup/deletion. */
3194 chan_mark_dead(ssh, c);
3199 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3201 int id = channel_parse_id(ssh, __func__, "window adjust");
3207 if ((c = channel_lookup(ssh, id)) == NULL) {
3208 logit("Received window adjust for non-open channel %d.", id);
3212 if (channel_proxy_upstream(c, type, seq, ssh))
3214 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3215 (r = sshpkt_get_end(ssh)) != 0) {
3216 error_fr(r, "parse adjust");
3217 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3219 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3220 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3221 fatal("channel %d: adjust %u overflows remote window %u",
3222 c->self, adjust, c->remote_window);
3224 c->remote_window = new_rwin;
3229 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3231 int id = channel_parse_id(ssh, __func__, "status confirm");
3233 struct channel_confirm *cc;
3235 /* Reset keepalive timeout */
3236 ssh_packet_set_alive_timeouts(ssh, 0);
3238 debug2_f("type %d id %d", type, id);
3240 if ((c = channel_lookup(ssh, id)) == NULL) {
3241 logit_f("%d: unknown", id);
3244 if (channel_proxy_upstream(c, type, seq, ssh))
3246 if (sshpkt_get_end(ssh) != 0)
3247 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3248 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3250 cc->cb(ssh, type, c, cc->ctx);
3251 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3252 freezero(cc, sizeof(*cc));
3256 /* -- tcp forwarding */
3259 channel_set_af(struct ssh *ssh, int af)
3261 ssh->chanctxt->IPv4or6 = af;
3266 * Determine whether or not a port forward listens to loopback, the
3267 * specified address or wildcard. On the client, a specified bind
3268 * address will always override gateway_ports. On the server, a
3269 * gateway_ports of 1 (``yes'') will override the client's specification
3270 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3271 * will bind to whatever address the client asked for.
3273 * Special-case listen_addrs are:
3275 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3276 * "" (empty string), "*" -> wildcard v4/v6
3277 * "localhost" -> loopback v4/v6
3278 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3281 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3282 int is_client, struct ForwardOptions *fwd_opts)
3284 const char *addr = NULL;
3287 if (listen_addr == NULL) {
3288 /* No address specified: default to gateway_ports setting */
3289 if (fwd_opts->gateway_ports)
3291 } else if (fwd_opts->gateway_ports || is_client) {
3292 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3293 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3294 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3295 (!is_client && fwd_opts->gateway_ports == 1)) {
3298 * Notify client if they requested a specific listen
3299 * address and it was overridden.
3301 if (*listen_addr != '\0' &&
3302 strcmp(listen_addr, "0.0.0.0") != 0 &&
3303 strcmp(listen_addr, "*") != 0) {
3304 ssh_packet_send_debug(ssh,
3305 "Forwarding listen address "
3306 "\"%s\" overridden by server "
3307 "GatewayPorts", listen_addr);
3309 } else if (strcmp(listen_addr, "localhost") != 0 ||
3310 strcmp(listen_addr, "127.0.0.1") == 0 ||
3311 strcmp(listen_addr, "::1") == 0) {
3313 * Accept explicit localhost address when
3314 * GatewayPorts=yes. The "localhost" hostname is
3315 * deliberately skipped here so it will listen on all
3316 * available local address families.
3320 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3321 strcmp(listen_addr, "::1") == 0) {
3323 * If a specific IPv4/IPv6 localhost address has been
3324 * requested then accept it even if gateway_ports is in
3325 * effect. This allows the client to prefer IPv4 or IPv6.
3329 if (wildcardp != NULL)
3330 *wildcardp = wildcard;
3335 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3336 struct Forward *fwd, int *allocated_listen_port,
3337 struct ForwardOptions *fwd_opts)
3340 int sock, r, success = 0, wildcard = 0, is_client;
3341 struct addrinfo hints, *ai, *aitop;
3342 const char *host, *addr;
3343 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3346 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3348 if (is_client && fwd->connect_path != NULL) {
3349 host = fwd->connect_path;
3351 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3352 fwd->listen_host : fwd->connect_host;
3354 error("No forward host name.");
3357 if (strlen(host) >= NI_MAXHOST) {
3358 error("Forward host name too long.");
3363 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3364 addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3365 is_client, fwd_opts);
3366 debug3_f("type %d wildcard %d addr %s", type, wildcard,
3367 (addr == NULL) ? "NULL" : addr);
3370 * getaddrinfo returns a loopback address if the hostname is
3371 * set to NULL and hints.ai_flags is not AI_PASSIVE
3373 memset(&hints, 0, sizeof(hints));
3374 hints.ai_family = ssh->chanctxt->IPv4or6;
3375 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3376 hints.ai_socktype = SOCK_STREAM;
3377 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3378 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3380 /* This really shouldn't happen */
3381 ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3382 ssh_gai_strerror(r));
3384 error_f("getaddrinfo(%.64s): %s", addr,
3385 ssh_gai_strerror(r));
3389 if (allocated_listen_port != NULL)
3390 *allocated_listen_port = 0;
3391 for (ai = aitop; ai; ai = ai->ai_next) {
3392 switch (ai->ai_family) {
3394 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3398 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3405 * If allocating a port for -R forwards, then use the
3406 * same port for all address families.
3408 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3409 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3410 *allocated_listen_port > 0)
3411 *lport_p = htons(*allocated_listen_port);
3413 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3414 strport, sizeof(strport),
3415 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3416 error_f("getnameinfo failed");
3419 /* Create a port to listen for the host. */
3420 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3422 /* this is no error since kernel may not support ipv6 */
3423 verbose("socket [%s]:%s: %.100s", ntop, strport,
3428 set_reuseaddr(sock);
3429 if (ai->ai_family == AF_INET6)
3430 sock_set_v6only(sock);
3432 debug("Local forwarding listening on %s port %s.",
3435 /* Bind the socket to the address. */
3436 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3438 * address can be in if use ipv6 address is
3442 error("bind [%s]:%s: %.100s",
3443 ntop, strport, strerror(errno));
3445 verbose("bind [%s]:%s: %.100s",
3446 ntop, strport, strerror(errno));
3451 /* Start listening for connections on the socket. */
3452 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3453 error("listen [%s]:%s: %.100s", ntop, strport,
3460 * fwd->listen_port == 0 requests a dynamically allocated port -
3461 * record what we got.
3463 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3464 fwd->listen_port == 0 &&
3465 allocated_listen_port != NULL &&
3466 *allocated_listen_port == 0) {
3467 *allocated_listen_port = get_local_port(sock);
3468 debug("Allocated listen port %d",
3469 *allocated_listen_port);
3472 /* Allocate a channel number for the socket. */
3473 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3474 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3475 0, "port listener", 1);
3476 c->path = xstrdup(host);
3477 c->host_port = fwd->connect_port;
3478 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3479 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3480 !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3481 c->listening_port = *allocated_listen_port;
3483 c->listening_port = fwd->listen_port;
3487 error_f("cannot listen to port: %d", fwd->listen_port);
3488 freeaddrinfo(aitop);
3493 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3494 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3496 struct sockaddr_un sunaddr;
3503 case SSH_CHANNEL_UNIX_LISTENER:
3504 if (fwd->connect_path != NULL) {
3505 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3506 error("Local connecting path too long: %s",
3510 path = fwd->connect_path;
3511 port = PORT_STREAMLOCAL;
3513 if (fwd->connect_host == NULL) {
3514 error("No forward host name.");
3517 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3518 error("Forward host name too long.");
3521 path = fwd->connect_host;
3522 port = fwd->connect_port;
3525 case SSH_CHANNEL_RUNIX_LISTENER:
3526 path = fwd->listen_path;
3527 port = PORT_STREAMLOCAL;
3530 error_f("unexpected channel type %d", type);
3534 if (fwd->listen_path == NULL) {
3535 error("No forward path name.");
3538 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3539 error("Local listening path too long: %s", fwd->listen_path);
3543 debug3_f("type %d path %s", type, fwd->listen_path);
3545 /* Start a Unix domain listener. */
3546 omask = umask(fwd_opts->streamlocal_bind_mask);
3547 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3548 fwd_opts->streamlocal_bind_unlink);
3553 debug("Local forwarding listening on path %s.", fwd->listen_path);
3555 /* Allocate a channel number for the socket. */
3556 c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3557 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3558 0, "unix listener", 1);
3559 c->path = xstrdup(path);
3560 c->host_port = port;
3561 c->listening_port = PORT_STREAMLOCAL;
3562 c->listening_addr = xstrdup(fwd->listen_path);
3567 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3568 const char *host, u_short port)
3573 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3574 Channel *c = ssh->chanctxt->channels[i];
3575 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3577 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3578 debug2_f("close channel %d", i);
3579 channel_free(ssh, c);
3588 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3593 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3594 Channel *c = ssh->chanctxt->channels[i];
3595 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3597 if (c->path == NULL)
3599 if (strcmp(c->path, path) == 0) {
3600 debug2_f("close channel %d", i);
3601 channel_free(ssh, c);
3610 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3612 if (fwd->listen_path != NULL) {
3613 return channel_cancel_rport_listener_streamlocal(ssh,
3616 return channel_cancel_rport_listener_tcpip(ssh,
3617 fwd->listen_host, fwd->listen_port);
3622 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3623 const char *lhost, u_short lport, int cport,
3624 struct ForwardOptions *fwd_opts)
3628 const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3630 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3631 Channel *c = ssh->chanctxt->channels[i];
3632 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3634 if (c->listening_port != lport)
3636 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3637 /* skip dynamic forwardings */
3638 if (c->host_port == 0)
3641 if (c->host_port != cport)
3644 if ((c->listening_addr == NULL && addr != NULL) ||
3645 (c->listening_addr != NULL && addr == NULL))
3647 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3648 debug2_f("close channel %d", i);
3649 channel_free(ssh, c);
3658 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3664 error_f("no path specified.");
3668 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3669 Channel *c = ssh->chanctxt->channels[i];
3670 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3672 if (c->listening_addr == NULL)
3674 if (strcmp(c->listening_addr, path) == 0) {
3675 debug2_f("close channel %d", i);
3676 channel_free(ssh, c);
3685 channel_cancel_lport_listener(struct ssh *ssh,
3686 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3688 if (fwd->listen_path != NULL) {
3689 return channel_cancel_lport_listener_streamlocal(ssh,
3692 return channel_cancel_lport_listener_tcpip(ssh,
3693 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3697 /* protocol local port fwd, used by ssh */
3699 channel_setup_local_fwd_listener(struct ssh *ssh,
3700 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3702 if (fwd->listen_path != NULL) {
3703 return channel_setup_fwd_listener_streamlocal(ssh,
3704 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3706 return channel_setup_fwd_listener_tcpip(ssh,
3707 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3711 /* Matches a remote forwarding permission against a requested forwarding */
3713 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3718 /* XXX add ACLs for streamlocal */
3719 if (fwd->listen_path != NULL)
3722 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3725 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3726 allowed_open->listen_port != fwd->listen_port)
3729 /* Match hostnames case-insensitively */
3730 lhost = xstrdup(fwd->listen_host);
3732 ret = match_pattern(lhost, allowed_open->listen_host);
3738 /* Checks whether a requested remote forwarding is permitted */
3740 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3742 struct ssh_channels *sc = ssh->chanctxt;
3743 struct permission_set *pset = &sc->remote_perms;
3744 u_int i, permit, permit_adm = 1;
3745 struct permission *perm;
3747 /* XXX apply GatewayPorts override before checking? */
3749 permit = pset->all_permitted;
3751 for (i = 0; i < pset->num_permitted_user; i++) {
3752 perm = &pset->permitted_user[i];
3753 if (remote_open_match(perm, fwd)) {
3760 if (pset->num_permitted_admin > 0) {
3762 for (i = 0; i < pset->num_permitted_admin; i++) {
3763 perm = &pset->permitted_admin[i];
3764 if (remote_open_match(perm, fwd)) {
3771 return permit && permit_adm;
3774 /* protocol v2 remote port fwd, used by sshd */
3776 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
3777 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3779 if (!check_rfwd_permission(ssh, fwd)) {
3780 ssh_packet_send_debug(ssh, "port forwarding refused");
3781 if (fwd->listen_path != NULL)
3782 /* XXX always allowed, see remote_open_match() */
3783 logit("Received request from %.100s port %d to "
3784 "remote forward to path \"%.100s\", "
3785 "but the request was denied.",
3786 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3788 else if(fwd->listen_host != NULL)
3789 logit("Received request from %.100s port %d to "
3790 "remote forward to host %.100s port %d, "
3791 "but the request was denied.",
3792 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
3793 fwd->listen_host, fwd->listen_port );
3795 logit("Received request from %.100s port %d to remote "
3796 "forward, but the request was denied.",
3797 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
3800 if (fwd->listen_path != NULL) {
3801 return channel_setup_fwd_listener_streamlocal(ssh,
3802 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3804 return channel_setup_fwd_listener_tcpip(ssh,
3805 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3811 * Translate the requested rfwd listen host to something usable for
3815 channel_rfwd_bind_host(const char *listen_host)
3817 if (listen_host == NULL) {
3819 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3826 * Initiate forwarding of connections to port "port" on remote host through
3827 * the secure channel to host:port from local side.
3828 * Returns handle (index) for updating the dynamic listen port with
3829 * channel_update_permission().
3832 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
3834 int r, success = 0, idx = -1;
3835 char *host_to_connect, *listen_host, *listen_path;
3836 int port_to_connect, listen_port;
3838 /* Send the forward request to the remote side. */
3839 if (fwd->listen_path != NULL) {
3840 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3841 (r = sshpkt_put_cstring(ssh,
3842 "streamlocal-forward@openssh.com")) != 0 ||
3843 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3844 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
3845 (r = sshpkt_send(ssh)) != 0 ||
3846 (r = ssh_packet_write_wait(ssh)) != 0)
3847 fatal_fr(r, "request streamlocal");
3849 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3850 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
3851 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3852 (r = sshpkt_put_cstring(ssh,
3853 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
3854 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
3855 (r = sshpkt_send(ssh)) != 0 ||
3856 (r = ssh_packet_write_wait(ssh)) != 0)
3857 fatal_fr(r, "request tcpip-forward");
3859 /* Assume that server accepts the request */
3862 /* Record that connection to this host/port is permitted. */
3863 host_to_connect = listen_host = listen_path = NULL;
3864 port_to_connect = listen_port = 0;
3865 if (fwd->connect_path != NULL) {
3866 host_to_connect = xstrdup(fwd->connect_path);
3867 port_to_connect = PORT_STREAMLOCAL;
3869 host_to_connect = xstrdup(fwd->connect_host);
3870 port_to_connect = fwd->connect_port;
3872 if (fwd->listen_path != NULL) {
3873 listen_path = xstrdup(fwd->listen_path);
3874 listen_port = PORT_STREAMLOCAL;
3876 if (fwd->listen_host != NULL)
3877 listen_host = xstrdup(fwd->listen_host);
3878 listen_port = fwd->listen_port;
3880 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
3881 host_to_connect, port_to_connect,
3882 listen_host, listen_path, listen_port, NULL);
3888 open_match(struct permission *allowed_open, const char *requestedhost,
3891 if (allowed_open->host_to_connect == NULL)
3893 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3894 allowed_open->port_to_connect != requestedport)
3896 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3897 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3903 * Note that in the listen host/port case
3904 * we don't support FWD_PERMIT_ANY_PORT and
3905 * need to translate between the configured-host (listen_host)
3906 * and what we've sent to the remote server (channel_rfwd_bind_host)
3909 open_listen_match_tcpip(struct permission *allowed_open,
3910 const char *requestedhost, u_short requestedport, int translate)
3912 const char *allowed_host;
3914 if (allowed_open->host_to_connect == NULL)
3916 if (allowed_open->listen_port != requestedport)
3918 if (!translate && allowed_open->listen_host == NULL &&
3919 requestedhost == NULL)
3921 allowed_host = translate ?
3922 channel_rfwd_bind_host(allowed_open->listen_host) :
3923 allowed_open->listen_host;
3924 if (allowed_host == NULL || requestedhost == NULL ||
3925 strcmp(allowed_host, requestedhost) != 0)
3931 open_listen_match_streamlocal(struct permission *allowed_open,
3932 const char *requestedpath)
3934 if (allowed_open->host_to_connect == NULL)
3936 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3938 if (allowed_open->listen_path == NULL ||
3939 strcmp(allowed_open->listen_path, requestedpath) != 0)
3945 * Request cancellation of remote forwarding of connection host:port from
3949 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
3950 const char *host, u_short port)
3952 struct ssh_channels *sc = ssh->chanctxt;
3953 struct permission_set *pset = &sc->local_perms;
3956 struct permission *perm = NULL;
3958 for (i = 0; i < pset->num_permitted_user; i++) {
3959 perm = &pset->permitted_user[i];
3960 if (open_listen_match_tcpip(perm, host, port, 0))
3965 debug_f("requested forward not found");
3968 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3969 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
3970 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3971 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
3972 (r = sshpkt_put_u32(ssh, port)) != 0 ||
3973 (r = sshpkt_send(ssh)) != 0)
3974 fatal_fr(r, "send cancel");
3976 fwd_perm_clear(perm); /* unregister */
3982 * Request cancellation of remote forwarding of Unix domain socket
3983 * path from local side.
3986 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
3988 struct ssh_channels *sc = ssh->chanctxt;
3989 struct permission_set *pset = &sc->local_perms;
3992 struct permission *perm = NULL;
3994 for (i = 0; i < pset->num_permitted_user; i++) {
3995 perm = &pset->permitted_user[i];
3996 if (open_listen_match_streamlocal(perm, path))
4001 debug_f("requested forward not found");
4004 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4005 (r = sshpkt_put_cstring(ssh,
4006 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4007 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4008 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4009 (r = sshpkt_send(ssh)) != 0)
4010 fatal_fr(r, "send cancel");
4012 fwd_perm_clear(perm); /* unregister */
4018 * Request cancellation of remote forwarding of a connection from local side.
4021 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4023 if (fwd->listen_path != NULL) {
4024 return channel_request_rforward_cancel_streamlocal(ssh,
4027 return channel_request_rforward_cancel_tcpip(ssh,
4029 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4034 * Permits opening to any host/port if permitted_user[] is empty. This is
4035 * usually called by the server, because the user could connect to any port
4036 * anyway, and the server has no way to know but to trust the client anyway.
4039 channel_permit_all(struct ssh *ssh, int where)
4041 struct permission_set *pset = permission_set_get(ssh, where);
4043 if (pset->num_permitted_user == 0)
4044 pset->all_permitted = 1;
4048 * Permit the specified host/port for forwarding.
4051 channel_add_permission(struct ssh *ssh, int who, int where,
4052 char *host, int port)
4054 int local = where == FORWARD_LOCAL;
4055 struct permission_set *pset = permission_set_get(ssh, where);
4057 debug("allow %s forwarding to host %s port %d",
4058 fwd_ident(who, where), host, port);
4060 * Remote forwards set listen_host/port, local forwards set
4061 * host/port_to_connect.
4063 permission_set_add(ssh, who, where,
4064 local ? host : 0, local ? port : 0,
4065 local ? NULL : host, NULL, local ? 0 : port, NULL);
4066 pset->all_permitted = 0;
4070 * Administratively disable forwarding.
4073 channel_disable_admin(struct ssh *ssh, int where)
4075 channel_clear_permission(ssh, FORWARD_ADM, where);
4076 permission_set_add(ssh, FORWARD_ADM, where,
4077 NULL, 0, NULL, NULL, 0, NULL);
4081 * Clear a list of permitted opens.
4084 channel_clear_permission(struct ssh *ssh, int who, int where)
4086 struct permission **permp;
4089 permission_set_get_array(ssh, who, where, &permp, &npermp);
4090 *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4095 * Update the listen port for a dynamic remote forward, after
4096 * the actual 'newport' has been allocated. If 'newport' < 0 is
4097 * passed then they entry will be invalidated.
4100 channel_update_permission(struct ssh *ssh, int idx, int newport)
4102 struct permission_set *pset = &ssh->chanctxt->local_perms;
4104 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4105 debug_f("index out of range: %d num_permitted_user %d",
4106 idx, pset->num_permitted_user);
4109 debug("%s allowed port %d for forwarding to host %s port %d",
4110 newport > 0 ? "Updating" : "Removing",
4112 pset->permitted_user[idx].host_to_connect,
4113 pset->permitted_user[idx].port_to_connect);
4115 fwd_perm_clear(&pset->permitted_user[idx]);
4117 pset->permitted_user[idx].listen_port =
4118 (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4122 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4124 permitopen_port(const char *p)
4128 if (strcmp(p, "*") == 0)
4129 return FWD_PERMIT_ANY_PORT;
4130 if ((port = a2port(p)) > 0)
4135 /* Try to start non-blocking connect to next host in cctx list */
4137 connect_next(struct channel_connect *cctx)
4139 int sock, saved_errno;
4140 struct sockaddr_un *sunaddr;
4141 char ntop[NI_MAXHOST];
4142 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4144 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4145 switch (cctx->ai->ai_family) {
4147 /* unix:pathname instead of host:port */
4148 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4149 strlcpy(ntop, "unix", sizeof(ntop));
4150 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4154 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4155 ntop, sizeof(ntop), strport, sizeof(strport),
4156 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4157 error("connect_next: getnameinfo failed");
4164 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4165 cctx->ai->ai_protocol)) == -1) {
4166 if (cctx->ai->ai_next == NULL)
4167 error("socket: %.100s", strerror(errno));
4169 verbose("socket: %.100s", strerror(errno));
4172 if (set_nonblock(sock) == -1)
4173 fatal_f("set_nonblock(%d)", sock);
4174 if (connect(sock, cctx->ai->ai_addr,
4175 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4176 debug("connect_next: host %.100s ([%.100s]:%s): "
4177 "%.100s", cctx->host, ntop, strport,
4179 saved_errno = errno;
4181 errno = saved_errno;
4182 continue; /* fail -- try next */
4184 if (cctx->ai->ai_family != AF_UNIX)
4186 debug("connect_next: host %.100s ([%.100s]:%s) "
4187 "in progress, fd=%d", cctx->host, ntop, strport, sock);
4188 cctx->ai = cctx->ai->ai_next;
4195 channel_connect_ctx_free(struct channel_connect *cctx)
4199 if (cctx->aitop->ai_family == AF_UNIX)
4202 freeaddrinfo(cctx->aitop);
4204 memset(cctx, 0, sizeof(*cctx));
4208 * Return connecting socket to remote host:port or local socket path,
4209 * passing back the failure reason if appropriate.
4212 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4213 char *ctype, char *rname, struct channel_connect *cctx,
4214 int *reason, const char **errmsg)
4216 struct addrinfo hints;
4219 char strport[NI_MAXSERV];
4221 if (port == PORT_STREAMLOCAL) {
4222 struct sockaddr_un *sunaddr;
4223 struct addrinfo *ai;
4225 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4226 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4231 * Fake up a struct addrinfo for AF_UNIX connections.
4232 * channel_connect_ctx_free() must check ai_family
4233 * and use free() not freeaddirinfo() for AF_UNIX.
4235 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4236 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4237 ai->ai_addr = (struct sockaddr *)(ai + 1);
4238 ai->ai_addrlen = sizeof(*sunaddr);
4239 ai->ai_family = AF_UNIX;
4240 ai->ai_socktype = socktype;
4241 ai->ai_protocol = PF_UNSPEC;
4242 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4243 sunaddr->sun_family = AF_UNIX;
4244 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4247 memset(&hints, 0, sizeof(hints));
4248 hints.ai_family = ssh->chanctxt->IPv4or6;
4249 hints.ai_socktype = socktype;
4250 snprintf(strport, sizeof strport, "%d", port);
4251 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4254 *errmsg = ssh_gai_strerror(gaierr);
4256 *reason = SSH2_OPEN_CONNECT_FAILED;
4257 error("connect_to %.100s: unknown host (%s)", name,
4258 ssh_gai_strerror(gaierr));
4263 cctx->host = xstrdup(name);
4265 cctx->ai = cctx->aitop;
4267 if ((sock = connect_next(cctx)) == -1) {
4268 error("connect to %.100s port %d failed: %s",
4269 name, port, strerror(errno));
4276 /* Return CONNECTING channel to remote host:port or local socket path */
4278 connect_to(struct ssh *ssh, const char *host, int port,
4279 char *ctype, char *rname)
4281 struct channel_connect cctx;
4285 memset(&cctx, 0, sizeof(cctx));
4286 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4289 channel_connect_ctx_free(&cctx);
4292 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4293 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4294 c->host_port = port;
4295 c->path = xstrdup(host);
4296 c->connect_ctx = cctx;
4302 * returns either the newly connected channel or the downstream channel
4303 * that needs to deal with this connection.
4306 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4307 u_short listen_port, char *ctype, char *rname)
4309 struct ssh_channels *sc = ssh->chanctxt;
4310 struct permission_set *pset = &sc->local_perms;
4312 struct permission *perm;
4314 for (i = 0; i < pset->num_permitted_user; i++) {
4315 perm = &pset->permitted_user[i];
4316 if (open_listen_match_tcpip(perm,
4317 listen_host, listen_port, 1)) {
4318 if (perm->downstream)
4319 return perm->downstream;
4320 if (perm->port_to_connect == 0)
4321 return rdynamic_connect_prepare(ssh,
4323 return connect_to(ssh,
4324 perm->host_to_connect, perm->port_to_connect,
4328 error("WARNING: Server requests forwarding for unknown listen_port %d",
4334 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4335 char *ctype, char *rname)
4337 struct ssh_channels *sc = ssh->chanctxt;
4338 struct permission_set *pset = &sc->local_perms;
4340 struct permission *perm;
4342 for (i = 0; i < pset->num_permitted_user; i++) {
4343 perm = &pset->permitted_user[i];
4344 if (open_listen_match_streamlocal(perm, path)) {
4345 return connect_to(ssh,
4346 perm->host_to_connect, perm->port_to_connect,
4350 error("WARNING: Server requests forwarding for unknown path %.100s",
4355 /* Check if connecting to that port is permitted and connect. */
4357 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4358 char *ctype, char *rname, int *reason, const char **errmsg)
4360 struct ssh_channels *sc = ssh->chanctxt;
4361 struct permission_set *pset = &sc->local_perms;
4362 struct channel_connect cctx;
4364 u_int i, permit, permit_adm = 1;
4366 struct permission *perm;
4368 permit = pset->all_permitted;
4370 for (i = 0; i < pset->num_permitted_user; i++) {
4371 perm = &pset->permitted_user[i];
4372 if (open_match(perm, host, port)) {
4379 if (pset->num_permitted_admin > 0) {
4381 for (i = 0; i < pset->num_permitted_admin; i++) {
4382 perm = &pset->permitted_admin[i];
4383 if (open_match(perm, host, port)) {
4390 if (!permit || !permit_adm) {
4391 logit("Received request from %.100s port %d to connect to "
4392 "host %.100s port %d, but the request was denied.",
4393 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4395 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4399 memset(&cctx, 0, sizeof(cctx));
4400 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4401 &cctx, reason, errmsg);
4403 channel_connect_ctx_free(&cctx);
4407 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4408 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4409 c->host_port = port;
4410 c->path = xstrdup(host);
4411 c->connect_ctx = cctx;
4416 /* Check if connecting to that path is permitted and connect. */
4418 channel_connect_to_path(struct ssh *ssh, const char *path,
4419 char *ctype, char *rname)
4421 struct ssh_channels *sc = ssh->chanctxt;
4422 struct permission_set *pset = &sc->local_perms;
4423 u_int i, permit, permit_adm = 1;
4424 struct permission *perm;
4426 permit = pset->all_permitted;
4428 for (i = 0; i < pset->num_permitted_user; i++) {
4429 perm = &pset->permitted_user[i];
4430 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4437 if (pset->num_permitted_admin > 0) {
4439 for (i = 0; i < pset->num_permitted_admin; i++) {
4440 perm = &pset->permitted_admin[i];
4441 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4448 if (!permit || !permit_adm) {
4449 logit("Received request to connect to path %.100s, "
4450 "but the request was denied.", path);
4453 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4457 channel_send_window_changes(struct ssh *ssh)
4459 struct ssh_channels *sc = ssh->chanctxt;
4464 for (i = 0; i < sc->channels_alloc; i++) {
4465 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4466 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4468 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4470 channel_request_start(ssh, i, "window-change", 0);
4471 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4472 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4473 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4474 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4475 (r = sshpkt_send(ssh)) != 0)
4476 fatal_fr(r, "channel %u; send window-change", i);
4480 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4482 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4487 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4488 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4493 * We need to open the channel before we have a FD,
4494 * so that we can get SOCKS header from peer.
4496 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4497 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4498 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4499 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4500 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4501 fatal_fr(r, "channel %i; confirm", c->self);
4505 /* Return CONNECTING socket to remote host:port or local socket path */
4507 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4509 struct ssh_channels *sc = ssh->chanctxt;
4510 struct permission_set *pset = &sc->local_perms;
4511 struct permission *perm;
4512 struct channel_connect cctx;
4513 u_int i, permit_adm = 1;
4516 if (pset->num_permitted_admin > 0) {
4518 for (i = 0; i < pset->num_permitted_admin; i++) {
4519 perm = &pset->permitted_admin[i];
4520 if (open_match(perm, c->path, c->host_port)) {
4527 debug_f("requested forward not permitted");
4531 memset(&cctx, 0, sizeof(cctx));
4532 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4533 NULL, &cctx, NULL, NULL);
4535 channel_connect_ctx_free(&cctx);
4537 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4538 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4539 c->connect_ctx = cctx;
4540 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4545 /* -- X11 forwarding */
4548 * Creates an internet domain socket for listening for X11 connections.
4549 * Returns 0 and a suitable display number for the DISPLAY variable
4550 * stored in display_numberp , or -1 if an error occurs.
4553 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4554 int x11_use_localhost, int single_connection,
4555 u_int *display_numberp, int **chanids)
4558 int display_number, sock;
4560 struct addrinfo hints, *ai, *aitop;
4561 char strport[NI_MAXSERV];
4562 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4564 if (chanids == NULL)
4567 for (display_number = x11_display_offset;
4568 display_number < MAX_DISPLAYS;
4570 port = 6000 + display_number;
4571 memset(&hints, 0, sizeof(hints));
4572 hints.ai_family = ssh->chanctxt->IPv4or6;
4573 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4574 hints.ai_socktype = SOCK_STREAM;
4575 snprintf(strport, sizeof strport, "%d", port);
4576 if ((gaierr = getaddrinfo(NULL, strport,
4577 &hints, &aitop)) != 0) {
4578 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4581 for (ai = aitop; ai; ai = ai->ai_next) {
4582 if (ai->ai_family != AF_INET &&
4583 ai->ai_family != AF_INET6)
4585 sock = socket(ai->ai_family, ai->ai_socktype,
4588 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4590 && (errno != EPFNOSUPPORT)
4593 error("socket: %.100s", strerror(errno));
4594 freeaddrinfo(aitop);
4597 debug("x11_create_display_inet: Socket family %d not supported",
4602 if (ai->ai_family == AF_INET6)
4603 sock_set_v6only(sock);
4604 if (x11_use_localhost)
4605 set_reuseaddr(sock);
4606 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4607 debug2_f("bind port %d: %.100s", port,
4610 for (n = 0; n < num_socks; n++)
4615 socks[num_socks++] = sock;
4616 if (num_socks == NUM_SOCKS)
4619 freeaddrinfo(aitop);
4623 if (display_number >= MAX_DISPLAYS) {
4624 error("Failed to allocate internet-domain X11 display socket.");
4627 /* Start listening for connections on the socket. */
4628 for (n = 0; n < num_socks; n++) {
4630 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4631 error("listen: %.100s", strerror(errno));
4637 /* Allocate a channel for each socket. */
4638 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4639 for (n = 0; n < num_socks; n++) {
4641 nc = channel_new(ssh, "x11 listener",
4642 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4643 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4644 0, "X11 inet listener", 1);
4645 nc->single_connection = single_connection;
4646 (*chanids)[n] = nc->self;
4650 /* Return the display number for the DISPLAY environment variable. */
4651 *display_numberp = display_number;
4656 connect_local_xsocket_path(const char *pathname)
4659 struct sockaddr_un addr;
4661 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4663 error("socket: %.100s", strerror(errno));
4664 memset(&addr, 0, sizeof(addr));
4665 addr.sun_family = AF_UNIX;
4666 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4667 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4670 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4675 connect_local_xsocket(u_int dnr)
4678 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4679 return connect_local_xsocket_path(buf);
4684 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4688 if (strlcpy(path, display, pathlen) >= pathlen) {
4689 error("%s: display path too long", __func__);
4692 if (display[0] != '/')
4694 if (stat(path, &sbuf) == 0) {
4697 char *dot = strrchr(path, '.');
4700 if (stat(path, &sbuf) == 0) {
4710 x11_connect_display(struct ssh *ssh)
4712 u_int display_number;
4713 const char *display;
4714 char buf[1024], *cp;
4715 struct addrinfo hints, *ai, *aitop;
4716 char strport[NI_MAXSERV];
4717 int gaierr, sock = 0;
4719 /* Try to open a socket for the local X server. */
4720 display = getenv("DISPLAY");
4722 error("DISPLAY not set.");
4726 * Now we decode the value of the DISPLAY variable and make a
4727 * connection to the real X server.
4731 /* Check if display is a path to a socket (as set by launchd). */
4733 char path[PATH_MAX];
4735 if (is_path_to_xsocket(display, path, sizeof(path))) {
4736 debug("x11_connect_display: $DISPLAY is launchd");
4738 /* Create a socket. */
4739 sock = connect_local_xsocket_path(path);
4743 /* OK, we now have a connection to the display. */
4749 * Check if it is a unix domain socket. Unix domain displays are in
4750 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4752 if (strncmp(display, "unix:", 5) == 0 ||
4753 display[0] == ':') {
4754 /* Connect to the unix domain socket. */
4755 if (sscanf(strrchr(display, ':') + 1, "%u",
4756 &display_number) != 1) {
4757 error("Could not parse display number from DISPLAY: "
4761 /* Create a socket. */
4762 sock = connect_local_xsocket(display_number);
4766 /* OK, we now have a connection to the display. */
4770 * Connect to an inet socket. The DISPLAY value is supposedly
4771 * hostname:d[.s], where hostname may also be numeric IP address.
4773 strlcpy(buf, display, sizeof(buf));
4774 cp = strchr(buf, ':');
4776 error("Could not find ':' in DISPLAY: %.100s", display);
4781 * buf now contains the host name. But first we parse the
4784 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4785 error("Could not parse display number from DISPLAY: %.100s",
4790 /* Look up the host address */
4791 memset(&hints, 0, sizeof(hints));
4792 hints.ai_family = ssh->chanctxt->IPv4or6;
4793 hints.ai_socktype = SOCK_STREAM;
4794 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4795 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4796 error("%.100s: unknown host. (%s)", buf,
4797 ssh_gai_strerror(gaierr));
4800 for (ai = aitop; ai; ai = ai->ai_next) {
4801 /* Create a socket. */
4802 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4804 debug2("socket: %.100s", strerror(errno));
4807 /* Connect it to the display. */
4808 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4809 debug2("connect %.100s port %u: %.100s", buf,
4810 6000 + display_number, strerror(errno));
4817 freeaddrinfo(aitop);
4819 error("connect %.100s port %u: %.100s", buf,
4820 6000 + display_number, strerror(errno));
4828 * Requests forwarding of X11 connections, generates fake authentication
4829 * data, and enables authentication spoofing.
4830 * This should be called in the client only.
4833 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
4834 const char *disp, const char *proto, const char *data, int want_reply)
4836 struct ssh_channels *sc = ssh->chanctxt;
4837 u_int data_len = (u_int) strlen(data) / 2;
4841 int r, screen_number;
4843 if (sc->x11_saved_display == NULL)
4844 sc->x11_saved_display = xstrdup(disp);
4845 else if (strcmp(disp, sc->x11_saved_display) != 0) {
4846 error("x11_request_forwarding_with_spoofing: different "
4847 "$DISPLAY already forwarded");
4851 cp = strchr(disp, ':');
4853 cp = strchr(cp, '.');
4855 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4859 if (sc->x11_saved_proto == NULL) {
4860 /* Save protocol name. */
4861 sc->x11_saved_proto = xstrdup(proto);
4863 /* Extract real authentication data. */
4864 sc->x11_saved_data = xmalloc(data_len);
4865 for (i = 0; i < data_len; i++) {
4866 if (sscanf(data + 2 * i, "%2x", &value) != 1) {
4867 fatal("x11_request_forwarding: bad "
4868 "authentication data: %.100s", data);
4870 sc->x11_saved_data[i] = value;
4872 sc->x11_saved_data_len = data_len;
4874 /* Generate fake data of the same length. */
4875 sc->x11_fake_data = xmalloc(data_len);
4876 arc4random_buf(sc->x11_fake_data, data_len);
4877 sc->x11_fake_data_len = data_len;
4880 /* Convert the fake data into hex. */
4881 new_data = tohex(sc->x11_fake_data, data_len);
4883 /* Send the request packet. */
4884 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
4885 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
4886 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
4887 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
4888 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
4889 (r = sshpkt_send(ssh)) != 0 ||
4890 (r = ssh_packet_write_wait(ssh)) != 0)
4891 fatal_fr(r, "send x11-req");