1 /* $OpenBSD: channels.c,v 1.386 2018/10/04 01:04:52 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
70 #include "openbsd-compat/sys-queue.h"
84 #include "pathnames.h"
87 /* -- agent forwarding */
90 /* -- tcp forwarding */
91 /* special-case port number meaning allow any port */
92 #define FWD_PERMIT_ANY_PORT 0
94 /* special-case wildcard meaning allow any host */
95 #define FWD_PERMIT_ANY_HOST "*"
97 /* -- X11 forwarding */
98 /* Maximum number of fake X11 displays to try. */
99 #define MAX_DISPLAYS 1000
101 /* Per-channel callback for pre/post select() actions */
102 typedef void chan_fn(struct ssh *, Channel *c,
103 fd_set *readset, fd_set *writeset);
106 * Data structure for storing which hosts are permitted for forward requests.
107 * The local sides of any remote forwards are stored in this array to prevent
108 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109 * network (which might be behind a firewall).
111 /* XXX: streamlocal wants a path instead of host:port */
112 /* Overload host_to_connect; we could just make this match Forward */
113 /* XXX - can we use listen_host instead of listen_path? */
115 char *host_to_connect; /* Connect to 'host'. */
116 int port_to_connect; /* Connect to 'port'. */
117 char *listen_host; /* Remote side should listen address. */
118 char *listen_path; /* Remote side should listen path. */
119 int listen_port; /* Remote side should listen port. */
120 Channel *downstream; /* Downstream mux*/
124 * Stores the forwarding permission state for a single direction (local or
127 struct permission_set {
129 * List of all local permitted host/port pairs to allow for the
132 u_int num_permitted_user;
133 struct permission *permitted_user;
136 * List of all permitted host/port pairs to allow for the admin.
138 u_int num_permitted_admin;
139 struct permission *permitted_admin;
142 * If this is true, all opens/listens are permitted. This is the
143 * case on the server on which we have to trust the client anyway,
144 * and the user could do anything after logging in.
149 /* Master structure for channels state */
150 struct ssh_channels {
152 * Pointer to an array containing all allocated channels. The array
153 * is dynamically extended as needed.
158 * Size of the channel array. All slots of the array must always be
159 * initialized (at least the type field); unused slots set to NULL
161 u_int channels_alloc;
164 * Maximum file descriptor value used in any of the channels. This is
165 * updated in channel_new.
170 * 'channel_pre*' are called just before select() to add any bits
171 * relevant to channels in the select bitmasks.
173 * 'channel_post*': perform any appropriate operations for
174 * channels which have events pending.
176 chan_fn **channel_pre;
177 chan_fn **channel_post;
179 /* -- tcp forwarding */
180 struct permission_set local_perms;
181 struct permission_set remote_perms;
183 /* -- X11 forwarding */
185 /* Saved X11 local (client) display. */
186 char *x11_saved_display;
188 /* Saved X11 authentication protocol name. */
189 char *x11_saved_proto;
191 /* Saved X11 authentication data. This is the real data. */
192 char *x11_saved_data;
193 u_int x11_saved_data_len;
195 /* Deadline after which all X11 connections are refused */
196 u_int x11_refuse_time;
199 * Fake X11 authentication data. This is what the server will be
200 * sending us; we should replace any occurrences of this by the
203 u_char *x11_fake_data;
204 u_int x11_fake_data_len;
206 /* AF_UNSPEC or AF_INET or AF_INET6 */
211 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212 static const char *channel_rfwd_bind_host(const char *listen_host);
214 /* non-blocking connect helpers */
215 static int connect_next(struct channel_connect *);
216 static void channel_connect_ctx_free(struct channel_connect *);
217 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218 static int rdynamic_connect_finish(struct ssh *, Channel *);
221 static void channel_handler_init(struct ssh_channels *sc);
223 /* -- channel core */
226 channel_init_channels(struct ssh *ssh)
228 struct ssh_channels *sc;
230 if ((sc = calloc(1, sizeof(*sc))) == NULL ||
231 (sc->channel_pre = calloc(SSH_CHANNEL_MAX_TYPE,
232 sizeof(*sc->channel_pre))) == NULL ||
233 (sc->channel_post = calloc(SSH_CHANNEL_MAX_TYPE,
234 sizeof(*sc->channel_post))) == NULL)
235 fatal("%s: allocation failed", __func__);
236 sc->channels_alloc = 10;
237 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
238 sc->IPv4or6 = AF_UNSPEC;
239 channel_handler_init(sc);
245 channel_by_id(struct ssh *ssh, int id)
249 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
250 logit("%s: %d: bad id", __func__, id);
253 c = ssh->chanctxt->channels[id];
255 logit("%s: %d: bad id: channel free", __func__, id);
262 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
267 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
268 c = ssh->chanctxt->channels[i];
269 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
276 * Returns the channel if it is allowed to receive protocol messages.
277 * Private channels, like listening sockets, may not receive messages.
280 channel_lookup(struct ssh *ssh, int id)
284 if ((c = channel_by_id(ssh, id)) == NULL)
288 case SSH_CHANNEL_X11_OPEN:
289 case SSH_CHANNEL_LARVAL:
290 case SSH_CHANNEL_CONNECTING:
291 case SSH_CHANNEL_DYNAMIC:
292 case SSH_CHANNEL_RDYNAMIC_OPEN:
293 case SSH_CHANNEL_RDYNAMIC_FINISH:
294 case SSH_CHANNEL_OPENING:
295 case SSH_CHANNEL_OPEN:
296 case SSH_CHANNEL_ABANDONED:
297 case SSH_CHANNEL_MUX_PROXY:
300 logit("Non-public channel %d, type %d.", id, c->type);
305 * Register filedescriptors for a channel, used when allocating a channel or
306 * when the channel consumer/producer is ready, e.g. shell exec'd
309 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
310 int extusage, int nonblock, int is_tty)
312 struct ssh_channels *sc = ssh->chanctxt;
314 /* Update the maximum file descriptor value. */
315 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
316 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
317 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
320 fcntl(rfd, F_SETFD, FD_CLOEXEC);
321 if (wfd != -1 && wfd != rfd)
322 fcntl(wfd, F_SETFD, FD_CLOEXEC);
323 if (efd != -1 && efd != rfd && efd != wfd)
324 fcntl(efd, F_SETFD, FD_CLOEXEC);
328 c->sock = (rfd == wfd) ? rfd : -1;
330 c->extended_usage = extusage;
332 if ((c->isatty = is_tty) != 0)
333 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
335 /* XXX: Later AIX versions can't push as much data to tty */
336 c->wfd_isatty = is_tty || isatty(c->wfd);
339 /* enable nonblocking mode */
351 * Allocate a new channel object and set its type and socket. This will cause
352 * remote_name to be freed.
355 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
356 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
358 struct ssh_channels *sc = ssh->chanctxt;
362 /* Try to find a free slot where to put the new channel. */
363 for (i = 0; i < sc->channels_alloc; i++) {
364 if (sc->channels[i] == NULL) {
365 /* Found a free slot. */
370 if (i >= sc->channels_alloc) {
372 * There are no free slots. Take last+1 slot and expand
375 found = sc->channels_alloc;
376 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
377 fatal("%s: internal error: channels_alloc %d too big",
378 __func__, sc->channels_alloc);
379 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
380 sc->channels_alloc + 10, sizeof(*sc->channels));
381 sc->channels_alloc += 10;
382 debug2("channel: expanding %d", sc->channels_alloc);
384 /* Initialize and return new channel. */
385 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
386 if ((c->input = sshbuf_new()) == NULL ||
387 (c->output = sshbuf_new()) == NULL ||
388 (c->extended = sshbuf_new()) == NULL)
389 fatal("%s: sshbuf_new failed", __func__);
390 c->ostate = CHAN_OUTPUT_OPEN;
391 c->istate = CHAN_INPUT_OPEN;
392 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
396 c->local_window = window;
397 c->local_window_max = window;
398 c->local_maxpacket = maxpack;
399 c->remote_name = xstrdup(remote_name);
401 c->delayed = 1; /* prevent call to channel_post handler */
402 TAILQ_INIT(&c->status_confirms);
403 debug("channel %d: new [%s]", found, remote_name);
408 channel_find_maxfd(struct ssh_channels *sc)
414 for (i = 0; i < sc->channels_alloc; i++) {
417 max = MAXIMUM(max, c->rfd);
418 max = MAXIMUM(max, c->wfd);
419 max = MAXIMUM(max, c->efd);
422 sc->channel_max_fd = max;
426 channel_close_fd(struct ssh *ssh, int *fdp)
428 struct ssh_channels *sc = ssh->chanctxt;
429 int ret = 0, fd = *fdp;
434 if (fd == sc->channel_max_fd)
435 channel_find_maxfd(sc);
440 /* Close all channel fd/socket. */
442 channel_close_fds(struct ssh *ssh, Channel *c)
444 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
446 channel_close_fd(ssh, &c->sock);
448 channel_close_fd(ssh, &c->rfd);
449 if (wfd != sock && wfd != rfd)
450 channel_close_fd(ssh, &c->wfd);
451 if (efd != sock && efd != rfd && efd != wfd)
452 channel_close_fd(ssh, &c->efd);
456 fwd_perm_clear(struct permission *perm)
458 free(perm->host_to_connect);
459 free(perm->listen_host);
460 free(perm->listen_path);
461 bzero(perm, sizeof(*perm));
464 /* Returns an printable name for the specified forwarding permission list */
466 fwd_ident(int who, int where)
468 if (who == FORWARD_ADM) {
469 if (where == FORWARD_LOCAL)
470 return "admin local";
471 else if (where == FORWARD_REMOTE)
472 return "admin remote";
473 } else if (who == FORWARD_USER) {
474 if (where == FORWARD_LOCAL)
476 else if (where == FORWARD_REMOTE)
477 return "user remote";
479 fatal("Unknown forward permission list %d/%d", who, where);
482 /* Returns the forwarding permission list for the specified direction */
483 static struct permission_set *
484 permission_set_get(struct ssh *ssh, int where)
486 struct ssh_channels *sc = ssh->chanctxt;
490 return &sc->local_perms;
493 return &sc->remote_perms;
496 fatal("%s: invalid forwarding direction %d", __func__, where);
500 /* Reutrns pointers to the specified forwarding list and its element count */
502 permission_set_get_array(struct ssh *ssh, int who, int where,
503 struct permission ***permpp, u_int **npermpp)
505 struct permission_set *pset = permission_set_get(ssh, where);
509 *permpp = &pset->permitted_user;
510 *npermpp = &pset->num_permitted_user;
513 *permpp = &pset->permitted_admin;
514 *npermpp = &pset->num_permitted_admin;
517 fatal("%s: invalid forwarding client %d", __func__, who);
521 /* Adds an entry to the spcified forwarding list */
523 permission_set_add(struct ssh *ssh, int who, int where,
524 const char *host_to_connect, int port_to_connect,
525 const char *listen_host, const char *listen_path, int listen_port,
528 struct permission **permp;
531 permission_set_get_array(ssh, who, where, &permp, &npermp);
533 if (*npermp >= INT_MAX)
534 fatal("%s: %s overflow", __func__, fwd_ident(who, where));
536 *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
538 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
539 (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
540 (*permp)[n].port_to_connect = port_to_connect;
541 (*permp)[n].listen_host = MAYBE_DUP(listen_host);
542 (*permp)[n].listen_path = MAYBE_DUP(listen_path);
543 (*permp)[n].listen_port = listen_port;
544 (*permp)[n].downstream = downstream;
550 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
552 struct ssh_channels *sc = ssh->chanctxt;
553 struct permission_set *pset = &sc->local_perms;
554 struct permission *perm;
558 for (i = 0; i < pset->num_permitted_user; i++) {
559 perm = &pset->permitted_user[i];
560 if (perm->downstream != c)
563 /* cancel on the server, since mux client is gone */
564 debug("channel %d: cleanup remote forward for %s:%u",
565 c->self, perm->listen_host, perm->listen_port);
566 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
567 (r = sshpkt_put_cstring(ssh,
568 "cancel-tcpip-forward")) != 0 ||
569 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
570 (r = sshpkt_put_cstring(ssh,
571 channel_rfwd_bind_host(perm->listen_host))) != 0 ||
572 (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
573 (r = sshpkt_send(ssh)) != 0) {
574 fatal("%s: channel %i: %s", __func__,
575 c->self, ssh_err(r));
577 fwd_perm_clear(perm); /* unregister */
581 /* Free the channel and close its fd/socket. */
583 channel_free(struct ssh *ssh, Channel *c)
585 struct ssh_channels *sc = ssh->chanctxt;
589 struct channel_confirm *cc;
591 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
592 if ((other = sc->channels[i]) == NULL)
595 /* detach from mux client and prepare for closing */
596 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
597 other->type == SSH_CHANNEL_MUX_PROXY &&
598 other->mux_ctx == c) {
599 other->mux_ctx = NULL;
600 other->type = SSH_CHANNEL_OPEN;
601 other->istate = CHAN_INPUT_CLOSED;
602 other->ostate = CHAN_OUTPUT_CLOSED;
605 debug("channel %d: free: %s, nchannels %u", c->self,
606 c->remote_name ? c->remote_name : "???", n);
608 if (c->type == SSH_CHANNEL_MUX_CLIENT)
609 mux_remove_remote_forwardings(ssh, c);
611 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
612 s = channel_open_message(ssh);
613 debug3("channel %d: status: %s", c->self, s);
617 channel_close_fds(ssh, c);
618 sshbuf_free(c->input);
619 sshbuf_free(c->output);
620 sshbuf_free(c->extended);
621 c->input = c->output = c->extended = NULL;
622 free(c->remote_name);
623 c->remote_name = NULL;
626 free(c->listening_addr);
627 c->listening_addr = NULL;
628 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
629 if (cc->abandon_cb != NULL)
630 cc->abandon_cb(ssh, c, cc->ctx);
631 TAILQ_REMOVE(&c->status_confirms, cc, entry);
632 explicit_bzero(cc, sizeof(*cc));
635 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
636 c->filter_cleanup(ssh, c->self, c->filter_ctx);
637 sc->channels[c->self] = NULL;
638 explicit_bzero(c, sizeof(*c));
643 channel_free_all(struct ssh *ssh)
647 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
648 if (ssh->chanctxt->channels[i] != NULL)
649 channel_free(ssh, ssh->chanctxt->channels[i]);
653 * Closes the sockets/fds of all channels. This is used to close extra file
654 * descriptors after a fork.
657 channel_close_all(struct ssh *ssh)
661 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
662 if (ssh->chanctxt->channels[i] != NULL)
663 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
667 * Stop listening to channels.
670 channel_stop_listening(struct ssh *ssh)
675 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
676 c = ssh->chanctxt->channels[i];
679 case SSH_CHANNEL_AUTH_SOCKET:
680 case SSH_CHANNEL_PORT_LISTENER:
681 case SSH_CHANNEL_RPORT_LISTENER:
682 case SSH_CHANNEL_X11_LISTENER:
683 case SSH_CHANNEL_UNIX_LISTENER:
684 case SSH_CHANNEL_RUNIX_LISTENER:
685 channel_close_fd(ssh, &c->sock);
686 channel_free(ssh, c);
694 * Returns true if no channel has too much buffered data, and false if one or
695 * more channel is overfull.
698 channel_not_very_much_buffered_data(struct ssh *ssh)
701 u_int maxsize = ssh_packet_get_maxsize(ssh);
704 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
705 c = ssh->chanctxt->channels[i];
706 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
708 if (sshbuf_len(c->output) > maxsize) {
709 debug2("channel %d: big output buffer %zu > %u",
710 c->self, sshbuf_len(c->output), maxsize);
717 /* Returns true if any channel is still open. */
719 channel_still_open(struct ssh *ssh)
724 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
725 c = ssh->chanctxt->channels[i];
729 case SSH_CHANNEL_X11_LISTENER:
730 case SSH_CHANNEL_PORT_LISTENER:
731 case SSH_CHANNEL_RPORT_LISTENER:
732 case SSH_CHANNEL_MUX_LISTENER:
733 case SSH_CHANNEL_CLOSED:
734 case SSH_CHANNEL_AUTH_SOCKET:
735 case SSH_CHANNEL_DYNAMIC:
736 case SSH_CHANNEL_RDYNAMIC_OPEN:
737 case SSH_CHANNEL_CONNECTING:
738 case SSH_CHANNEL_ZOMBIE:
739 case SSH_CHANNEL_ABANDONED:
740 case SSH_CHANNEL_UNIX_LISTENER:
741 case SSH_CHANNEL_RUNIX_LISTENER:
743 case SSH_CHANNEL_LARVAL:
745 case SSH_CHANNEL_OPENING:
746 case SSH_CHANNEL_OPEN:
747 case SSH_CHANNEL_RDYNAMIC_FINISH:
748 case SSH_CHANNEL_X11_OPEN:
749 case SSH_CHANNEL_MUX_CLIENT:
750 case SSH_CHANNEL_MUX_PROXY:
753 fatal("%s: bad channel type %d", __func__, c->type);
760 /* Returns the id of an open channel suitable for keepaliving */
762 channel_find_open(struct ssh *ssh)
767 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
768 c = ssh->chanctxt->channels[i];
769 if (c == NULL || !c->have_remote_id)
772 case SSH_CHANNEL_CLOSED:
773 case SSH_CHANNEL_DYNAMIC:
774 case SSH_CHANNEL_RDYNAMIC_OPEN:
775 case SSH_CHANNEL_RDYNAMIC_FINISH:
776 case SSH_CHANNEL_X11_LISTENER:
777 case SSH_CHANNEL_PORT_LISTENER:
778 case SSH_CHANNEL_RPORT_LISTENER:
779 case SSH_CHANNEL_MUX_LISTENER:
780 case SSH_CHANNEL_MUX_CLIENT:
781 case SSH_CHANNEL_MUX_PROXY:
782 case SSH_CHANNEL_OPENING:
783 case SSH_CHANNEL_CONNECTING:
784 case SSH_CHANNEL_ZOMBIE:
785 case SSH_CHANNEL_ABANDONED:
786 case SSH_CHANNEL_UNIX_LISTENER:
787 case SSH_CHANNEL_RUNIX_LISTENER:
789 case SSH_CHANNEL_LARVAL:
790 case SSH_CHANNEL_AUTH_SOCKET:
791 case SSH_CHANNEL_OPEN:
792 case SSH_CHANNEL_X11_OPEN:
795 fatal("%s: bad channel type %d", __func__, c->type);
802 /* Returns the state of the channel's extended usage flag */
804 channel_format_extended_usage(const Channel *c)
809 switch (c->extended_usage) {
810 case CHAN_EXTENDED_WRITE:
812 case CHAN_EXTENDED_READ:
814 case CHAN_EXTENDED_IGNORE:
822 channel_format_status(const Channel *c)
826 xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
827 "fd %d/%d/%d sock %d cc %d",
829 c->have_remote_id ? "r" : "nr", c->remote_id,
830 c->istate, sshbuf_len(c->input),
831 c->ostate, sshbuf_len(c->output),
832 channel_format_extended_usage(c), sshbuf_len(c->extended),
833 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
838 * Returns a message describing the currently open forwarded connections,
839 * suitable for sending to the client. The message contains crlf pairs for
843 channel_open_message(struct ssh *ssh)
851 if ((buf = sshbuf_new()) == NULL)
852 fatal("%s: sshbuf_new", __func__);
853 if ((r = sshbuf_putf(buf,
854 "The following connections are open:\r\n")) != 0)
855 fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
856 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
857 c = ssh->chanctxt->channels[i];
861 case SSH_CHANNEL_X11_LISTENER:
862 case SSH_CHANNEL_PORT_LISTENER:
863 case SSH_CHANNEL_RPORT_LISTENER:
864 case SSH_CHANNEL_CLOSED:
865 case SSH_CHANNEL_AUTH_SOCKET:
866 case SSH_CHANNEL_ZOMBIE:
867 case SSH_CHANNEL_ABANDONED:
868 case SSH_CHANNEL_MUX_LISTENER:
869 case SSH_CHANNEL_UNIX_LISTENER:
870 case SSH_CHANNEL_RUNIX_LISTENER:
872 case SSH_CHANNEL_LARVAL:
873 case SSH_CHANNEL_OPENING:
874 case SSH_CHANNEL_CONNECTING:
875 case SSH_CHANNEL_DYNAMIC:
876 case SSH_CHANNEL_RDYNAMIC_OPEN:
877 case SSH_CHANNEL_RDYNAMIC_FINISH:
878 case SSH_CHANNEL_OPEN:
879 case SSH_CHANNEL_X11_OPEN:
880 case SSH_CHANNEL_MUX_PROXY:
881 case SSH_CHANNEL_MUX_CLIENT:
882 cp = channel_format_status(c);
883 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
884 c->self, c->remote_name, cp)) != 0) {
886 fatal("%s: sshbuf_putf: %s",
887 __func__, ssh_err(r));
892 fatal("%s: bad channel type %d", __func__, c->type);
896 if ((ret = sshbuf_dup_string(buf)) == NULL)
897 fatal("%s: sshbuf_dup_string", __func__);
903 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
907 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
908 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
909 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
910 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
911 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
912 fatal("%s: channel %i: open: %s", where, c->self, ssh_err(r));
917 channel_send_open(struct ssh *ssh, int id)
919 Channel *c = channel_lookup(ssh, id);
923 logit("channel_send_open: %d: bad id", id);
926 debug2("channel %d: send open", id);
927 open_preamble(ssh, __func__, c, c->ctype);
928 if ((r = sshpkt_send(ssh)) != 0)
929 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
933 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
935 Channel *c = channel_lookup(ssh, id);
939 logit("%s: %d: unknown channel id", __func__, id);
942 if (!c->have_remote_id)
943 fatal(":%s: channel %d: no remote id", __func__, c->self);
945 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
946 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
947 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
948 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
949 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
950 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
955 channel_register_status_confirm(struct ssh *ssh, int id,
956 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
958 struct channel_confirm *cc;
961 if ((c = channel_lookup(ssh, id)) == NULL)
962 fatal("%s: %d: bad id", __func__, id);
964 cc = xcalloc(1, sizeof(*cc));
966 cc->abandon_cb = abandon_cb;
968 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
972 channel_register_open_confirm(struct ssh *ssh, int id,
973 channel_open_fn *fn, void *ctx)
975 Channel *c = channel_lookup(ssh, id);
978 logit("%s: %d: bad id", __func__, id);
981 c->open_confirm = fn;
982 c->open_confirm_ctx = ctx;
986 channel_register_cleanup(struct ssh *ssh, int id,
987 channel_callback_fn *fn, int do_close)
989 Channel *c = channel_by_id(ssh, id);
992 logit("%s: %d: bad id", __func__, id);
996 c->detach_close = do_close;
1000 channel_cancel_cleanup(struct ssh *ssh, int id)
1002 Channel *c = channel_by_id(ssh, id);
1005 logit("%s: %d: bad id", __func__, id);
1008 c->detach_user = NULL;
1009 c->detach_close = 0;
1013 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1014 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1016 Channel *c = channel_lookup(ssh, id);
1019 logit("%s: %d: bad id", __func__, id);
1022 c->input_filter = ifn;
1023 c->output_filter = ofn;
1024 c->filter_ctx = ctx;
1025 c->filter_cleanup = cfn;
1029 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1030 int extusage, int nonblock, int is_tty, u_int window_max)
1032 Channel *c = channel_lookup(ssh, id);
1035 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1036 fatal("channel_activate for non-larval channel %d.", id);
1037 if (!c->have_remote_id)
1038 fatal(":%s: channel %d: no remote id", __func__, c->self);
1040 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1041 c->type = SSH_CHANNEL_OPEN;
1042 c->local_window = c->local_window_max = window_max;
1044 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1045 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1046 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1047 (r = sshpkt_send(ssh)) != 0)
1048 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
1052 channel_pre_listener(struct ssh *ssh, Channel *c,
1053 fd_set *readset, fd_set *writeset)
1055 FD_SET(c->sock, readset);
1059 channel_pre_connecting(struct ssh *ssh, Channel *c,
1060 fd_set *readset, fd_set *writeset)
1062 debug3("channel %d: waiting for connection", c->self);
1063 FD_SET(c->sock, writeset);
1067 channel_pre_open(struct ssh *ssh, Channel *c,
1068 fd_set *readset, fd_set *writeset)
1070 if (c->istate == CHAN_INPUT_OPEN &&
1071 c->remote_window > 0 &&
1072 sshbuf_len(c->input) < c->remote_window &&
1073 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1074 FD_SET(c->rfd, readset);
1075 if (c->ostate == CHAN_OUTPUT_OPEN ||
1076 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1077 if (sshbuf_len(c->output) > 0) {
1078 FD_SET(c->wfd, writeset);
1079 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1080 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1081 debug2("channel %d: "
1082 "obuf_empty delayed efd %d/(%zu)", c->self,
1083 c->efd, sshbuf_len(c->extended));
1085 chan_obuf_empty(ssh, c);
1088 /** XXX check close conditions, too */
1089 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1090 c->ostate == CHAN_OUTPUT_CLOSED)) {
1091 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1092 sshbuf_len(c->extended) > 0)
1093 FD_SET(c->efd, writeset);
1094 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1095 (c->extended_usage == CHAN_EXTENDED_READ ||
1096 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1097 sshbuf_len(c->extended) < c->remote_window)
1098 FD_SET(c->efd, readset);
1100 /* XXX: What about efd? races? */
1104 * This is a special state for X11 authentication spoofing. An opened X11
1105 * connection (when authentication spoofing is being done) remains in this
1106 * state until the first packet has been completely read. The authentication
1107 * data in that packet is then substituted by the real data if it matches the
1108 * fake data, and the channel is put into normal mode.
1109 * XXX All this happens at the client side.
1110 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1113 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1115 struct ssh_channels *sc = ssh->chanctxt;
1117 u_int proto_len, data_len;
1119 /* Is this being called after the refusal deadline? */
1120 if (sc->x11_refuse_time != 0 &&
1121 (u_int)monotime() >= sc->x11_refuse_time) {
1122 verbose("Rejected X11 connection after ForwardX11Timeout "
1127 /* Check if the fixed size part of the packet is in buffer. */
1128 if (sshbuf_len(b) < 12)
1131 /* Parse the lengths of variable-length fields. */
1132 ucp = sshbuf_mutable_ptr(b);
1133 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1134 proto_len = 256 * ucp[6] + ucp[7];
1135 data_len = 256 * ucp[8] + ucp[9];
1136 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1137 proto_len = ucp[6] + 256 * ucp[7];
1138 data_len = ucp[8] + 256 * ucp[9];
1140 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1145 /* Check if the whole packet is in buffer. */
1147 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1150 /* Check if authentication protocol matches. */
1151 if (proto_len != strlen(sc->x11_saved_proto) ||
1152 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1153 debug2("X11 connection uses different authentication protocol.");
1156 /* Check if authentication data matches our fake data. */
1157 if (data_len != sc->x11_fake_data_len ||
1158 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1159 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1160 debug2("X11 auth data does not match fake data.");
1163 /* Check fake data length */
1164 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1165 error("X11 fake_data_len %d != saved_data_len %d",
1166 sc->x11_fake_data_len, sc->x11_saved_data_len);
1170 * Received authentication protocol and data match
1171 * our fake data. Substitute the fake data with real
1174 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1175 sc->x11_saved_data, sc->x11_saved_data_len);
1180 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1181 fd_set *readset, fd_set *writeset)
1183 int ret = x11_open_helper(ssh, c->output);
1185 /* c->force_drain = 1; */
1188 c->type = SSH_CHANNEL_OPEN;
1189 channel_pre_open(ssh, c, readset, writeset);
1190 } else if (ret == -1) {
1191 logit("X11 connection rejected because of wrong authentication.");
1192 debug2("X11 rejected %d i%d/o%d",
1193 c->self, c->istate, c->ostate);
1194 chan_read_failed(ssh, c);
1195 sshbuf_reset(c->input);
1196 chan_ibuf_empty(ssh, c);
1197 sshbuf_reset(c->output);
1198 chan_write_failed(ssh, c);
1199 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1204 channel_pre_mux_client(struct ssh *ssh,
1205 Channel *c, fd_set *readset, fd_set *writeset)
1207 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1208 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1209 FD_SET(c->rfd, readset);
1210 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1211 /* clear buffer immediately (discard any partial packet) */
1212 sshbuf_reset(c->input);
1213 chan_ibuf_empty(ssh, c);
1214 /* Start output drain. XXX just kill chan? */
1215 chan_rcvd_oclose(ssh, c);
1217 if (c->ostate == CHAN_OUTPUT_OPEN ||
1218 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1219 if (sshbuf_len(c->output) > 0)
1220 FD_SET(c->wfd, writeset);
1221 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1222 chan_obuf_empty(ssh, c);
1226 /* try to decode a socks4 header */
1228 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1232 u_int len, have, i, found, need;
1237 u_int16_t dest_port;
1238 struct in_addr dest_addr;
1242 debug2("channel %d: decode socks4", c->self);
1244 have = sshbuf_len(input);
1245 len = sizeof(s4_req);
1248 p = sshbuf_ptr(input);
1251 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1252 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1253 debug2("channel %d: socks4a request", c->self);
1254 /* ... and needs an extra string (the hostname) */
1257 /* Check for terminating NUL on the string(s) */
1258 for (found = 0, i = len; i < have; i++) {
1265 /* the peer is probably sending garbage */
1266 debug("channel %d: decode socks4: too long",
1273 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1274 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1275 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1276 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1277 debug("channels %d: decode socks4: %s", c->self, ssh_err(r));
1280 have = sshbuf_len(input);
1281 p = sshbuf_ptr(input);
1282 if (memchr(p, '\0', have) == NULL) {
1283 error("channel %d: decode socks4: user not nul terminated",
1288 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1289 len++; /* trailing '\0' */
1290 strlcpy(username, p, sizeof(username));
1291 if ((r = sshbuf_consume(input, len)) != 0) {
1292 fatal("%s: channel %d: consume: %s", __func__,
1293 c->self, ssh_err(r));
1297 if (need == 1) { /* SOCKS4: one string */
1298 host = inet_ntoa(s4_req.dest_addr);
1299 c->path = xstrdup(host);
1300 } else { /* SOCKS4A: two strings */
1301 have = sshbuf_len(input);
1302 p = sshbuf_ptr(input);
1303 if (memchr(p, '\0', have) == NULL) {
1304 error("channel %d: decode socks4a: host not nul "
1305 "terminated", c->self);
1309 debug2("channel %d: decode socks4a: host %s/%d",
1311 len++; /* trailing '\0' */
1312 if (len > NI_MAXHOST) {
1313 error("channel %d: hostname \"%.100s\" too long",
1317 c->path = xstrdup(p);
1318 if ((r = sshbuf_consume(input, len)) != 0) {
1319 fatal("%s: channel %d: consume: %s", __func__,
1320 c->self, ssh_err(r));
1323 c->host_port = ntohs(s4_req.dest_port);
1325 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1326 c->self, c->path, c->host_port, s4_req.command);
1328 if (s4_req.command != 1) {
1329 debug("channel %d: cannot handle: %s cn %d",
1330 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1333 s4_rsp.version = 0; /* vn: 0 for reply */
1334 s4_rsp.command = 90; /* cd: req granted */
1335 s4_rsp.dest_port = 0; /* ignored */
1336 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1337 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0) {
1338 fatal("%s: channel %d: append reply: %s", __func__,
1339 c->self, ssh_err(r));
1344 /* try to decode a socks5 header */
1345 #define SSH_SOCKS5_AUTHDONE 0x1000
1346 #define SSH_SOCKS5_NOAUTH 0x00
1347 #define SSH_SOCKS5_IPV4 0x01
1348 #define SSH_SOCKS5_DOMAIN 0x03
1349 #define SSH_SOCKS5_IPV6 0x04
1350 #define SSH_SOCKS5_CONNECT 0x01
1351 #define SSH_SOCKS5_SUCCESS 0x00
1354 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1356 /* XXX use get/put_u8 instead of trusting struct padding */
1363 u_int16_t dest_port;
1364 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1366 u_int have, need, i, found, nmethods, addrlen, af;
1369 debug2("channel %d: decode socks5", c->self);
1370 p = sshbuf_ptr(input);
1373 have = sshbuf_len(input);
1374 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1375 /* format: ver | nmethods | methods */
1379 if (have < nmethods + 2)
1381 /* look for method: "NO AUTHENTICATION REQUIRED" */
1382 for (found = 0, i = 2; i < nmethods + 2; i++) {
1383 if (p[i] == SSH_SOCKS5_NOAUTH) {
1389 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1393 if ((r = sshbuf_consume(input, nmethods + 2)) != 0) {
1394 fatal("%s: channel %d: consume: %s", __func__,
1395 c->self, ssh_err(r));
1397 /* version, method */
1398 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1399 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0) {
1400 fatal("%s: channel %d: append reply: %s", __func__,
1401 c->self, ssh_err(r));
1403 c->flags |= SSH_SOCKS5_AUTHDONE;
1404 debug2("channel %d: socks5 auth done", c->self);
1405 return 0; /* need more */
1407 debug2("channel %d: socks5 post auth", c->self);
1408 if (have < sizeof(s5_req)+1)
1409 return 0; /* need more */
1410 memcpy(&s5_req, p, sizeof(s5_req));
1411 if (s5_req.version != 0x05 ||
1412 s5_req.command != SSH_SOCKS5_CONNECT ||
1413 s5_req.reserved != 0x00) {
1414 debug2("channel %d: only socks5 connect supported", c->self);
1417 switch (s5_req.atyp){
1418 case SSH_SOCKS5_IPV4:
1422 case SSH_SOCKS5_DOMAIN:
1423 addrlen = p[sizeof(s5_req)];
1426 case SSH_SOCKS5_IPV6:
1431 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1434 need = sizeof(s5_req) + addrlen + 2;
1435 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1439 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0) {
1440 fatal("%s: channel %d: consume: %s", __func__,
1441 c->self, ssh_err(r));
1443 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1444 /* host string length */
1445 if ((r = sshbuf_consume(input, 1)) != 0) {
1446 fatal("%s: channel %d: consume: %s", __func__,
1447 c->self, ssh_err(r));
1450 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1451 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1452 debug("channel %d: parse addr/port: %s", c->self, ssh_err(r));
1455 dest_addr[addrlen] = '\0';
1458 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1459 if (addrlen >= NI_MAXHOST) {
1460 error("channel %d: dynamic request: socks5 hostname "
1461 "\"%.100s\" too long", c->self, dest_addr);
1464 c->path = xstrdup(dest_addr);
1466 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1468 c->path = xstrdup(ntop);
1470 c->host_port = ntohs(dest_port);
1472 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1473 c->self, c->path, c->host_port, s5_req.command);
1475 s5_rsp.version = 0x05;
1476 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1477 s5_rsp.reserved = 0; /* ignored */
1478 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1479 dest_port = 0; /* ignored */
1481 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1482 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1483 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1484 fatal("%s: channel %d: append reply: %s", __func__,
1485 c->self, ssh_err(r));
1490 channel_connect_stdio_fwd(struct ssh *ssh,
1491 const char *host_to_connect, u_short port_to_connect, int in, int out)
1495 debug("%s %s:%d", __func__, host_to_connect, port_to_connect);
1497 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1498 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1499 0, "stdio-forward", /*nonblock*/0);
1501 c->path = xstrdup(host_to_connect);
1502 c->host_port = port_to_connect;
1503 c->listening_port = 0;
1506 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1507 port_open_helper(ssh, c, "direct-tcpip");
1512 /* dynamic port forwarding */
1514 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1515 fd_set *readset, fd_set *writeset)
1521 have = sshbuf_len(c->input);
1522 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1523 /* sshbuf_dump(c->input, stderr); */
1524 /* check if the fixed size part of the packet is in buffer. */
1527 FD_SET(c->sock, readset);
1530 /* try to guess the protocol */
1531 p = sshbuf_ptr(c->input);
1532 /* XXX sshbuf_peek_u8? */
1535 ret = channel_decode_socks4(c, c->input, c->output);
1538 ret = channel_decode_socks5(c, c->input, c->output);
1545 chan_mark_dead(ssh, c);
1546 } else if (ret == 0) {
1547 debug2("channel %d: pre_dynamic: need more", c->self);
1549 FD_SET(c->sock, readset);
1550 if (sshbuf_len(c->output))
1551 FD_SET(c->sock, writeset);
1553 /* switch to the next state */
1554 c->type = SSH_CHANNEL_OPENING;
1555 port_open_helper(ssh, c, "direct-tcpip");
1559 /* simulate read-error */
1561 rdynamic_close(struct ssh *ssh, Channel *c)
1563 c->type = SSH_CHANNEL_OPEN;
1564 chan_read_failed(ssh, c);
1565 sshbuf_reset(c->input);
1566 chan_ibuf_empty(ssh, c);
1567 sshbuf_reset(c->output);
1568 chan_write_failed(ssh, c);
1571 /* reverse dynamic port forwarding */
1573 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1579 have = sshbuf_len(c->output);
1580 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1581 /* sshbuf_dump(c->output, stderr); */
1583 if (c->flags & CHAN_EOF_RCVD) {
1584 if ((r = sshbuf_consume(c->output, have)) != 0) {
1585 fatal("%s: channel %d: consume: %s",
1586 __func__, c->self, ssh_err(r));
1588 rdynamic_close(ssh, c);
1591 /* check if the fixed size part of the packet is in buffer. */
1594 /* try to guess the protocol */
1595 p = sshbuf_ptr(c->output);
1598 /* switch input/output for reverse forwarding */
1599 ret = channel_decode_socks4(c, c->output, c->input);
1602 ret = channel_decode_socks5(c, c->output, c->input);
1609 rdynamic_close(ssh, c);
1610 } else if (ret == 0) {
1611 debug2("channel %d: pre_rdynamic: need more", c->self);
1612 /* send socks request to peer */
1613 len = sshbuf_len(c->input);
1614 if (len > 0 && len < c->remote_window) {
1615 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1616 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1617 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1618 (r = sshpkt_send(ssh)) != 0) {
1619 fatal("%s: channel %i: rdynamic: %s", __func__,
1620 c->self, ssh_err(r));
1622 if ((r = sshbuf_consume(c->input, len)) != 0) {
1623 fatal("%s: channel %d: consume: %s",
1624 __func__, c->self, ssh_err(r));
1626 c->remote_window -= len;
1628 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1629 /* the connect failed */
1630 rdynamic_close(ssh, c);
1634 /* This is our fake X11 server socket. */
1636 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1637 fd_set *readset, fd_set *writeset)
1640 struct sockaddr_storage addr;
1641 int r, newsock, oerrno, remote_port;
1643 char buf[16384], *remote_ipaddr;
1645 if (!FD_ISSET(c->sock, readset))
1648 debug("X11 connection requested.");
1649 addrlen = sizeof(addr);
1650 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1651 if (c->single_connection) {
1653 debug2("single_connection: closing X11 listener.");
1654 channel_close_fd(ssh, &c->sock);
1655 chan_mark_dead(ssh, c);
1659 if (errno != EINTR && errno != EWOULDBLOCK &&
1660 errno != ECONNABORTED)
1661 error("accept: %.100s", strerror(errno));
1662 if (errno == EMFILE || errno == ENFILE)
1663 c->notbefore = monotime() + 1;
1666 set_nodelay(newsock);
1667 remote_ipaddr = get_peer_ipaddr(newsock);
1668 remote_port = get_peer_port(newsock);
1669 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1670 remote_ipaddr, remote_port);
1672 nc = channel_new(ssh, "accepted x11 socket",
1673 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1674 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1675 open_preamble(ssh, __func__, nc, "x11");
1676 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1677 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1678 fatal("%s: channel %i: reply %s", __func__,
1679 c->self, ssh_err(r));
1681 if ((r = sshpkt_send(ssh)) != 0)
1682 fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1683 free(remote_ipaddr);
1687 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1689 char *local_ipaddr = get_local_ipaddr(c->sock);
1690 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1691 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1692 int remote_port = get_peer_port(c->sock);
1695 if (remote_port == -1) {
1696 /* Fake addr/port to appease peers that validate it (Tectia) */
1697 free(remote_ipaddr);
1698 remote_ipaddr = xstrdup("127.0.0.1");
1699 remote_port = 65535;
1702 free(c->remote_name);
1703 xasprintf(&c->remote_name,
1704 "%s: listening port %d for %.100s port %d, "
1705 "connect from %.200s port %d to %.100s port %d",
1706 rtype, c->listening_port, c->path, c->host_port,
1707 remote_ipaddr, remote_port, local_ipaddr, local_port);
1709 open_preamble(ssh, __func__, c, rtype);
1710 if (strcmp(rtype, "direct-tcpip") == 0) {
1711 /* target host, port */
1712 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1713 (r = sshpkt_put_u32(ssh, c->host_port)) != 0) {
1714 fatal("%s: channel %i: reply %s", __func__,
1715 c->self, ssh_err(r));
1717 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1719 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1720 fatal("%s: channel %i: reply %s", __func__,
1721 c->self, ssh_err(r));
1723 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1725 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1726 fatal("%s: channel %i: reply %s", __func__,
1727 c->self, ssh_err(r));
1730 /* listen address, port */
1731 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1732 (r = sshpkt_put_u32(ssh, local_port)) != 0) {
1733 fatal("%s: channel %i: reply %s", __func__,
1734 c->self, ssh_err(r));
1737 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1738 /* reserved for future owner/mode info */
1739 if ((r = sshpkt_put_cstring(ssh, "")) != 0) {
1740 fatal("%s: channel %i: reply %s", __func__,
1741 c->self, ssh_err(r));
1744 /* originator host and port */
1745 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1746 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0) {
1747 fatal("%s: channel %i: reply %s", __func__,
1748 c->self, ssh_err(r));
1751 if ((r = sshpkt_send(ssh)) != 0)
1752 fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1753 free(remote_ipaddr);
1758 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1760 ssh->chanctxt->x11_refuse_time = refuse_time;
1764 * This socket is listening for connections to a forwarded TCP/IP port.
1767 channel_post_port_listener(struct ssh *ssh, Channel *c,
1768 fd_set *readset, fd_set *writeset)
1771 struct sockaddr_storage addr;
1772 int newsock, nextstate;
1776 if (!FD_ISSET(c->sock, readset))
1779 debug("Connection to port %d forwarding to %.100s port %d requested.",
1780 c->listening_port, c->path, c->host_port);
1782 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1783 nextstate = SSH_CHANNEL_OPENING;
1784 rtype = "forwarded-tcpip";
1785 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1786 nextstate = SSH_CHANNEL_OPENING;
1787 rtype = "forwarded-streamlocal@openssh.com";
1788 } else if (c->host_port == PORT_STREAMLOCAL) {
1789 nextstate = SSH_CHANNEL_OPENING;
1790 rtype = "direct-streamlocal@openssh.com";
1791 } else if (c->host_port == 0) {
1792 nextstate = SSH_CHANNEL_DYNAMIC;
1793 rtype = "dynamic-tcpip";
1795 nextstate = SSH_CHANNEL_OPENING;
1796 rtype = "direct-tcpip";
1799 addrlen = sizeof(addr);
1800 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1802 if (errno != EINTR && errno != EWOULDBLOCK &&
1803 errno != ECONNABORTED)
1804 error("accept: %.100s", strerror(errno));
1805 if (errno == EMFILE || errno == ENFILE)
1806 c->notbefore = monotime() + 1;
1809 if (c->host_port != PORT_STREAMLOCAL)
1810 set_nodelay(newsock);
1811 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1812 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1813 nc->listening_port = c->listening_port;
1814 nc->host_port = c->host_port;
1815 if (c->path != NULL)
1816 nc->path = xstrdup(c->path);
1818 if (nextstate != SSH_CHANNEL_DYNAMIC)
1819 port_open_helper(ssh, nc, rtype);
1823 * This is the authentication agent socket listening for connections from
1827 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1828 fd_set *readset, fd_set *writeset)
1832 struct sockaddr_storage addr;
1835 if (!FD_ISSET(c->sock, readset))
1838 addrlen = sizeof(addr);
1839 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1841 error("accept from auth socket: %.100s", strerror(errno));
1842 if (errno == EMFILE || errno == ENFILE)
1843 c->notbefore = monotime() + 1;
1846 nc = channel_new(ssh, "accepted auth socket",
1847 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1848 c->local_window_max, c->local_maxpacket,
1849 0, "accepted auth socket", 1);
1850 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1851 if ((r = sshpkt_send(ssh)) != 0)
1852 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
1856 channel_post_connecting(struct ssh *ssh, Channel *c,
1857 fd_set *readset, fd_set *writeset)
1859 int err = 0, sock, isopen, r;
1860 socklen_t sz = sizeof(err);
1862 if (!FD_ISSET(c->sock, writeset))
1864 if (!c->have_remote_id)
1865 fatal(":%s: channel %d: no remote id", __func__, c->self);
1866 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1867 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1868 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1870 error("getsockopt SO_ERROR failed");
1873 debug("channel %d: connected to %s port %d",
1874 c->self, c->connect_ctx.host, c->connect_ctx.port);
1875 channel_connect_ctx_free(&c->connect_ctx);
1876 c->type = SSH_CHANNEL_OPEN;
1878 /* no message necessary */
1880 if ((r = sshpkt_start(ssh,
1881 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1882 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1883 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1884 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1885 (r = sshpkt_put_u32(ssh, c->local_maxpacket))
1887 fatal("%s: channel %i: confirm: %s", __func__,
1888 c->self, ssh_err(r));
1889 if ((r = sshpkt_send(ssh)) != 0)
1890 fatal("%s: channel %i: %s", __func__, c->self,
1894 debug("channel %d: connection failed: %s",
1895 c->self, strerror(err));
1896 /* Try next address, if any */
1897 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1899 c->sock = c->rfd = c->wfd = sock;
1900 channel_find_maxfd(ssh->chanctxt);
1903 /* Exhausted all addresses */
1904 error("connect_to %.100s port %d: failed.",
1905 c->connect_ctx.host, c->connect_ctx.port);
1906 channel_connect_ctx_free(&c->connect_ctx);
1908 rdynamic_close(ssh, c);
1910 if ((r = sshpkt_start(ssh,
1911 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1912 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1913 (r = sshpkt_put_u32(ssh,
1914 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1915 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1916 (r = sshpkt_put_cstring(ssh, "")) != 0) {
1917 fatal("%s: channel %i: failure: %s", __func__,
1918 c->self, ssh_err(r));
1920 if ((r = sshpkt_send(ssh)) != 0)
1921 fatal("%s: channel %i: %s", __func__, c->self,
1923 chan_mark_dead(ssh, c);
1929 channel_handle_rfd(struct ssh *ssh, Channel *c,
1930 fd_set *readset, fd_set *writeset)
1932 char buf[CHAN_RBUF];
1936 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1938 if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1942 len = read(c->rfd, buf, sizeof(buf));
1943 if (len < 0 && (errno == EINTR ||
1944 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1946 #ifndef PTY_ZEROREAD
1949 if ((!c->isatty && len <= 0) ||
1950 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1952 debug2("channel %d: read<=0 rfd %d len %zd",
1953 c->self, c->rfd, len);
1954 if (c->type != SSH_CHANNEL_OPEN) {
1955 debug2("channel %d: not open", c->self);
1956 chan_mark_dead(ssh, c);
1959 chan_read_failed(ssh, c);
1963 if (c->input_filter != NULL) {
1964 if (c->input_filter(ssh, c, buf, len) == -1) {
1965 debug2("channel %d: filter stops", c->self);
1966 chan_read_failed(ssh, c);
1968 } else if (c->datagram) {
1969 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1970 fatal("%s: channel %d: put datagram: %s", __func__,
1971 c->self, ssh_err(r));
1972 } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
1973 fatal("%s: channel %d: put data: %s", __func__,
1974 c->self, ssh_err(r));
1980 channel_handle_wfd(struct ssh *ssh, Channel *c,
1981 fd_set *readset, fd_set *writeset)
1984 u_char *data = NULL, *buf; /* XXX const; need filter API change */
1985 size_t dlen, olen = 0;
1988 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1989 sshbuf_len(c->output) == 0)
1992 /* Send buffered output data to the socket. */
1993 olen = sshbuf_len(c->output);
1994 if (c->output_filter != NULL) {
1995 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1996 debug2("channel %d: filter stops", c->self);
1997 if (c->type != SSH_CHANNEL_OPEN)
1998 chan_mark_dead(ssh, c);
2000 chan_write_failed(ssh, c);
2003 } else if (c->datagram) {
2004 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2005 fatal("%s: channel %d: get datagram: %s", __func__,
2006 c->self, ssh_err(r));
2009 buf = data = sshbuf_mutable_ptr(c->output);
2010 dlen = sshbuf_len(c->output);
2014 /* ignore truncated writes, datagrams might get lost */
2015 len = write(c->wfd, buf, dlen);
2017 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
2018 errno == EWOULDBLOCK))
2026 /* XXX: Later AIX versions can't push as much data to tty */
2028 dlen = MIN(dlen, 8*1024);
2031 len = write(c->wfd, buf, dlen);
2033 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2037 if (c->type != SSH_CHANNEL_OPEN) {
2038 debug2("channel %d: not open", c->self);
2039 chan_mark_dead(ssh, c);
2042 chan_write_failed(ssh, c);
2046 #ifndef BROKEN_TCGETATTR_ICANON
2047 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2048 if (tcgetattr(c->wfd, &tio) == 0 &&
2049 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2051 * Simulate echo to reduce the impact of
2052 * traffic analysis. We need to match the
2053 * size of a SSH2_MSG_CHANNEL_DATA message
2054 * (4 byte channel id + buf)
2056 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2057 (r = sshpkt_send(ssh)) != 0)
2058 fatal("%s: channel %d: ignore: %s",
2059 __func__, c->self, ssh_err(r));
2062 #endif /* BROKEN_TCGETATTR_ICANON */
2063 if ((r = sshbuf_consume(c->output, len)) != 0) {
2064 fatal("%s: channel %d: consume: %s",
2065 __func__, c->self, ssh_err(r));
2068 c->local_consumed += olen - sshbuf_len(c->output);
2074 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2075 fd_set *readset, fd_set *writeset)
2080 if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2083 len = write(c->efd, sshbuf_ptr(c->extended),
2084 sshbuf_len(c->extended));
2085 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2086 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
2087 errno == EWOULDBLOCK))
2090 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2091 channel_close_fd(ssh, &c->efd);
2093 if ((r = sshbuf_consume(c->extended, len)) != 0) {
2094 fatal("%s: channel %d: consume: %s",
2095 __func__, c->self, ssh_err(r));
2097 c->local_consumed += len;
2103 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2104 fd_set *readset, fd_set *writeset)
2106 char buf[CHAN_RBUF];
2110 if (!c->detach_close && !FD_ISSET(c->efd, readset))
2113 len = read(c->efd, buf, sizeof(buf));
2114 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2115 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
2116 errno == EWOULDBLOCK) && !c->detach_close)))
2119 debug2("channel %d: closing read-efd %d",
2121 channel_close_fd(ssh, &c->efd);
2123 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
2124 debug3("channel %d: discard efd",
2126 } else if ((r = sshbuf_put(c->extended, buf, len)) != 0) {
2127 fatal("%s: channel %d: append: %s",
2128 __func__, c->self, ssh_err(r));
2135 channel_handle_efd(struct ssh *ssh, Channel *c,
2136 fd_set *readset, fd_set *writeset)
2141 /** XXX handle drain efd, too */
2143 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2144 return channel_handle_efd_write(ssh, c, readset, writeset);
2145 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2146 c->extended_usage == CHAN_EXTENDED_IGNORE)
2147 return channel_handle_efd_read(ssh, c, readset, writeset);
2153 channel_check_window(struct ssh *ssh, Channel *c)
2157 if (c->type == SSH_CHANNEL_OPEN &&
2158 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2159 ((c->local_window_max - c->local_window >
2160 c->local_maxpacket*3) ||
2161 c->local_window < c->local_window_max/2) &&
2162 c->local_consumed > 0) {
2163 if (!c->have_remote_id)
2164 fatal(":%s: channel %d: no remote id",
2166 if ((r = sshpkt_start(ssh,
2167 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2168 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2169 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2170 (r = sshpkt_send(ssh)) != 0) {
2171 fatal("%s: channel %i: %s", __func__,
2172 c->self, ssh_err(r));
2174 debug2("channel %d: window %d sent adjust %d",
2175 c->self, c->local_window,
2177 c->local_window += c->local_consumed;
2178 c->local_consumed = 0;
2184 channel_post_open(struct ssh *ssh, Channel *c,
2185 fd_set *readset, fd_set *writeset)
2187 channel_handle_rfd(ssh, c, readset, writeset);
2188 channel_handle_wfd(ssh, c, readset, writeset);
2189 channel_handle_efd(ssh, c, readset, writeset);
2190 channel_check_window(ssh, c);
2194 read_mux(struct ssh *ssh, Channel *c, u_int need)
2196 char buf[CHAN_RBUF];
2201 if (sshbuf_len(c->input) < need) {
2202 rlen = need - sshbuf_len(c->input);
2203 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2204 if (len < 0 && (errno == EINTR || errno == EAGAIN))
2205 return sshbuf_len(c->input);
2207 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2208 c->self, c->rfd, len);
2209 chan_read_failed(ssh, c);
2211 } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
2212 fatal("%s: channel %d: append: %s",
2213 __func__, c->self, ssh_err(r));
2216 return sshbuf_len(c->input);
2220 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2221 fd_set *readset, fd_set *writeset)
2225 if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2227 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2233 * Don't not read past the precise end of packets to
2234 * avoid disrupting fd passing.
2236 if (read_mux(ssh, c, 4) < 4) /* read header */
2238 /* XXX sshbuf_peek_u32 */
2239 need = PEEK_U32(sshbuf_ptr(c->input));
2240 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2241 if (need > CHANNEL_MUX_MAX_PACKET) {
2242 debug2("channel %d: packet too big %u > %u",
2243 c->self, CHANNEL_MUX_MAX_PACKET, need);
2244 chan_rcvd_oclose(ssh, c);
2247 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2249 if (c->mux_rcb(ssh, c) != 0) {
2250 debug("channel %d: mux_rcb failed", c->self);
2251 chan_mark_dead(ssh, c);
2257 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2258 fd_set *readset, fd_set *writeset)
2263 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2264 sshbuf_len(c->output) == 0)
2267 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2268 if (len < 0 && (errno == EINTR || errno == EAGAIN))
2271 chan_mark_dead(ssh, c);
2274 if ((r = sshbuf_consume(c->output, len)) != 0)
2275 fatal("%s: channel %d: consume: %s", __func__,
2276 c->self, ssh_err(r));
2280 channel_post_mux_client(struct ssh *ssh, Channel *c,
2281 fd_set *readset, fd_set *writeset)
2283 channel_post_mux_client_read(ssh, c, readset, writeset);
2284 channel_post_mux_client_write(ssh, c, readset, writeset);
2288 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2289 fd_set *readset, fd_set *writeset)
2292 struct sockaddr_storage addr;
2298 if (!FD_ISSET(c->sock, readset))
2301 debug("multiplexing control connection");
2304 * Accept connection on control socket
2306 memset(&addr, 0, sizeof(addr));
2307 addrlen = sizeof(addr);
2308 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2310 error("%s accept: %s", __func__, strerror(errno));
2311 if (errno == EMFILE || errno == ENFILE)
2312 c->notbefore = monotime() + 1;
2316 if (getpeereid(newsock, &euid, &egid) < 0) {
2317 error("%s getpeereid failed: %s", __func__,
2322 if ((euid != 0) && (getuid() != euid)) {
2323 error("multiplex uid mismatch: peer euid %u != uid %u",
2324 (u_int)euid, (u_int)getuid());
2328 nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2329 newsock, newsock, -1, c->local_window_max,
2330 c->local_maxpacket, 0, "mux-control", 1);
2331 nc->mux_rcb = c->mux_rcb;
2332 debug3("%s: new mux channel %d fd %d", __func__, nc->self, nc->sock);
2333 /* establish state */
2334 nc->mux_rcb(ssh, nc);
2335 /* mux state transitions must not elicit protocol messages */
2336 nc->flags |= CHAN_LOCAL;
2340 channel_handler_init(struct ssh_channels *sc)
2342 chan_fn **pre, **post;
2344 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2345 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2346 fatal("%s: allocation failed", __func__);
2348 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2349 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2350 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2351 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2352 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2353 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2354 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2355 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2356 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2357 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2358 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2359 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2360 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2362 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2363 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2364 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2365 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2366 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2367 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2368 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2369 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2370 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2371 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2372 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2373 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2375 sc->channel_pre = pre;
2376 sc->channel_post = post;
2379 /* gc dead channels */
2381 channel_garbage_collect(struct ssh *ssh, Channel *c)
2385 if (c->detach_user != NULL) {
2386 if (!chan_is_dead(ssh, c, c->detach_close))
2389 debug2("channel %d: gc: notify user", c->self);
2390 c->detach_user(ssh, c->self, NULL);
2391 /* if we still have a callback */
2392 if (c->detach_user != NULL)
2394 debug2("channel %d: gc: user detached", c->self);
2396 if (!chan_is_dead(ssh, c, 1))
2398 debug2("channel %d: garbage collecting", c->self);
2399 channel_free(ssh, c);
2402 enum channel_table { CHAN_PRE, CHAN_POST };
2405 channel_handler(struct ssh *ssh, int table,
2406 fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2408 struct ssh_channels *sc = ssh->chanctxt;
2409 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2415 if (unpause_secs != NULL)
2417 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2418 c = sc->channels[i];
2422 if (table == CHAN_PRE)
2427 if (ftab[c->type] != NULL) {
2429 * Run handlers that are not paused.
2431 if (c->notbefore <= now)
2432 (*ftab[c->type])(ssh, c, readset, writeset);
2433 else if (unpause_secs != NULL) {
2435 * Collect the time that the earliest
2436 * channel comes off pause.
2438 debug3("%s: chan %d: skip for %d more seconds",
2440 (int)(c->notbefore - now));
2441 if (*unpause_secs == 0 ||
2442 (c->notbefore - now) < *unpause_secs)
2443 *unpause_secs = c->notbefore - now;
2446 channel_garbage_collect(ssh, c);
2448 if (unpause_secs != NULL && *unpause_secs != 0)
2449 debug3("%s: first channel unpauses in %d seconds",
2450 __func__, (int)*unpause_secs);
2454 * Create sockets before allocating the select bitmasks.
2455 * This is necessary for things that need to happen after reading
2456 * the network-input but before channel_prepare_select().
2459 channel_before_prepare_select(struct ssh *ssh)
2461 struct ssh_channels *sc = ssh->chanctxt;
2465 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2466 c = sc->channels[i];
2469 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2470 channel_before_prepare_select_rdynamic(ssh, c);
2475 * Allocate/update select bitmasks and add any bits relevant to channels in
2479 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2480 int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2482 u_int n, sz, nfdset;
2484 channel_before_prepare_select(ssh); /* might update channel_max_fd */
2486 n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2488 nfdset = howmany(n+1, NFDBITS);
2489 /* Explicitly test here, because xrealloc isn't always called */
2490 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2491 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2492 sz = nfdset * sizeof(fd_mask);
2494 /* perhaps check sz < nalloc/2 and shrink? */
2495 if (*readsetp == NULL || sz > *nallocp) {
2496 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2497 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2501 memset(*readsetp, 0, sz);
2502 memset(*writesetp, 0, sz);
2504 if (!ssh_packet_is_rekeying(ssh))
2505 channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2510 * After select, perform any appropriate operations for channels which have
2514 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2516 channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2520 * Enqueue data for channels with open or draining c->input.
2523 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2529 if ((len = sshbuf_len(c->input)) == 0) {
2530 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2532 * input-buffer is empty and read-socket shutdown:
2533 * tell peer, that we will not send more data:
2535 * hack for extended data: delay EOF if EFD still
2538 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2539 debug2("channel %d: "
2540 "ibuf_empty delayed efd %d/(%zu)",
2541 c->self, c->efd, sshbuf_len(c->extended));
2543 chan_ibuf_empty(ssh, c);
2548 if (!c->have_remote_id)
2549 fatal(":%s: channel %d: no remote id", __func__, c->self);
2552 /* Check datagram will fit; drop if not */
2553 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2554 fatal("%s: channel %d: get datagram: %s", __func__,
2555 c->self, ssh_err(r));
2557 * XXX this does tail-drop on the datagram queue which is
2558 * usually suboptimal compared to head-drop. Better to have
2559 * backpressure at read time? (i.e. read + discard)
2561 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2562 debug("channel %d: datagram too big", c->self);
2566 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2567 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2568 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2569 (r = sshpkt_send(ssh)) != 0) {
2570 fatal("%s: channel %i: datagram: %s", __func__,
2571 c->self, ssh_err(r));
2573 c->remote_window -= plen;
2577 /* Enqueue packet for buffered data. */
2578 if (len > c->remote_window)
2579 len = c->remote_window;
2580 if (len > c->remote_maxpacket)
2581 len = c->remote_maxpacket;
2584 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2585 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2586 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2587 (r = sshpkt_send(ssh)) != 0) {
2588 fatal("%s: channel %i: data: %s", __func__,
2589 c->self, ssh_err(r));
2591 if ((r = sshbuf_consume(c->input, len)) != 0)
2592 fatal("%s: channel %i: consume: %s", __func__,
2593 c->self, ssh_err(r));
2594 c->remote_window -= len;
2598 * Enqueue data for channels with open c->extended in read mode.
2601 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2606 if ((len = sshbuf_len(c->extended)) == 0)
2609 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2610 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2611 if (len > c->remote_window)
2612 len = c->remote_window;
2613 if (len > c->remote_maxpacket)
2614 len = c->remote_maxpacket;
2617 if (!c->have_remote_id)
2618 fatal(":%s: channel %d: no remote id", __func__, c->self);
2619 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2620 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2621 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2622 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2623 (r = sshpkt_send(ssh)) != 0) {
2624 fatal("%s: channel %i: data: %s", __func__,
2625 c->self, ssh_err(r));
2627 if ((r = sshbuf_consume(c->extended, len)) != 0)
2628 fatal("%s: channel %i: consume: %s", __func__,
2629 c->self, ssh_err(r));
2630 c->remote_window -= len;
2631 debug2("channel %d: sent ext data %zu", c->self, len);
2634 /* If there is data to send to the connection, enqueue some of it now. */
2636 channel_output_poll(struct ssh *ssh)
2638 struct ssh_channels *sc = ssh->chanctxt;
2642 for (i = 0; i < sc->channels_alloc; i++) {
2643 c = sc->channels[i];
2648 * We are only interested in channels that can have buffered
2651 if (c->type != SSH_CHANNEL_OPEN)
2653 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2654 /* XXX is this true? */
2655 debug3("channel %d: will not send data after close",
2660 /* Get the amount of buffered data for this channel. */
2661 if (c->istate == CHAN_INPUT_OPEN ||
2662 c->istate == CHAN_INPUT_WAIT_DRAIN)
2663 channel_output_poll_input_open(ssh, c);
2664 /* Send extended data, i.e. stderr */
2665 if (!(c->flags & CHAN_EOF_SENT) &&
2666 c->extended_usage == CHAN_EXTENDED_READ)
2667 channel_output_poll_extended_read(ssh, c);
2671 /* -- mux proxy support */
2674 * When multiplexing channel messages for mux clients we have to deal
2675 * with downstream messages from the mux client and upstream messages
2676 * from the ssh server:
2677 * 1) Handling downstream messages is straightforward and happens
2678 * in channel_proxy_downstream():
2679 * - We forward all messages (mostly) unmodified to the server.
2680 * - However, in order to route messages from upstream to the correct
2681 * downstream client, we have to replace the channel IDs used by the
2682 * mux clients with a unique channel ID because the mux clients might
2683 * use conflicting channel IDs.
2684 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2685 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2686 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2687 * with the newly allocated channel ID.
2688 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2689 * channels and processed by channel_proxy_upstream(). The local channel ID
2690 * is then translated back to the original mux client ID.
2691 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2692 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2693 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2694 * downstream mux client are removed.
2695 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2696 * requires more work, because they are not addressed to a specific
2697 * channel. E.g. client_request_forwarded_tcpip() needs to figure
2698 * out whether the request is addressed to the local client or a
2699 * specific downstream client based on the listen-address/port.
2700 * 6) Agent and X11-Forwarding have a similar problem and are currently
2701 * not supported as the matching session/channel cannot be identified
2706 * receive packets from downstream mux clients:
2707 * channel callback fired on read from mux client, creates
2708 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2709 * on channel creation.
2712 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2715 struct sshbuf *original = NULL, *modified = NULL;
2717 char *ctype = NULL, *listen_host = NULL;
2721 u_int id, remote_id, listen_port;
2723 /* sshbuf_dump(downstream->input, stderr); */
2724 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2726 error("%s: malformed message: %s", __func__, ssh_err(r));
2730 error("%s: short message", __func__);
2734 /* skip padlen + type */
2737 if (ssh_packet_log_type(type))
2738 debug3("%s: channel %u: down->up: type %u", __func__,
2739 downstream->self, type);
2742 case SSH2_MSG_CHANNEL_OPEN:
2743 if ((original = sshbuf_from(cp, have)) == NULL ||
2744 (modified = sshbuf_new()) == NULL) {
2745 error("%s: alloc", __func__);
2748 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2749 (r = sshbuf_get_u32(original, &id)) != 0) {
2750 error("%s: parse error %s", __func__, ssh_err(r));
2753 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2754 -1, -1, -1, 0, 0, 0, ctype, 1);
2755 c->mux_ctx = downstream; /* point to mux client */
2756 c->mux_downstream_id = id; /* original downstream id */
2757 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2758 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2759 (r = sshbuf_putb(modified, original)) != 0) {
2760 error("%s: compose error %s", __func__, ssh_err(r));
2761 channel_free(ssh, c);
2765 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2767 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2768 * need to parse 'remote_id' instead of 'ctype'.
2770 if ((original = sshbuf_from(cp, have)) == NULL ||
2771 (modified = sshbuf_new()) == NULL) {
2772 error("%s: alloc", __func__);
2775 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2776 (r = sshbuf_get_u32(original, &id)) != 0) {
2777 error("%s: parse error %s", __func__, ssh_err(r));
2780 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2781 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2782 c->mux_ctx = downstream; /* point to mux client */
2783 c->mux_downstream_id = id;
2784 c->remote_id = remote_id;
2785 c->have_remote_id = 1;
2786 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2787 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2788 (r = sshbuf_putb(modified, original)) != 0) {
2789 error("%s: compose error %s", __func__, ssh_err(r));
2790 channel_free(ssh, c);
2794 case SSH2_MSG_GLOBAL_REQUEST:
2795 if ((original = sshbuf_from(cp, have)) == NULL) {
2796 error("%s: alloc", __func__);
2799 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2800 error("%s: parse error %s", __func__, ssh_err(r));
2803 if (strcmp(ctype, "tcpip-forward") != 0) {
2804 error("%s: unsupported request %s", __func__, ctype);
2807 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2808 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2809 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2810 error("%s: parse error %s", __func__, ssh_err(r));
2813 if (listen_port > 65535) {
2814 error("%s: tcpip-forward for %s: bad port %u",
2815 __func__, listen_host, listen_port);
2818 /* Record that connection to this host/port is permitted. */
2819 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
2820 listen_host, NULL, (int)listen_port, downstream);
2823 case SSH2_MSG_CHANNEL_CLOSE:
2826 remote_id = PEEK_U32(cp);
2827 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2828 if (c->flags & CHAN_CLOSE_RCVD)
2829 channel_free(ssh, c);
2831 c->flags |= CHAN_CLOSE_SENT;
2836 if ((r = sshpkt_start(ssh, type)) != 0 ||
2837 (r = sshpkt_putb(ssh, modified)) != 0 ||
2838 (r = sshpkt_send(ssh)) != 0) {
2839 error("%s: send %s", __func__, ssh_err(r));
2843 if ((r = sshpkt_start(ssh, type)) != 0 ||
2844 (r = sshpkt_put(ssh, cp, have)) != 0 ||
2845 (r = sshpkt_send(ssh)) != 0) {
2846 error("%s: send %s", __func__, ssh_err(r));
2854 sshbuf_free(original);
2855 sshbuf_free(modified);
2860 * receive packets from upstream server and de-multiplex packets
2861 * to correct downstream:
2862 * implemented as a helper for channel input handlers,
2863 * replaces local (proxy) channel ID with downstream channel ID.
2866 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2868 struct sshbuf *b = NULL;
2869 Channel *downstream;
2870 const u_char *cp = NULL;
2875 * When receiving packets from the peer we need to check whether we
2876 * need to forward the packets to the mux client. In this case we
2877 * restore the original channel id and keep track of CLOSE messages,
2878 * so we can cleanup the channel.
2880 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2882 if ((downstream = c->mux_ctx) == NULL)
2885 case SSH2_MSG_CHANNEL_CLOSE:
2886 case SSH2_MSG_CHANNEL_DATA:
2887 case SSH2_MSG_CHANNEL_EOF:
2888 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
2889 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2890 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
2891 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2892 case SSH2_MSG_CHANNEL_SUCCESS:
2893 case SSH2_MSG_CHANNEL_FAILURE:
2894 case SSH2_MSG_CHANNEL_REQUEST:
2897 debug2("%s: channel %u: unsupported type %u", __func__,
2901 if ((b = sshbuf_new()) == NULL) {
2902 error("%s: alloc reply", __func__);
2905 /* get remaining payload (after id) */
2906 cp = sshpkt_ptr(ssh, &len);
2908 error("%s: no packet", __func__);
2911 /* translate id and send to muxclient */
2912 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
2913 (r = sshbuf_put_u8(b, type)) != 0 ||
2914 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
2915 (r = sshbuf_put(b, cp, len)) != 0 ||
2916 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
2917 error("%s: compose for muxclient %s", __func__, ssh_err(r));
2920 /* sshbuf_dump(b, stderr); */
2921 if (ssh_packet_log_type(type))
2922 debug3("%s: channel %u: up->down: type %u", __func__, c->self,
2927 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2928 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
2929 if (cp && len > 4) {
2930 c->remote_id = PEEK_U32(cp);
2931 c->have_remote_id = 1;
2934 case SSH2_MSG_CHANNEL_CLOSE:
2935 if (c->flags & CHAN_CLOSE_SENT)
2936 channel_free(ssh, c);
2938 c->flags |= CHAN_CLOSE_RCVD;
2945 /* -- protocol input */
2947 /* Parse a channel ID from the current packet */
2949 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
2954 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
2955 error("%s: parse id: %s", where, ssh_err(r));
2956 ssh_packet_disconnect(ssh, "Invalid %s message", what);
2959 error("%s: bad channel id %u: %s", where, id, ssh_err(r));
2960 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
2965 /* Lookup a channel from an ID in the current packet */
2967 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
2969 int id = channel_parse_id(ssh, where, what);
2972 if ((c = channel_lookup(ssh, id)) == NULL) {
2973 ssh_packet_disconnect(ssh,
2974 "%s packet referred to nonexistent channel %d", what, id);
2980 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
2983 size_t data_len, win_len;
2984 Channel *c = channel_from_packet_id(ssh, __func__, "data");
2987 if (channel_proxy_upstream(c, type, seq, ssh))
2990 /* Ignore any data for non-open channels (might happen on close) */
2991 if (c->type != SSH_CHANNEL_OPEN &&
2992 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
2993 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
2994 c->type != SSH_CHANNEL_X11_OPEN)
2998 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0)
2999 fatal("%s: channel %d: get data: %s", __func__,
3000 c->self, ssh_err(r));
3001 ssh_packet_check_eom(ssh);
3005 win_len += 4; /* string length header */
3008 * The sending side reduces its window as it sends data, so we
3009 * must 'fake' consumption of the data in order to ensure that window
3010 * updates are sent back. Otherwise the connection might deadlock.
3012 if (c->ostate != CHAN_OUTPUT_OPEN) {
3013 c->local_window -= win_len;
3014 c->local_consumed += win_len;
3018 if (win_len > c->local_maxpacket) {
3019 logit("channel %d: rcvd big packet %zu, maxpack %u",
3020 c->self, win_len, c->local_maxpacket);
3023 if (win_len > c->local_window) {
3024 logit("channel %d: rcvd too much data %zu, win %u",
3025 c->self, win_len, c->local_window);
3028 c->local_window -= win_len;
3031 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3032 fatal("%s: channel %d: append datagram: %s",
3033 __func__, c->self, ssh_err(r));
3034 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3035 fatal("%s: channel %d: append data: %s",
3036 __func__, c->self, ssh_err(r));
3042 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3047 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3050 if (channel_proxy_upstream(c, type, seq, ssh))
3052 if (c->type != SSH_CHANNEL_OPEN) {
3053 logit("channel %d: ext data for non open", c->self);
3056 if (c->flags & CHAN_EOF_RCVD) {
3057 if (datafellows & SSH_BUG_EXTEOF)
3058 debug("channel %d: accepting ext data after eof",
3061 ssh_packet_disconnect(ssh, "Received extended_data "
3062 "after EOF on channel %d.", c->self);
3065 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3066 error("%s: parse tcode: %s", __func__, ssh_err(r));
3067 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3070 c->extended_usage != CHAN_EXTENDED_WRITE ||
3071 tcode != SSH2_EXTENDED_DATA_STDERR) {
3072 logit("channel %d: bad ext data", c->self);
3075 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0) {
3076 error("%s: parse data: %s", __func__, ssh_err(r));
3077 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3079 ssh_packet_check_eom(ssh);
3081 if (data_len > c->local_window) {
3082 logit("channel %d: rcvd too much extended_data %zu, win %u",
3083 c->self, data_len, c->local_window);
3086 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3087 /* XXX sshpkt_getb? */
3088 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3089 error("%s: append: %s", __func__, ssh_err(r));
3090 c->local_window -= data_len;
3095 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3097 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3099 ssh_packet_check_eom(ssh);
3101 if (channel_proxy_upstream(c, type, seq, ssh))
3103 chan_rcvd_ieof(ssh, c);
3105 /* XXX force input close */
3106 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3107 debug("channel %d: FORCE input drain", c->self);
3108 c->istate = CHAN_INPUT_WAIT_DRAIN;
3109 if (sshbuf_len(c->input) == 0)
3110 chan_ibuf_empty(ssh, c);
3116 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3118 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3120 if (channel_proxy_upstream(c, type, seq, ssh))
3122 ssh_packet_check_eom(ssh);
3123 chan_rcvd_oclose(ssh, c);
3128 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3130 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3131 u_int32_t remote_window, remote_maxpacket;
3134 if (channel_proxy_upstream(c, type, seq, ssh))
3136 if (c->type != SSH_CHANNEL_OPENING)
3137 packet_disconnect("Received open confirmation for "
3138 "non-opening channel %d.", c->self);
3140 * Record the remote channel number and mark that the channel
3143 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3144 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3145 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0) {
3146 error("%s: window/maxpacket: %s", __func__, ssh_err(r));
3147 packet_disconnect("Invalid open confirmation message");
3149 ssh_packet_check_eom(ssh);
3151 c->have_remote_id = 1;
3152 c->remote_window = remote_window;
3153 c->remote_maxpacket = remote_maxpacket;
3154 c->type = SSH_CHANNEL_OPEN;
3155 if (c->open_confirm) {
3156 debug2("%s: channel %d: callback start", __func__, c->self);
3157 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3158 debug2("%s: channel %d: callback done", __func__, c->self);
3160 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3161 c->remote_window, c->remote_maxpacket);
3166 reason2txt(int reason)
3169 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3170 return "administratively prohibited";
3171 case SSH2_OPEN_CONNECT_FAILED:
3172 return "connect failed";
3173 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3174 return "unknown channel type";
3175 case SSH2_OPEN_RESOURCE_SHORTAGE:
3176 return "resource shortage";
3178 return "unknown reason";
3182 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3184 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3189 if (channel_proxy_upstream(c, type, seq, ssh))
3191 if (c->type != SSH_CHANNEL_OPENING)
3192 packet_disconnect("Received open failure for "
3193 "non-opening channel %d.", c->self);
3194 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3195 error("%s: reason: %s", __func__, ssh_err(r));
3196 packet_disconnect("Invalid open failure message");
3199 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3200 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0) {
3201 error("%s: message/lang: %s", __func__, ssh_err(r));
3202 packet_disconnect("Invalid open failure message");
3204 ssh_packet_check_eom(ssh);
3205 logit("channel %d: open failed: %s%s%s", c->self,
3206 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3208 if (c->open_confirm) {
3209 debug2("%s: channel %d: callback start", __func__, c->self);
3210 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3211 debug2("%s: channel %d: callback done", __func__, c->self);
3213 /* Schedule the channel for cleanup/deletion. */
3214 chan_mark_dead(ssh, c);
3219 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3221 int id = channel_parse_id(ssh, __func__, "window adjust");
3227 if ((c = channel_lookup(ssh, id)) == NULL) {
3228 logit("Received window adjust for non-open channel %d.", id);
3232 if (channel_proxy_upstream(c, type, seq, ssh))
3234 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0) {
3235 error("%s: adjust: %s", __func__, ssh_err(r));
3236 packet_disconnect("Invalid window adjust message");
3238 ssh_packet_check_eom(ssh);
3239 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3240 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3241 fatal("channel %d: adjust %u overflows remote window %u",
3242 c->self, adjust, c->remote_window);
3244 c->remote_window = new_rwin;
3249 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3251 int id = channel_parse_id(ssh, __func__, "status confirm");
3253 struct channel_confirm *cc;
3255 /* Reset keepalive timeout */
3256 packet_set_alive_timeouts(0);
3258 debug2("%s: type %d id %d", __func__, type, id);
3260 if ((c = channel_lookup(ssh, id)) == NULL) {
3261 logit("%s: %d: unknown", __func__, id);
3264 if (channel_proxy_upstream(c, type, seq, ssh))
3266 ssh_packet_check_eom(ssh);
3267 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3269 cc->cb(ssh, type, c, cc->ctx);
3270 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3271 explicit_bzero(cc, sizeof(*cc));
3276 /* -- tcp forwarding */
3279 channel_set_af(struct ssh *ssh, int af)
3281 ssh->chanctxt->IPv4or6 = af;
3286 * Determine whether or not a port forward listens to loopback, the
3287 * specified address or wildcard. On the client, a specified bind
3288 * address will always override gateway_ports. On the server, a
3289 * gateway_ports of 1 (``yes'') will override the client's specification
3290 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3291 * will bind to whatever address the client asked for.
3293 * Special-case listen_addrs are:
3295 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3296 * "" (empty string), "*" -> wildcard v4/v6
3297 * "localhost" -> loopback v4/v6
3298 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3301 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
3302 int is_client, struct ForwardOptions *fwd_opts)
3304 const char *addr = NULL;
3307 if (listen_addr == NULL) {
3308 /* No address specified: default to gateway_ports setting */
3309 if (fwd_opts->gateway_ports)
3311 } else if (fwd_opts->gateway_ports || is_client) {
3312 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
3313 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3314 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3315 (!is_client && fwd_opts->gateway_ports == 1)) {
3318 * Notify client if they requested a specific listen
3319 * address and it was overridden.
3321 if (*listen_addr != '\0' &&
3322 strcmp(listen_addr, "0.0.0.0") != 0 &&
3323 strcmp(listen_addr, "*") != 0) {
3324 packet_send_debug("Forwarding listen address "
3325 "\"%s\" overridden by server "
3326 "GatewayPorts", listen_addr);
3328 } else if (strcmp(listen_addr, "localhost") != 0 ||
3329 strcmp(listen_addr, "127.0.0.1") == 0 ||
3330 strcmp(listen_addr, "::1") == 0) {
3331 /* Accept localhost address when GatewayPorts=yes */
3334 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3335 strcmp(listen_addr, "::1") == 0) {
3337 * If a specific IPv4/IPv6 localhost address has been
3338 * requested then accept it even if gateway_ports is in
3339 * effect. This allows the client to prefer IPv4 or IPv6.
3343 if (wildcardp != NULL)
3344 *wildcardp = wildcard;
3349 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3350 struct Forward *fwd, int *allocated_listen_port,
3351 struct ForwardOptions *fwd_opts)
3354 int sock, r, success = 0, wildcard = 0, is_client;
3355 struct addrinfo hints, *ai, *aitop;
3356 const char *host, *addr;
3357 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3360 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3362 if (is_client && fwd->connect_path != NULL) {
3363 host = fwd->connect_path;
3365 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3366 fwd->listen_host : fwd->connect_host;
3368 error("No forward host name.");
3371 if (strlen(host) >= NI_MAXHOST) {
3372 error("Forward host name too long.");
3377 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3378 addr = channel_fwd_bind_addr(fwd->listen_host, &wildcard,
3379 is_client, fwd_opts);
3380 debug3("%s: type %d wildcard %d addr %s", __func__,
3381 type, wildcard, (addr == NULL) ? "NULL" : addr);
3384 * getaddrinfo returns a loopback address if the hostname is
3385 * set to NULL and hints.ai_flags is not AI_PASSIVE
3387 memset(&hints, 0, sizeof(hints));
3388 hints.ai_family = ssh->chanctxt->IPv4or6;
3389 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3390 hints.ai_socktype = SOCK_STREAM;
3391 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3392 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3394 /* This really shouldn't happen */
3395 packet_disconnect("getaddrinfo: fatal error: %s",
3396 ssh_gai_strerror(r));
3398 error("%s: getaddrinfo(%.64s): %s", __func__, addr,
3399 ssh_gai_strerror(r));
3403 if (allocated_listen_port != NULL)
3404 *allocated_listen_port = 0;
3405 for (ai = aitop; ai; ai = ai->ai_next) {
3406 switch (ai->ai_family) {
3408 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3412 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3419 * If allocating a port for -R forwards, then use the
3420 * same port for all address families.
3422 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3423 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3424 *allocated_listen_port > 0)
3425 *lport_p = htons(*allocated_listen_port);
3427 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3428 strport, sizeof(strport),
3429 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3430 error("%s: getnameinfo failed", __func__);
3433 /* Create a port to listen for the host. */
3434 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3436 /* this is no error since kernel may not support ipv6 */
3437 verbose("socket [%s]:%s: %.100s", ntop, strport,
3442 set_reuseaddr(sock);
3443 if (ai->ai_family == AF_INET6)
3444 sock_set_v6only(sock);
3446 debug("Local forwarding listening on %s port %s.",
3449 /* Bind the socket to the address. */
3450 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3452 * address can be in if use ipv6 address is
3456 error("bind [%s]:%s: %.100s",
3457 ntop, strport, strerror(errno));
3459 verbose("bind [%s]:%s: %.100s",
3460 ntop, strport, strerror(errno));
3465 /* Start listening for connections on the socket. */
3466 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3467 error("listen: %.100s", strerror(errno));
3468 error("listen [%s]:%s: %.100s", ntop, strport,
3475 * fwd->listen_port == 0 requests a dynamically allocated port -
3476 * record what we got.
3478 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3479 fwd->listen_port == 0 &&
3480 allocated_listen_port != NULL &&
3481 *allocated_listen_port == 0) {
3482 *allocated_listen_port = get_local_port(sock);
3483 debug("Allocated listen port %d",
3484 *allocated_listen_port);
3487 /* Allocate a channel number for the socket. */
3488 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3489 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3490 0, "port listener", 1);
3491 c->path = xstrdup(host);
3492 c->host_port = fwd->connect_port;
3493 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3494 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3495 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
3496 c->listening_port = *allocated_listen_port;
3498 c->listening_port = fwd->listen_port;
3502 error("%s: cannot listen to port: %d", __func__,
3504 freeaddrinfo(aitop);
3509 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3510 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3512 struct sockaddr_un sunaddr;
3519 case SSH_CHANNEL_UNIX_LISTENER:
3520 if (fwd->connect_path != NULL) {
3521 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3522 error("Local connecting path too long: %s",
3526 path = fwd->connect_path;
3527 port = PORT_STREAMLOCAL;
3529 if (fwd->connect_host == NULL) {
3530 error("No forward host name.");
3533 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3534 error("Forward host name too long.");
3537 path = fwd->connect_host;
3538 port = fwd->connect_port;
3541 case SSH_CHANNEL_RUNIX_LISTENER:
3542 path = fwd->listen_path;
3543 port = PORT_STREAMLOCAL;
3546 error("%s: unexpected channel type %d", __func__, type);
3550 if (fwd->listen_path == NULL) {
3551 error("No forward path name.");
3554 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3555 error("Local listening path too long: %s", fwd->listen_path);
3559 debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
3561 /* Start a Unix domain listener. */
3562 omask = umask(fwd_opts->streamlocal_bind_mask);
3563 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3564 fwd_opts->streamlocal_bind_unlink);
3569 debug("Local forwarding listening on path %s.", fwd->listen_path);
3571 /* Allocate a channel number for the socket. */
3572 c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3573 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3574 0, "unix listener", 1);
3575 c->path = xstrdup(path);
3576 c->host_port = port;
3577 c->listening_port = PORT_STREAMLOCAL;
3578 c->listening_addr = xstrdup(fwd->listen_path);
3583 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3584 const char *host, u_short port)
3589 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3590 Channel *c = ssh->chanctxt->channels[i];
3591 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3593 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3594 debug2("%s: close channel %d", __func__, i);
3595 channel_free(ssh, c);
3604 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3609 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3610 Channel *c = ssh->chanctxt->channels[i];
3611 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3613 if (c->path == NULL)
3615 if (strcmp(c->path, path) == 0) {
3616 debug2("%s: close channel %d", __func__, i);
3617 channel_free(ssh, c);
3626 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3628 if (fwd->listen_path != NULL) {
3629 return channel_cancel_rport_listener_streamlocal(ssh,
3632 return channel_cancel_rport_listener_tcpip(ssh,
3633 fwd->listen_host, fwd->listen_port);
3638 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3639 const char *lhost, u_short lport, int cport,
3640 struct ForwardOptions *fwd_opts)
3644 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, fwd_opts);
3646 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3647 Channel *c = ssh->chanctxt->channels[i];
3648 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3650 if (c->listening_port != lport)
3652 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3653 /* skip dynamic forwardings */
3654 if (c->host_port == 0)
3657 if (c->host_port != cport)
3660 if ((c->listening_addr == NULL && addr != NULL) ||
3661 (c->listening_addr != NULL && addr == NULL))
3663 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3664 debug2("%s: close channel %d", __func__, i);
3665 channel_free(ssh, c);
3674 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3680 error("%s: no path specified.", __func__);
3684 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3685 Channel *c = ssh->chanctxt->channels[i];
3686 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3688 if (c->listening_addr == NULL)
3690 if (strcmp(c->listening_addr, path) == 0) {
3691 debug2("%s: close channel %d", __func__, i);
3692 channel_free(ssh, c);
3701 channel_cancel_lport_listener(struct ssh *ssh,
3702 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3704 if (fwd->listen_path != NULL) {
3705 return channel_cancel_lport_listener_streamlocal(ssh,
3708 return channel_cancel_lport_listener_tcpip(ssh,
3709 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3713 /* protocol local port fwd, used by ssh */
3715 channel_setup_local_fwd_listener(struct ssh *ssh,
3716 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3718 if (fwd->listen_path != NULL) {
3719 return channel_setup_fwd_listener_streamlocal(ssh,
3720 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3722 return channel_setup_fwd_listener_tcpip(ssh,
3723 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3727 /* Matches a remote forwarding permission against a requested forwarding */
3729 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3734 /* XXX add ACLs for streamlocal */
3735 if (fwd->listen_path != NULL)
3738 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3741 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3742 allowed_open->listen_port != fwd->listen_port)
3745 /* Match hostnames case-insensitively */
3746 lhost = xstrdup(fwd->listen_host);
3748 ret = match_pattern(lhost, allowed_open->listen_host);
3754 /* Checks whether a requested remote forwarding is permitted */
3756 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3758 struct ssh_channels *sc = ssh->chanctxt;
3759 struct permission_set *pset = &sc->remote_perms;
3760 u_int i, permit, permit_adm = 1;
3761 struct permission *perm;
3763 /* XXX apply GatewayPorts override before checking? */
3765 permit = pset->all_permitted;
3767 for (i = 0; i < pset->num_permitted_user; i++) {
3768 perm = &pset->permitted_user[i];
3769 if (remote_open_match(perm, fwd)) {
3776 if (pset->num_permitted_admin > 0) {
3778 for (i = 0; i < pset->num_permitted_admin; i++) {
3779 perm = &pset->permitted_admin[i];
3780 if (remote_open_match(perm, fwd)) {
3787 return permit && permit_adm;
3790 /* protocol v2 remote port fwd, used by sshd */
3792 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
3793 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3795 if (!check_rfwd_permission(ssh, fwd)) {
3796 packet_send_debug("port forwarding refused");
3799 if (fwd->listen_path != NULL) {
3800 return channel_setup_fwd_listener_streamlocal(ssh,
3801 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3803 return channel_setup_fwd_listener_tcpip(ssh,
3804 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3810 * Translate the requested rfwd listen host to something usable for
3814 channel_rfwd_bind_host(const char *listen_host)
3816 if (listen_host == NULL) {
3818 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3825 * Initiate forwarding of connections to port "port" on remote host through
3826 * the secure channel to host:port from local side.
3827 * Returns handle (index) for updating the dynamic listen port with
3828 * channel_update_permission().
3831 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
3833 int r, success = 0, idx = -1;
3834 char *host_to_connect, *listen_host, *listen_path;
3835 int port_to_connect, listen_port;
3837 /* Send the forward request to the remote side. */
3838 if (fwd->listen_path != NULL) {
3839 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3840 (r = sshpkt_put_cstring(ssh,
3841 "streamlocal-forward@openssh.com")) != 0 ||
3842 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3843 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
3844 (r = sshpkt_send(ssh)) != 0 ||
3845 (r = ssh_packet_write_wait(ssh)) != 0)
3846 fatal("%s: request streamlocal: %s",
3847 __func__, ssh_err(r));
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("%s: request tcpip-forward: %s",
3858 __func__, ssh_err(r));
3860 /* Assume that server accepts the request */
3863 /* Record that connection to this host/port is permitted. */
3864 host_to_connect = listen_host = listen_path = NULL;
3865 port_to_connect = listen_port = 0;
3866 if (fwd->connect_path != NULL) {
3867 host_to_connect = xstrdup(fwd->connect_path);
3868 port_to_connect = PORT_STREAMLOCAL;
3870 host_to_connect = xstrdup(fwd->connect_host);
3871 port_to_connect = fwd->connect_port;
3873 if (fwd->listen_path != NULL) {
3874 listen_path = xstrdup(fwd->listen_path);
3875 listen_port = PORT_STREAMLOCAL;
3877 if (fwd->listen_host != NULL)
3878 listen_host = xstrdup(fwd->listen_host);
3879 listen_port = fwd->listen_port;
3881 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
3882 host_to_connect, port_to_connect,
3883 listen_host, listen_path, listen_port, NULL);
3889 open_match(struct permission *allowed_open, const char *requestedhost,
3892 if (allowed_open->host_to_connect == NULL)
3894 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3895 allowed_open->port_to_connect != requestedport)
3897 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3898 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3904 * Note that in the listen host/port case
3905 * we don't support FWD_PERMIT_ANY_PORT and
3906 * need to translate between the configured-host (listen_host)
3907 * and what we've sent to the remote server (channel_rfwd_bind_host)
3910 open_listen_match_tcpip(struct permission *allowed_open,
3911 const char *requestedhost, u_short requestedport, int translate)
3913 const char *allowed_host;
3915 if (allowed_open->host_to_connect == NULL)
3917 if (allowed_open->listen_port != requestedport)
3919 if (!translate && allowed_open->listen_host == NULL &&
3920 requestedhost == NULL)
3922 allowed_host = translate ?
3923 channel_rfwd_bind_host(allowed_open->listen_host) :
3924 allowed_open->listen_host;
3925 if (allowed_host == NULL || requestedhost == NULL ||
3926 strcmp(allowed_host, requestedhost) != 0)
3932 open_listen_match_streamlocal(struct permission *allowed_open,
3933 const char *requestedpath)
3935 if (allowed_open->host_to_connect == NULL)
3937 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3939 if (allowed_open->listen_path == NULL ||
3940 strcmp(allowed_open->listen_path, requestedpath) != 0)
3946 * Request cancellation of remote forwarding of connection host:port from
3950 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
3951 const char *host, u_short port)
3953 struct ssh_channels *sc = ssh->chanctxt;
3954 struct permission_set *pset = &sc->local_perms;
3957 struct permission *perm;
3959 for (i = 0; i < pset->num_permitted_user; i++) {
3960 perm = &pset->permitted_user[i];
3961 if (open_listen_match_tcpip(perm, host, port, 0))
3966 debug("%s: requested forward not found", __func__);
3969 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3970 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
3971 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3972 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
3973 (r = sshpkt_put_u32(ssh, port)) != 0 ||
3974 (r = sshpkt_send(ssh)) != 0)
3975 fatal("%s: send cancel: %s", __func__, ssh_err(r));
3977 fwd_perm_clear(perm); /* unregister */
3983 * Request cancellation of remote forwarding of Unix domain socket
3984 * path from local side.
3987 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
3989 struct ssh_channels *sc = ssh->chanctxt;
3990 struct permission_set *pset = &sc->local_perms;
3993 struct permission *perm;
3995 for (i = 0; i < pset->num_permitted_user; i++) {
3996 perm = &pset->permitted_user[i];
3997 if (open_listen_match_streamlocal(perm, path))
4002 debug("%s: requested forward not found", __func__);
4005 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4006 (r = sshpkt_put_cstring(ssh,
4007 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4008 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4009 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4010 (r = sshpkt_send(ssh)) != 0)
4011 fatal("%s: send cancel: %s", __func__, ssh_err(r));
4013 fwd_perm_clear(perm); /* unregister */
4019 * Request cancellation of remote forwarding of a connection from local side.
4022 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4024 if (fwd->listen_path != NULL) {
4025 return channel_request_rforward_cancel_streamlocal(ssh,
4028 return channel_request_rforward_cancel_tcpip(ssh,
4030 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4035 * Permits opening to any host/port if permitted_user[] is empty. This is
4036 * usually called by the server, because the user could connect to any port
4037 * anyway, and the server has no way to know but to trust the client anyway.
4040 channel_permit_all(struct ssh *ssh, int where)
4042 struct permission_set *pset = permission_set_get(ssh, where);
4044 if (pset->num_permitted_user == 0)
4045 pset->all_permitted = 1;
4049 * Permit the specified host/port for forwarding.
4052 channel_add_permission(struct ssh *ssh, int who, int where,
4053 char *host, int port)
4055 int local = where == FORWARD_LOCAL;
4056 struct permission_set *pset = permission_set_get(ssh, where);
4058 debug("allow %s forwarding to host %s port %d",
4059 fwd_ident(who, where), host, port);
4061 * Remote forwards set listen_host/port, local forwards set
4062 * host/port_to_connect.
4064 permission_set_add(ssh, who, where,
4065 local ? host : 0, local ? port : 0,
4066 local ? NULL : host, NULL, local ? 0 : port, NULL);
4067 pset->all_permitted = 0;
4071 * Administratively disable forwarding.
4074 channel_disable_admin(struct ssh *ssh, int where)
4076 channel_clear_permission(ssh, FORWARD_ADM, where);
4077 permission_set_add(ssh, FORWARD_ADM, where,
4078 NULL, 0, NULL, NULL, 0, NULL);
4082 * Clear a list of permitted opens.
4085 channel_clear_permission(struct ssh *ssh, int who, int where)
4087 struct permission **permp;
4090 permission_set_get_array(ssh, who, where, &permp, &npermp);
4091 *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4096 * Update the listen port for a dynamic remote forward, after
4097 * the actual 'newport' has been allocated. If 'newport' < 0 is
4098 * passed then they entry will be invalidated.
4101 channel_update_permission(struct ssh *ssh, int idx, int newport)
4103 struct permission_set *pset = &ssh->chanctxt->local_perms;
4105 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4106 debug("%s: index out of range: %d num_permitted_user %d",
4107 __func__, idx, pset->num_permitted_user);
4110 debug("%s allowed port %d for forwarding to host %s port %d",
4111 newport > 0 ? "Updating" : "Removing",
4113 pset->permitted_user[idx].host_to_connect,
4114 pset->permitted_user[idx].port_to_connect);
4116 fwd_perm_clear(&pset->permitted_user[idx]);
4118 pset->permitted_user[idx].listen_port =
4119 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4123 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4125 permitopen_port(const char *p)
4129 if (strcmp(p, "*") == 0)
4130 return FWD_PERMIT_ANY_PORT;
4131 if ((port = a2port(p)) > 0)
4136 /* Try to start non-blocking connect to next host in cctx list */
4138 connect_next(struct channel_connect *cctx)
4140 int sock, saved_errno;
4141 struct sockaddr_un *sunaddr;
4142 char ntop[NI_MAXHOST];
4143 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4145 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4146 switch (cctx->ai->ai_family) {
4148 /* unix:pathname instead of host:port */
4149 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4150 strlcpy(ntop, "unix", sizeof(ntop));
4151 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4155 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4156 ntop, sizeof(ntop), strport, sizeof(strport),
4157 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4158 error("connect_next: getnameinfo failed");
4165 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4166 cctx->ai->ai_protocol)) == -1) {
4167 if (cctx->ai->ai_next == NULL)
4168 error("socket: %.100s", strerror(errno));
4170 verbose("socket: %.100s", strerror(errno));
4173 if (set_nonblock(sock) == -1)
4174 fatal("%s: set_nonblock(%d)", __func__, sock);
4175 if (connect(sock, cctx->ai->ai_addr,
4176 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4177 debug("connect_next: host %.100s ([%.100s]:%s): "
4178 "%.100s", cctx->host, ntop, strport,
4180 saved_errno = errno;
4182 errno = saved_errno;
4183 continue; /* fail -- try next */
4185 if (cctx->ai->ai_family != AF_UNIX)
4187 debug("connect_next: host %.100s ([%.100s]:%s) "
4188 "in progress, fd=%d", cctx->host, ntop, strport, sock);
4189 cctx->ai = cctx->ai->ai_next;
4196 channel_connect_ctx_free(struct channel_connect *cctx)
4200 if (cctx->aitop->ai_family == AF_UNIX)
4203 freeaddrinfo(cctx->aitop);
4205 memset(cctx, 0, sizeof(*cctx));
4209 * Return connecting socket to remote host:port or local socket path,
4210 * passing back the failure reason if appropriate.
4213 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4214 char *ctype, char *rname, struct channel_connect *cctx,
4215 int *reason, const char **errmsg)
4217 struct addrinfo hints;
4220 char strport[NI_MAXSERV];
4222 if (port == PORT_STREAMLOCAL) {
4223 struct sockaddr_un *sunaddr;
4224 struct addrinfo *ai;
4226 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4227 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4232 * Fake up a struct addrinfo for AF_UNIX connections.
4233 * channel_connect_ctx_free() must check ai_family
4234 * and use free() not freeaddirinfo() for AF_UNIX.
4236 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4237 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4238 ai->ai_addr = (struct sockaddr *)(ai + 1);
4239 ai->ai_addrlen = sizeof(*sunaddr);
4240 ai->ai_family = AF_UNIX;
4241 ai->ai_socktype = socktype;
4242 ai->ai_protocol = PF_UNSPEC;
4243 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4244 sunaddr->sun_family = AF_UNIX;
4245 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4248 memset(&hints, 0, sizeof(hints));
4249 hints.ai_family = ssh->chanctxt->IPv4or6;
4250 hints.ai_socktype = socktype;
4251 snprintf(strport, sizeof strport, "%d", port);
4252 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4255 *errmsg = ssh_gai_strerror(gaierr);
4257 *reason = SSH2_OPEN_CONNECT_FAILED;
4258 error("connect_to %.100s: unknown host (%s)", name,
4259 ssh_gai_strerror(gaierr));
4264 cctx->host = xstrdup(name);
4266 cctx->ai = cctx->aitop;
4268 if ((sock = connect_next(cctx)) == -1) {
4269 error("connect to %.100s port %d failed: %s",
4270 name, port, strerror(errno));
4277 /* Return CONNECTING channel to remote host:port or local socket path */
4279 connect_to(struct ssh *ssh, const char *host, int port,
4280 char *ctype, char *rname)
4282 struct channel_connect cctx;
4286 memset(&cctx, 0, sizeof(cctx));
4287 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4290 channel_connect_ctx_free(&cctx);
4293 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4294 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4295 c->host_port = port;
4296 c->path = xstrdup(host);
4297 c->connect_ctx = cctx;
4303 * returns either the newly connected channel or the downstream channel
4304 * that needs to deal with this connection.
4307 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4308 u_short listen_port, char *ctype, char *rname)
4310 struct ssh_channels *sc = ssh->chanctxt;
4311 struct permission_set *pset = &sc->local_perms;
4313 struct permission *perm;
4315 for (i = 0; i < pset->num_permitted_user; i++) {
4316 perm = &pset->permitted_user[i];
4317 if (open_listen_match_tcpip(perm,
4318 listen_host, listen_port, 1)) {
4319 if (perm->downstream)
4320 return perm->downstream;
4321 if (perm->port_to_connect == 0)
4322 return rdynamic_connect_prepare(ssh,
4324 return connect_to(ssh,
4325 perm->host_to_connect, perm->port_to_connect,
4329 error("WARNING: Server requests forwarding for unknown listen_port %d",
4335 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4336 char *ctype, char *rname)
4338 struct ssh_channels *sc = ssh->chanctxt;
4339 struct permission_set *pset = &sc->local_perms;
4341 struct permission *perm;
4343 for (i = 0; i < pset->num_permitted_user; i++) {
4344 perm = &pset->permitted_user[i];
4345 if (open_listen_match_streamlocal(perm, path)) {
4346 return connect_to(ssh,
4347 perm->host_to_connect, perm->port_to_connect,
4351 error("WARNING: Server requests forwarding for unknown path %.100s",
4356 /* Check if connecting to that port is permitted and connect. */
4358 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4359 char *ctype, char *rname, int *reason, const char **errmsg)
4361 struct ssh_channels *sc = ssh->chanctxt;
4362 struct permission_set *pset = &sc->local_perms;
4363 struct channel_connect cctx;
4365 u_int i, permit, permit_adm = 1;
4367 struct permission *perm;
4369 permit = pset->all_permitted;
4371 for (i = 0; i < pset->num_permitted_user; i++) {
4372 perm = &pset->permitted_user[i];
4373 if (open_match(perm, host, port)) {
4380 if (pset->num_permitted_admin > 0) {
4382 for (i = 0; i < pset->num_permitted_admin; i++) {
4383 perm = &pset->permitted_admin[i];
4384 if (open_match(perm, host, port)) {
4391 if (!permit || !permit_adm) {
4392 logit("Received request to connect to host %.100s port %d, "
4393 "but the request was denied.", 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) < 0)
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("%s: channel %u: send window-change: %s",
4477 __func__, i, ssh_err(r));
4481 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4483 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4488 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4489 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4494 * We need to open the channel before we have a FD,
4495 * so that we can get SOCKS header from peer.
4497 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4498 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4499 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4500 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4501 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
4502 fatal("%s: channel %i: confirm: %s", __func__,
4503 c->self, ssh_err(r));
4508 /* Return CONNECTING socket to remote host:port or local socket path */
4510 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4512 struct channel_connect cctx;
4515 memset(&cctx, 0, sizeof(cctx));
4516 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4517 NULL, &cctx, NULL, NULL);
4519 channel_connect_ctx_free(&cctx);
4521 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4522 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4523 c->connect_ctx = cctx;
4524 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4529 /* -- X11 forwarding */
4532 * Creates an internet domain socket for listening for X11 connections.
4533 * Returns 0 and a suitable display number for the DISPLAY variable
4534 * stored in display_numberp , or -1 if an error occurs.
4537 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4538 int x11_use_localhost, int single_connection,
4539 u_int *display_numberp, int **chanids)
4542 int display_number, sock;
4544 struct addrinfo hints, *ai, *aitop;
4545 char strport[NI_MAXSERV];
4546 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4548 if (chanids == NULL)
4551 for (display_number = x11_display_offset;
4552 display_number < MAX_DISPLAYS;
4554 port = 6000 + display_number;
4555 memset(&hints, 0, sizeof(hints));
4556 hints.ai_family = ssh->chanctxt->IPv4or6;
4557 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4558 hints.ai_socktype = SOCK_STREAM;
4559 snprintf(strport, sizeof strport, "%d", port);
4560 if ((gaierr = getaddrinfo(NULL, strport,
4561 &hints, &aitop)) != 0) {
4562 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4565 for (ai = aitop; ai; ai = ai->ai_next) {
4566 if (ai->ai_family != AF_INET &&
4567 ai->ai_family != AF_INET6)
4569 sock = socket(ai->ai_family, ai->ai_socktype,
4572 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4574 && (errno != EPFNOSUPPORT)
4577 error("socket: %.100s", strerror(errno));
4578 freeaddrinfo(aitop);
4581 debug("x11_create_display_inet: Socket family %d not supported",
4586 if (ai->ai_family == AF_INET6)
4587 sock_set_v6only(sock);
4588 if (x11_use_localhost)
4589 set_reuseaddr(sock);
4590 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4591 debug2("%s: bind port %d: %.100s", __func__,
4592 port, strerror(errno));
4594 for (n = 0; n < num_socks; n++)
4599 socks[num_socks++] = sock;
4600 if (num_socks == NUM_SOCKS)
4603 freeaddrinfo(aitop);
4607 if (display_number >= MAX_DISPLAYS) {
4608 error("Failed to allocate internet-domain X11 display socket.");
4611 /* Start listening for connections on the socket. */
4612 for (n = 0; n < num_socks; n++) {
4614 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
4615 error("listen: %.100s", strerror(errno));
4621 /* Allocate a channel for each socket. */
4622 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4623 for (n = 0; n < num_socks; n++) {
4625 nc = channel_new(ssh, "x11 listener",
4626 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4627 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4628 0, "X11 inet listener", 1);
4629 nc->single_connection = single_connection;
4630 (*chanids)[n] = nc->self;
4634 /* Return the display number for the DISPLAY environment variable. */
4635 *display_numberp = display_number;
4640 connect_local_xsocket_path(const char *pathname)
4643 struct sockaddr_un addr;
4645 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4647 error("socket: %.100s", strerror(errno));
4648 memset(&addr, 0, sizeof(addr));
4649 addr.sun_family = AF_UNIX;
4650 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4651 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4654 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4659 connect_local_xsocket(u_int dnr)
4662 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4663 return connect_local_xsocket_path(buf);
4668 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4672 if (strlcpy(path, display, pathlen) >= pathlen) {
4673 error("%s: display path too long", __func__);
4676 if (display[0] != '/')
4678 if (stat(path, &sbuf) == 0) {
4681 char *dot = strrchr(path, '.');
4684 if (stat(path, &sbuf) == 0) {
4694 x11_connect_display(struct ssh *ssh)
4696 u_int display_number;
4697 const char *display;
4698 char buf[1024], *cp;
4699 struct addrinfo hints, *ai, *aitop;
4700 char strport[NI_MAXSERV];
4701 int gaierr, sock = 0;
4703 /* Try to open a socket for the local X server. */
4704 display = getenv("DISPLAY");
4706 error("DISPLAY not set.");
4710 * Now we decode the value of the DISPLAY variable and make a
4711 * connection to the real X server.
4715 /* Check if display is a path to a socket (as set by launchd). */
4717 char path[PATH_MAX];
4719 if (is_path_to_xsocket(display, path, sizeof(path))) {
4720 debug("x11_connect_display: $DISPLAY is launchd");
4722 /* Create a socket. */
4723 sock = connect_local_xsocket_path(path);
4727 /* OK, we now have a connection to the display. */
4733 * Check if it is a unix domain socket. Unix domain displays are in
4734 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4736 if (strncmp(display, "unix:", 5) == 0 ||
4737 display[0] == ':') {
4738 /* Connect to the unix domain socket. */
4739 if (sscanf(strrchr(display, ':') + 1, "%u",
4740 &display_number) != 1) {
4741 error("Could not parse display number from DISPLAY: "
4745 /* Create a socket. */
4746 sock = connect_local_xsocket(display_number);
4750 /* OK, we now have a connection to the display. */
4754 * Connect to an inet socket. The DISPLAY value is supposedly
4755 * hostname:d[.s], where hostname may also be numeric IP address.
4757 strlcpy(buf, display, sizeof(buf));
4758 cp = strchr(buf, ':');
4760 error("Could not find ':' in DISPLAY: %.100s", display);
4765 * buf now contains the host name. But first we parse the
4768 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4769 error("Could not parse display number from DISPLAY: %.100s",
4774 /* Look up the host address */
4775 memset(&hints, 0, sizeof(hints));
4776 hints.ai_family = ssh->chanctxt->IPv4or6;
4777 hints.ai_socktype = SOCK_STREAM;
4778 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4779 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4780 error("%.100s: unknown host. (%s)", buf,
4781 ssh_gai_strerror(gaierr));
4784 for (ai = aitop; ai; ai = ai->ai_next) {
4785 /* Create a socket. */
4786 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4788 debug2("socket: %.100s", strerror(errno));
4791 /* Connect it to the display. */
4792 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4793 debug2("connect %.100s port %u: %.100s", buf,
4794 6000 + display_number, strerror(errno));
4801 freeaddrinfo(aitop);
4803 error("connect %.100s port %u: %.100s", buf,
4804 6000 + display_number, strerror(errno));
4812 * Requests forwarding of X11 connections, generates fake authentication
4813 * data, and enables authentication spoofing.
4814 * This should be called in the client only.
4817 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
4818 const char *disp, const char *proto, const char *data, int want_reply)
4820 struct ssh_channels *sc = ssh->chanctxt;
4821 u_int data_len = (u_int) strlen(data) / 2;
4825 int r, screen_number;
4827 if (sc->x11_saved_display == NULL)
4828 sc->x11_saved_display = xstrdup(disp);
4829 else if (strcmp(disp, sc->x11_saved_display) != 0) {
4830 error("x11_request_forwarding_with_spoofing: different "
4831 "$DISPLAY already forwarded");
4835 cp = strchr(disp, ':');
4837 cp = strchr(cp, '.');
4839 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4843 if (sc->x11_saved_proto == NULL) {
4844 /* Save protocol name. */
4845 sc->x11_saved_proto = xstrdup(proto);
4847 /* Extract real authentication data. */
4848 sc->x11_saved_data = xmalloc(data_len);
4849 for (i = 0; i < data_len; i++) {
4850 if (sscanf(data + 2 * i, "%2x", &value) != 1)
4851 fatal("x11_request_forwarding: bad "
4852 "authentication data: %.100s", data);
4853 sc->x11_saved_data[i] = value;
4855 sc->x11_saved_data_len = data_len;
4857 /* Generate fake data of the same length. */
4858 sc->x11_fake_data = xmalloc(data_len);
4859 arc4random_buf(sc->x11_fake_data, data_len);
4860 sc->x11_fake_data_len = data_len;
4863 /* Convert the fake data into hex. */
4864 new_data = tohex(sc->x11_fake_data, data_len);
4866 /* Send the request packet. */
4867 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
4868 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
4869 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
4870 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
4871 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
4872 (r = sshpkt_send(ssh)) != 0 ||
4873 (r = ssh_packet_write_wait(ssh)) != 0)
4874 fatal("%s: send x11-req: %s", __func__, ssh_err(r));