1 /* $OpenBSD: channels.c,v 1.430 2023/03/10 03:01:51 dtucker Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
73 #include "openbsd-compat/sys-queue.h"
87 #include "pathnames.h"
90 /* XXX remove once we're satisfied there's no lurking bugs */
91 /* #define DEBUG_CHANNEL_POLL 1 */
93 /* -- agent forwarding */
96 /* -- tcp forwarding */
97 /* special-case port number meaning allow any port */
98 #define FWD_PERMIT_ANY_PORT 0
100 /* special-case wildcard meaning allow any host */
101 #define FWD_PERMIT_ANY_HOST "*"
103 /* -- X11 forwarding */
104 /* Maximum number of fake X11 displays to try. */
105 #define MAX_DISPLAYS 1000
107 /* Per-channel callback for pre/post IO actions */
108 typedef void chan_fn(struct ssh *, Channel *c);
111 * Data structure for storing which hosts are permitted for forward requests.
112 * The local sides of any remote forwards are stored in this array to prevent
113 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
114 * network (which might be behind a firewall).
116 /* XXX: streamlocal wants a path instead of host:port */
117 /* Overload host_to_connect; we could just make this match Forward */
118 /* XXX - can we use listen_host instead of listen_path? */
120 char *host_to_connect; /* Connect to 'host'. */
121 int port_to_connect; /* Connect to 'port'. */
122 char *listen_host; /* Remote side should listen address. */
123 char *listen_path; /* Remote side should listen path. */
124 int listen_port; /* Remote side should listen port. */
125 Channel *downstream; /* Downstream mux*/
129 * Stores the forwarding permission state for a single direction (local or
132 struct permission_set {
134 * List of all local permitted host/port pairs to allow for the
137 u_int num_permitted_user;
138 struct permission *permitted_user;
141 * List of all permitted host/port pairs to allow for the admin.
143 u_int num_permitted_admin;
144 struct permission *permitted_admin;
147 * If this is true, all opens/listens are permitted. This is the
148 * case on the server on which we have to trust the client anyway,
149 * and the user could do anything after logging in.
154 /* Used to record timeouts per channel type */
155 struct ssh_channel_timeout {
160 /* Master structure for channels state */
161 struct ssh_channels {
163 * Pointer to an array containing all allocated channels. The array
164 * is dynamically extended as needed.
169 * Size of the channel array. All slots of the array must always be
170 * initialized (at least the type field); unused slots set to NULL
172 u_int channels_alloc;
175 * 'channel_pre*' are called just before IO to add any bits
176 * relevant to channels in the c->io_want bitmasks.
178 * 'channel_post*': perform any appropriate operations for
179 * channels which have c->io_ready events pending.
181 chan_fn **channel_pre;
182 chan_fn **channel_post;
184 /* -- tcp forwarding */
185 struct permission_set local_perms;
186 struct permission_set remote_perms;
188 /* -- X11 forwarding */
190 /* Saved X11 local (client) display. */
191 char *x11_saved_display;
193 /* Saved X11 authentication protocol name. */
194 char *x11_saved_proto;
196 /* Saved X11 authentication data. This is the real data. */
197 char *x11_saved_data;
198 u_int x11_saved_data_len;
200 /* Deadline after which all X11 connections are refused */
201 time_t x11_refuse_time;
204 * Fake X11 authentication data. This is what the server will be
205 * sending us; we should replace any occurrences of this by the
208 u_char *x11_fake_data;
209 u_int x11_fake_data_len;
211 /* AF_UNSPEC or AF_INET or AF_INET6 */
214 /* Channel timeouts by type */
215 struct ssh_channel_timeout *timeouts;
220 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
221 static const char *channel_rfwd_bind_host(const char *listen_host);
223 /* non-blocking connect helpers */
224 static int connect_next(struct channel_connect *);
225 static void channel_connect_ctx_free(struct channel_connect *);
226 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
227 static int rdynamic_connect_finish(struct ssh *, Channel *);
230 static void channel_handler_init(struct ssh_channels *sc);
232 /* -- channel core */
235 channel_init_channels(struct ssh *ssh)
237 struct ssh_channels *sc;
239 if ((sc = calloc(1, sizeof(*sc))) == NULL)
240 fatal_f("allocation failed");
241 sc->channels_alloc = 10;
242 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
243 sc->IPv4or6 = AF_UNSPEC;
244 channel_handler_init(sc);
250 channel_by_id(struct ssh *ssh, int id)
254 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
255 logit_f("%d: bad id", id);
258 c = ssh->chanctxt->channels[id];
260 logit_f("%d: bad id: channel free", id);
267 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
272 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
273 c = ssh->chanctxt->channels[i];
274 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
281 * Returns the channel if it is allowed to receive protocol messages.
282 * Private channels, like listening sockets, may not receive messages.
285 channel_lookup(struct ssh *ssh, int id)
289 if ((c = channel_by_id(ssh, id)) == NULL)
293 case SSH_CHANNEL_X11_OPEN:
294 case SSH_CHANNEL_LARVAL:
295 case SSH_CHANNEL_CONNECTING:
296 case SSH_CHANNEL_DYNAMIC:
297 case SSH_CHANNEL_RDYNAMIC_OPEN:
298 case SSH_CHANNEL_RDYNAMIC_FINISH:
299 case SSH_CHANNEL_OPENING:
300 case SSH_CHANNEL_OPEN:
301 case SSH_CHANNEL_ABANDONED:
302 case SSH_CHANNEL_MUX_PROXY:
305 logit("Non-public channel %d, type %d.", id, c->type);
310 * Add a timeout for open channels whose c->ctype (or c->xctype if it is set)
311 * match type_pattern.
314 channel_add_timeout(struct ssh *ssh, const char *type_pattern,
317 struct ssh_channels *sc = ssh->chanctxt;
319 debug2_f("channel type \"%s\" timeout %u seconds",
320 type_pattern, timeout_secs);
321 sc->timeouts = xrecallocarray(sc->timeouts, sc->ntimeouts,
322 sc->ntimeouts + 1, sizeof(*sc->timeouts));
323 sc->timeouts[sc->ntimeouts].type_pattern = xstrdup(type_pattern);
324 sc->timeouts[sc->ntimeouts].timeout_secs = timeout_secs;
328 /* Clears all previously-added channel timeouts */
330 channel_clear_timeouts(struct ssh *ssh)
332 struct ssh_channels *sc = ssh->chanctxt;
335 debug3_f("clearing");
336 for (i = 0; i < sc->ntimeouts; i++)
337 free(sc->timeouts[i].type_pattern);
344 lookup_timeout(struct ssh *ssh, const char *type)
346 struct ssh_channels *sc = ssh->chanctxt;
349 for (i = 0; i < sc->ntimeouts; i++) {
350 if (match_pattern(type, sc->timeouts[i].type_pattern))
351 return sc->timeouts[i].timeout_secs;
358 * Sets "extended type" of a channel; used by session layer to add additional
359 * information about channel types (e.g. shell, login, subsystem) that can then
360 * be used to select timeouts.
361 * Will reset c->inactive_deadline as a side-effect.
364 channel_set_xtype(struct ssh *ssh, int id, const char *xctype)
368 if ((c = channel_by_id(ssh, id)) == NULL)
369 fatal_f("missing channel %d", id);
370 if (c->xctype != NULL)
372 c->xctype = xstrdup(xctype);
373 /* Type has changed, so look up inactivity deadline again */
374 c->inactive_deadline = lookup_timeout(ssh, c->xctype);
375 debug2_f("labeled channel %d as %s (inactive timeout %u)", id, xctype,
376 c->inactive_deadline);
380 * Register filedescriptors for a channel, used when allocating a channel or
381 * when the channel consumer/producer is ready, e.g. shell exec'd
384 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
385 int extusage, int nonblock, int is_tty)
390 (void)fcntl(rfd, F_SETFD, FD_CLOEXEC);
391 if (wfd != -1 && wfd != rfd)
392 (void)fcntl(wfd, F_SETFD, FD_CLOEXEC);
393 if (efd != -1 && efd != rfd && efd != wfd)
394 (void)fcntl(efd, F_SETFD, FD_CLOEXEC);
398 c->sock = (rfd == wfd) ? rfd : -1;
400 c->extended_usage = extusage;
402 if ((c->isatty = is_tty) != 0)
403 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
405 /* XXX: Later AIX versions can't push as much data to tty */
406 c->wfd_isatty = is_tty || isatty(c->wfd);
409 /* enable nonblocking mode */
410 c->restore_block = 0;
411 if (nonblock == CHANNEL_NONBLOCK_STDIO) {
413 * Special handling for stdio file descriptors: do not set
414 * non-blocking mode if they are TTYs. Otherwise prepare to
415 * restore their blocking state on exit to avoid interfering
416 * with other programs that follow.
418 if (rfd != -1 && !isatty(rfd) &&
419 (val = fcntl(rfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
420 c->restore_flags[0] = val;
421 c->restore_block |= CHANNEL_RESTORE_RFD;
424 if (wfd != -1 && !isatty(wfd) &&
425 (val = fcntl(wfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
426 c->restore_flags[1] = val;
427 c->restore_block |= CHANNEL_RESTORE_WFD;
430 if (efd != -1 && !isatty(efd) &&
431 (val = fcntl(efd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
432 c->restore_flags[2] = val;
433 c->restore_block |= CHANNEL_RESTORE_EFD;
436 } else if (nonblock) {
447 * Allocate a new channel object and set its type and socket.
450 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
451 u_int window, u_int maxpack, int extusage, const char *remote_name,
454 struct ssh_channels *sc = ssh->chanctxt;
459 /* Try to find a free slot where to put the new channel. */
460 for (i = 0; i < sc->channels_alloc; i++) {
461 if (sc->channels[i] == NULL) {
462 /* Found a free slot. */
467 if (i >= sc->channels_alloc) {
469 * There are no free slots. Take last+1 slot and expand
472 found = sc->channels_alloc;
473 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
474 fatal_f("internal error: channels_alloc %d too big",
476 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
477 sc->channels_alloc + 10, sizeof(*sc->channels));
478 sc->channels_alloc += 10;
479 debug2("channel: expanding %d", sc->channels_alloc);
481 /* Initialize and return new channel. */
482 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
483 if ((c->input = sshbuf_new()) == NULL ||
484 (c->output = sshbuf_new()) == NULL ||
485 (c->extended = sshbuf_new()) == NULL)
486 fatal_f("sshbuf_new failed");
487 if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
488 fatal_fr(r, "sshbuf_set_max_size");
489 c->ostate = CHAN_OUTPUT_OPEN;
490 c->istate = CHAN_INPUT_OPEN;
491 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
495 c->local_window = window;
496 c->local_window_max = window;
497 c->local_maxpacket = maxpack;
498 c->remote_name = xstrdup(remote_name);
500 c->delayed = 1; /* prevent call to channel_post handler */
501 c->inactive_deadline = lookup_timeout(ssh, c->ctype);
502 TAILQ_INIT(&c->status_confirms);
503 debug("channel %d: new %s [%s] (inactive timeout: %u)",
504 found, c->ctype, remote_name, c->inactive_deadline);
509 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
516 /* restore blocking */
517 if (*fdp == c->rfd &&
518 (c->restore_block & CHANNEL_RESTORE_RFD) != 0)
519 (void)fcntl(*fdp, F_SETFL, c->restore_flags[0]);
520 else if (*fdp == c->wfd &&
521 (c->restore_block & CHANNEL_RESTORE_WFD) != 0)
522 (void)fcntl(*fdp, F_SETFL, c->restore_flags[1]);
523 else if (*fdp == c->efd &&
524 (c->restore_block & CHANNEL_RESTORE_EFD) != 0)
525 (void)fcntl(*fdp, F_SETFL, c->restore_flags[2]);
527 if (*fdp == c->rfd) {
528 c->io_want &= ~SSH_CHAN_IO_RFD;
529 c->io_ready &= ~SSH_CHAN_IO_RFD;
533 if (*fdp == c->wfd) {
534 c->io_want &= ~SSH_CHAN_IO_WFD;
535 c->io_ready &= ~SSH_CHAN_IO_WFD;
539 if (*fdp == c->efd) {
540 c->io_want &= ~SSH_CHAN_IO_EFD;
541 c->io_ready &= ~SSH_CHAN_IO_EFD;
545 if (*fdp == c->sock) {
546 c->io_want &= ~SSH_CHAN_IO_SOCK;
547 c->io_ready &= ~SSH_CHAN_IO_SOCK;
553 *fdp = -1; /* probably redundant */
557 /* Close all channel fd/socket. */
559 channel_close_fds(struct ssh *ssh, Channel *c)
561 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
563 channel_close_fd(ssh, c, &c->sock);
565 channel_close_fd(ssh, c, &c->rfd);
566 if (wfd != sock && wfd != rfd)
567 channel_close_fd(ssh, c, &c->wfd);
568 if (efd != sock && efd != rfd && efd != wfd)
569 channel_close_fd(ssh, c, &c->efd);
573 fwd_perm_clear(struct permission *perm)
575 free(perm->host_to_connect);
576 free(perm->listen_host);
577 free(perm->listen_path);
578 memset(perm, 0, sizeof(*perm));
581 /* Returns an printable name for the specified forwarding permission list */
583 fwd_ident(int who, int where)
585 if (who == FORWARD_ADM) {
586 if (where == FORWARD_LOCAL)
587 return "admin local";
588 else if (where == FORWARD_REMOTE)
589 return "admin remote";
590 } else if (who == FORWARD_USER) {
591 if (where == FORWARD_LOCAL)
593 else if (where == FORWARD_REMOTE)
594 return "user remote";
596 fatal("Unknown forward permission list %d/%d", who, where);
599 /* Returns the forwarding permission list for the specified direction */
600 static struct permission_set *
601 permission_set_get(struct ssh *ssh, int where)
603 struct ssh_channels *sc = ssh->chanctxt;
607 return &sc->local_perms;
610 return &sc->remote_perms;
613 fatal_f("invalid forwarding direction %d", where);
617 /* Returns pointers to the specified forwarding list and its element count */
619 permission_set_get_array(struct ssh *ssh, int who, int where,
620 struct permission ***permpp, u_int **npermpp)
622 struct permission_set *pset = permission_set_get(ssh, where);
626 *permpp = &pset->permitted_user;
627 *npermpp = &pset->num_permitted_user;
630 *permpp = &pset->permitted_admin;
631 *npermpp = &pset->num_permitted_admin;
634 fatal_f("invalid forwarding client %d", who);
638 /* Adds an entry to the specified forwarding list */
640 permission_set_add(struct ssh *ssh, int who, int where,
641 const char *host_to_connect, int port_to_connect,
642 const char *listen_host, const char *listen_path, int listen_port,
645 struct permission **permp;
648 permission_set_get_array(ssh, who, where, &permp, &npermp);
650 if (*npermp >= INT_MAX)
651 fatal_f("%s overflow", fwd_ident(who, where));
653 *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
655 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
656 (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
657 (*permp)[n].port_to_connect = port_to_connect;
658 (*permp)[n].listen_host = MAYBE_DUP(listen_host);
659 (*permp)[n].listen_path = MAYBE_DUP(listen_path);
660 (*permp)[n].listen_port = listen_port;
661 (*permp)[n].downstream = downstream;
667 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
669 struct ssh_channels *sc = ssh->chanctxt;
670 struct permission_set *pset = &sc->local_perms;
671 struct permission *perm;
675 for (i = 0; i < pset->num_permitted_user; i++) {
676 perm = &pset->permitted_user[i];
677 if (perm->downstream != c)
680 /* cancel on the server, since mux client is gone */
681 debug("channel %d: cleanup remote forward for %s:%u",
682 c->self, perm->listen_host, perm->listen_port);
683 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
684 (r = sshpkt_put_cstring(ssh,
685 "cancel-tcpip-forward")) != 0 ||
686 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
687 (r = sshpkt_put_cstring(ssh,
688 channel_rfwd_bind_host(perm->listen_host))) != 0 ||
689 (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
690 (r = sshpkt_send(ssh)) != 0) {
691 fatal_fr(r, "channel %i", c->self);
693 fwd_perm_clear(perm); /* unregister */
697 /* Free the channel and close its fd/socket. */
699 channel_free(struct ssh *ssh, Channel *c)
701 struct ssh_channels *sc = ssh->chanctxt;
705 struct channel_confirm *cc;
707 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
708 if ((other = sc->channels[i]) == NULL)
711 /* detach from mux client and prepare for closing */
712 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
713 other->type == SSH_CHANNEL_MUX_PROXY &&
714 other->mux_ctx == c) {
715 other->mux_ctx = NULL;
716 other->type = SSH_CHANNEL_OPEN;
717 other->istate = CHAN_INPUT_CLOSED;
718 other->ostate = CHAN_OUTPUT_CLOSED;
721 debug("channel %d: free: %s, nchannels %u", c->self,
722 c->remote_name ? c->remote_name : "???", n);
724 if (c->type == SSH_CHANNEL_MUX_CLIENT) {
725 mux_remove_remote_forwardings(ssh, c);
728 } else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
733 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
734 s = channel_open_message(ssh);
735 debug3("channel %d: status: %s", c->self, s);
739 channel_close_fds(ssh, c);
740 sshbuf_free(c->input);
741 sshbuf_free(c->output);
742 sshbuf_free(c->extended);
743 c->input = c->output = c->extended = NULL;
744 free(c->remote_name);
745 c->remote_name = NULL;
748 free(c->listening_addr);
749 c->listening_addr = NULL;
752 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
753 if (cc->abandon_cb != NULL)
754 cc->abandon_cb(ssh, c, cc->ctx);
755 TAILQ_REMOVE(&c->status_confirms, cc, entry);
756 freezero(cc, sizeof(*cc));
758 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
759 c->filter_cleanup(ssh, c->self, c->filter_ctx);
760 sc->channels[c->self] = NULL;
761 freezero(c, sizeof(*c));
765 channel_free_all(struct ssh *ssh)
768 struct ssh_channels *sc = ssh->chanctxt;
770 for (i = 0; i < sc->channels_alloc; i++)
771 if (sc->channels[i] != NULL)
772 channel_free(ssh, sc->channels[i]);
776 sc->channels_alloc = 0;
778 free(sc->x11_saved_display);
779 sc->x11_saved_display = NULL;
781 free(sc->x11_saved_proto);
782 sc->x11_saved_proto = NULL;
784 free(sc->x11_saved_data);
785 sc->x11_saved_data = NULL;
786 sc->x11_saved_data_len = 0;
788 free(sc->x11_fake_data);
789 sc->x11_fake_data = NULL;
790 sc->x11_fake_data_len = 0;
794 * Closes the sockets/fds of all channels. This is used to close extra file
795 * descriptors after a fork.
798 channel_close_all(struct ssh *ssh)
802 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
803 if (ssh->chanctxt->channels[i] != NULL)
804 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
808 * Stop listening to channels.
811 channel_stop_listening(struct ssh *ssh)
816 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
817 c = ssh->chanctxt->channels[i];
820 case SSH_CHANNEL_AUTH_SOCKET:
821 case SSH_CHANNEL_PORT_LISTENER:
822 case SSH_CHANNEL_RPORT_LISTENER:
823 case SSH_CHANNEL_X11_LISTENER:
824 case SSH_CHANNEL_UNIX_LISTENER:
825 case SSH_CHANNEL_RUNIX_LISTENER:
826 channel_close_fd(ssh, c, &c->sock);
827 channel_free(ssh, c);
835 * Returns true if no channel has too much buffered data, and false if one or
836 * more channel is overfull.
839 channel_not_very_much_buffered_data(struct ssh *ssh)
842 u_int maxsize = ssh_packet_get_maxsize(ssh);
845 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
846 c = ssh->chanctxt->channels[i];
847 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
849 if (sshbuf_len(c->output) > maxsize) {
850 debug2("channel %d: big output buffer %zu > %u",
851 c->self, sshbuf_len(c->output), maxsize);
858 /* Returns true if any channel is still open. */
860 channel_still_open(struct ssh *ssh)
865 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
866 c = ssh->chanctxt->channels[i];
870 case SSH_CHANNEL_X11_LISTENER:
871 case SSH_CHANNEL_PORT_LISTENER:
872 case SSH_CHANNEL_RPORT_LISTENER:
873 case SSH_CHANNEL_MUX_LISTENER:
874 case SSH_CHANNEL_CLOSED:
875 case SSH_CHANNEL_AUTH_SOCKET:
876 case SSH_CHANNEL_DYNAMIC:
877 case SSH_CHANNEL_RDYNAMIC_OPEN:
878 case SSH_CHANNEL_CONNECTING:
879 case SSH_CHANNEL_ZOMBIE:
880 case SSH_CHANNEL_ABANDONED:
881 case SSH_CHANNEL_UNIX_LISTENER:
882 case SSH_CHANNEL_RUNIX_LISTENER:
884 case SSH_CHANNEL_LARVAL:
886 case SSH_CHANNEL_OPENING:
887 case SSH_CHANNEL_OPEN:
888 case SSH_CHANNEL_RDYNAMIC_FINISH:
889 case SSH_CHANNEL_X11_OPEN:
890 case SSH_CHANNEL_MUX_CLIENT:
891 case SSH_CHANNEL_MUX_PROXY:
894 fatal_f("bad channel type %d", c->type);
901 /* Returns the id of an open channel suitable for keepaliving */
903 channel_find_open(struct ssh *ssh)
908 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
909 c = ssh->chanctxt->channels[i];
910 if (c == NULL || !c->have_remote_id)
913 case SSH_CHANNEL_CLOSED:
914 case SSH_CHANNEL_DYNAMIC:
915 case SSH_CHANNEL_RDYNAMIC_OPEN:
916 case SSH_CHANNEL_RDYNAMIC_FINISH:
917 case SSH_CHANNEL_X11_LISTENER:
918 case SSH_CHANNEL_PORT_LISTENER:
919 case SSH_CHANNEL_RPORT_LISTENER:
920 case SSH_CHANNEL_MUX_LISTENER:
921 case SSH_CHANNEL_MUX_CLIENT:
922 case SSH_CHANNEL_MUX_PROXY:
923 case SSH_CHANNEL_OPENING:
924 case SSH_CHANNEL_CONNECTING:
925 case SSH_CHANNEL_ZOMBIE:
926 case SSH_CHANNEL_ABANDONED:
927 case SSH_CHANNEL_UNIX_LISTENER:
928 case SSH_CHANNEL_RUNIX_LISTENER:
930 case SSH_CHANNEL_LARVAL:
931 case SSH_CHANNEL_AUTH_SOCKET:
932 case SSH_CHANNEL_OPEN:
933 case SSH_CHANNEL_X11_OPEN:
936 fatal_f("bad channel type %d", c->type);
943 /* Returns the state of the channel's extended usage flag */
945 channel_format_extended_usage(const Channel *c)
950 switch (c->extended_usage) {
951 case CHAN_EXTENDED_WRITE:
953 case CHAN_EXTENDED_READ:
955 case CHAN_EXTENDED_IGNORE:
963 channel_format_status(const Channel *c)
967 xasprintf(&ret, "t%d [%s] %s%u i%u/%zu o%u/%zu e[%s]/%zu "
968 "fd %d/%d/%d sock %d cc %d io 0x%02x/0x%02x",
969 c->type, c->xctype != NULL ? c->xctype : c->ctype,
970 c->have_remote_id ? "r" : "nr", c->remote_id,
971 c->istate, sshbuf_len(c->input),
972 c->ostate, sshbuf_len(c->output),
973 channel_format_extended_usage(c), sshbuf_len(c->extended),
974 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan,
975 c->io_want, c->io_ready);
980 * Returns a message describing the currently open forwarded connections,
981 * suitable for sending to the client. The message contains crlf pairs for
985 channel_open_message(struct ssh *ssh)
993 if ((buf = sshbuf_new()) == NULL)
994 fatal_f("sshbuf_new");
995 if ((r = sshbuf_putf(buf,
996 "The following connections are open:\r\n")) != 0)
997 fatal_fr(r, "sshbuf_putf");
998 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
999 c = ssh->chanctxt->channels[i];
1003 case SSH_CHANNEL_X11_LISTENER:
1004 case SSH_CHANNEL_PORT_LISTENER:
1005 case SSH_CHANNEL_RPORT_LISTENER:
1006 case SSH_CHANNEL_CLOSED:
1007 case SSH_CHANNEL_AUTH_SOCKET:
1008 case SSH_CHANNEL_ZOMBIE:
1009 case SSH_CHANNEL_ABANDONED:
1010 case SSH_CHANNEL_MUX_LISTENER:
1011 case SSH_CHANNEL_UNIX_LISTENER:
1012 case SSH_CHANNEL_RUNIX_LISTENER:
1014 case SSH_CHANNEL_LARVAL:
1015 case SSH_CHANNEL_OPENING:
1016 case SSH_CHANNEL_CONNECTING:
1017 case SSH_CHANNEL_DYNAMIC:
1018 case SSH_CHANNEL_RDYNAMIC_OPEN:
1019 case SSH_CHANNEL_RDYNAMIC_FINISH:
1020 case SSH_CHANNEL_OPEN:
1021 case SSH_CHANNEL_X11_OPEN:
1022 case SSH_CHANNEL_MUX_PROXY:
1023 case SSH_CHANNEL_MUX_CLIENT:
1024 cp = channel_format_status(c);
1025 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
1026 c->self, c->remote_name, cp)) != 0) {
1028 fatal_fr(r, "sshbuf_putf");
1033 fatal_f("bad channel type %d", c->type);
1037 if ((ret = sshbuf_dup_string(buf)) == NULL)
1038 fatal_f("sshbuf_dup_string");
1044 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
1048 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1049 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
1050 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1051 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1052 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
1053 fatal_r(r, "%s: channel %i: open", where, c->self);
1058 channel_send_open(struct ssh *ssh, int id)
1060 Channel *c = channel_lookup(ssh, id);
1064 logit("channel_send_open: %d: bad id", id);
1067 debug2("channel %d: send open", id);
1068 open_preamble(ssh, __func__, c, c->ctype);
1069 if ((r = sshpkt_send(ssh)) != 0)
1070 fatal_fr(r, "channel %i", c->self);
1074 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
1076 Channel *c = channel_lookup(ssh, id);
1080 logit_f("%d: unknown channel id", id);
1083 if (!c->have_remote_id)
1084 fatal_f("channel %d: no remote id", c->self);
1086 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1087 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
1088 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1089 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
1090 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
1091 fatal_fr(r, "channel %i", c->self);
1096 channel_register_status_confirm(struct ssh *ssh, int id,
1097 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1099 struct channel_confirm *cc;
1102 if ((c = channel_lookup(ssh, id)) == NULL)
1103 fatal_f("%d: bad id", id);
1105 cc = xcalloc(1, sizeof(*cc));
1107 cc->abandon_cb = abandon_cb;
1109 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1113 channel_register_open_confirm(struct ssh *ssh, int id,
1114 channel_open_fn *fn, void *ctx)
1116 Channel *c = channel_lookup(ssh, id);
1119 logit_f("%d: bad id", id);
1122 c->open_confirm = fn;
1123 c->open_confirm_ctx = ctx;
1127 channel_register_cleanup(struct ssh *ssh, int id,
1128 channel_callback_fn *fn, int do_close)
1130 Channel *c = channel_by_id(ssh, id);
1133 logit_f("%d: bad id", id);
1136 c->detach_user = fn;
1137 c->detach_close = do_close;
1141 channel_cancel_cleanup(struct ssh *ssh, int id)
1143 Channel *c = channel_by_id(ssh, id);
1146 logit_f("%d: bad id", id);
1149 c->detach_user = NULL;
1150 c->detach_close = 0;
1154 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1155 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1157 Channel *c = channel_lookup(ssh, id);
1160 logit_f("%d: bad id", id);
1163 c->input_filter = ifn;
1164 c->output_filter = ofn;
1165 c->filter_ctx = ctx;
1166 c->filter_cleanup = cfn;
1170 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1171 int extusage, int nonblock, int is_tty, u_int window_max)
1173 Channel *c = channel_lookup(ssh, id);
1176 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1177 fatal("channel_activate for non-larval channel %d.", id);
1178 if (!c->have_remote_id)
1179 fatal_f("channel %d: no remote id", c->self);
1181 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1182 c->type = SSH_CHANNEL_OPEN;
1183 c->lastused = monotime();
1184 c->local_window = c->local_window_max = window_max;
1186 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1187 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1188 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1189 (r = sshpkt_send(ssh)) != 0)
1190 fatal_fr(r, "channel %i", c->self);
1194 channel_pre_listener(struct ssh *ssh, Channel *c)
1196 c->io_want = SSH_CHAN_IO_SOCK_R;
1200 channel_pre_connecting(struct ssh *ssh, Channel *c)
1202 debug3("channel %d: waiting for connection", c->self);
1203 c->io_want = SSH_CHAN_IO_SOCK_W;
1207 channel_pre_open(struct ssh *ssh, Channel *c)
1210 if (c->istate == CHAN_INPUT_OPEN &&
1211 c->remote_window > 0 &&
1212 sshbuf_len(c->input) < c->remote_window &&
1213 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1214 c->io_want |= SSH_CHAN_IO_RFD;
1215 if (c->ostate == CHAN_OUTPUT_OPEN ||
1216 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1217 if (sshbuf_len(c->output) > 0) {
1218 c->io_want |= SSH_CHAN_IO_WFD;
1219 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1220 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1221 debug2("channel %d: "
1222 "obuf_empty delayed efd %d/(%zu)", c->self,
1223 c->efd, sshbuf_len(c->extended));
1225 chan_obuf_empty(ssh, c);
1228 /** XXX check close conditions, too */
1229 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1230 c->ostate == CHAN_OUTPUT_CLOSED)) {
1231 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1232 sshbuf_len(c->extended) > 0)
1233 c->io_want |= SSH_CHAN_IO_EFD_W;
1234 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1235 (c->extended_usage == CHAN_EXTENDED_READ ||
1236 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1237 sshbuf_len(c->extended) < c->remote_window)
1238 c->io_want |= SSH_CHAN_IO_EFD_R;
1240 /* XXX: What about efd? races? */
1244 * This is a special state for X11 authentication spoofing. An opened X11
1245 * connection (when authentication spoofing is being done) remains in this
1246 * state until the first packet has been completely read. The authentication
1247 * data in that packet is then substituted by the real data if it matches the
1248 * fake data, and the channel is put into normal mode.
1249 * XXX All this happens at the client side.
1250 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1253 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1255 struct ssh_channels *sc = ssh->chanctxt;
1257 u_int proto_len, data_len;
1259 /* Is this being called after the refusal deadline? */
1260 if (sc->x11_refuse_time != 0 &&
1261 monotime() >= sc->x11_refuse_time) {
1262 verbose("Rejected X11 connection after ForwardX11Timeout "
1267 /* Check if the fixed size part of the packet is in buffer. */
1268 if (sshbuf_len(b) < 12)
1271 /* Parse the lengths of variable-length fields. */
1272 ucp = sshbuf_mutable_ptr(b);
1273 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1274 proto_len = 256 * ucp[6] + ucp[7];
1275 data_len = 256 * ucp[8] + ucp[9];
1276 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1277 proto_len = ucp[6] + 256 * ucp[7];
1278 data_len = ucp[8] + 256 * ucp[9];
1280 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1285 /* Check if the whole packet is in buffer. */
1287 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1290 /* Check if authentication protocol matches. */
1291 if (proto_len != strlen(sc->x11_saved_proto) ||
1292 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1293 debug2("X11 connection uses different authentication protocol.");
1296 /* Check if authentication data matches our fake data. */
1297 if (data_len != sc->x11_fake_data_len ||
1298 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1299 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1300 debug2("X11 auth data does not match fake data.");
1303 /* Check fake data length */
1304 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1305 error("X11 fake_data_len %d != saved_data_len %d",
1306 sc->x11_fake_data_len, sc->x11_saved_data_len);
1310 * Received authentication protocol and data match
1311 * our fake data. Substitute the fake data with real
1314 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1315 sc->x11_saved_data, sc->x11_saved_data_len);
1320 channel_force_close(struct ssh *ssh, Channel *c, int abandon)
1322 debug3_f("channel %d: forcibly closing", c->self);
1323 if (c->istate == CHAN_INPUT_OPEN)
1324 chan_read_failed(ssh, c);
1325 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1326 sshbuf_reset(c->input);
1327 chan_ibuf_empty(ssh, c);
1329 if (c->ostate == CHAN_OUTPUT_OPEN ||
1330 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1331 sshbuf_reset(c->output);
1332 chan_write_failed(ssh, c);
1335 c->detach_user(ssh, c->self, 1, NULL);
1337 channel_close_fd(ssh, c, &c->efd);
1339 c->type = SSH_CHANNEL_ABANDONED;
1340 /* exempt from inactivity timeouts */
1341 c->inactive_deadline = 0;
1346 channel_pre_x11_open(struct ssh *ssh, Channel *c)
1348 int ret = x11_open_helper(ssh, c->output);
1350 /* c->force_drain = 1; */
1353 c->type = SSH_CHANNEL_OPEN;
1354 c->lastused = monotime();
1355 channel_pre_open(ssh, c);
1356 } else if (ret == -1) {
1357 logit("X11 connection rejected because of wrong "
1359 debug2("X11 rejected %d i%d/o%d",
1360 c->self, c->istate, c->ostate);
1361 channel_force_close(ssh, c, 0);
1366 channel_pre_mux_client(struct ssh *ssh, Channel *c)
1369 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1370 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1371 c->io_want |= SSH_CHAN_IO_RFD;
1372 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1373 /* clear buffer immediately (discard any partial packet) */
1374 sshbuf_reset(c->input);
1375 chan_ibuf_empty(ssh, c);
1376 /* Start output drain. XXX just kill chan? */
1377 chan_rcvd_oclose(ssh, c);
1379 if (c->ostate == CHAN_OUTPUT_OPEN ||
1380 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1381 if (sshbuf_len(c->output) > 0)
1382 c->io_want |= SSH_CHAN_IO_WFD;
1383 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1384 chan_obuf_empty(ssh, c);
1388 /* try to decode a socks4 header */
1390 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1394 u_int len, have, i, found, need;
1399 u_int16_t dest_port;
1400 struct in_addr dest_addr;
1404 debug2("channel %d: decode socks4", c->self);
1406 have = sshbuf_len(input);
1407 len = sizeof(s4_req);
1410 p = sshbuf_ptr(input);
1413 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1414 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1415 debug2("channel %d: socks4a request", c->self);
1416 /* ... and needs an extra string (the hostname) */
1419 /* Check for terminating NUL on the string(s) */
1420 for (found = 0, i = len; i < have; i++) {
1427 /* the peer is probably sending garbage */
1428 debug("channel %d: decode socks4: too long",
1435 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1436 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1437 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1438 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1439 debug_r(r, "channels %d: decode socks4", c->self);
1442 have = sshbuf_len(input);
1443 p = sshbuf_ptr(input);
1444 if (memchr(p, '\0', have) == NULL) {
1445 error("channel %d: decode socks4: unterminated user", c->self);
1449 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1450 len++; /* trailing '\0' */
1451 strlcpy(username, p, sizeof(username));
1452 if ((r = sshbuf_consume(input, len)) != 0)
1453 fatal_fr(r, "channel %d: consume", c->self);
1456 if (need == 1) { /* SOCKS4: one string */
1457 host = inet_ntoa(s4_req.dest_addr);
1458 c->path = xstrdup(host);
1459 } else { /* SOCKS4A: two strings */
1460 have = sshbuf_len(input);
1461 p = sshbuf_ptr(input);
1462 if (memchr(p, '\0', have) == NULL) {
1463 error("channel %d: decode socks4a: host not nul "
1464 "terminated", c->self);
1468 debug2("channel %d: decode socks4a: host %s/%d",
1470 len++; /* trailing '\0' */
1471 if (len > NI_MAXHOST) {
1472 error("channel %d: hostname \"%.100s\" too long",
1476 c->path = xstrdup(p);
1477 if ((r = sshbuf_consume(input, len)) != 0)
1478 fatal_fr(r, "channel %d: consume", c->self);
1480 c->host_port = ntohs(s4_req.dest_port);
1482 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1483 c->self, c->path, c->host_port, s4_req.command);
1485 if (s4_req.command != 1) {
1486 debug("channel %d: cannot handle: %s cn %d",
1487 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1490 s4_rsp.version = 0; /* vn: 0 for reply */
1491 s4_rsp.command = 90; /* cd: req granted */
1492 s4_rsp.dest_port = 0; /* ignored */
1493 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1494 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1495 fatal_fr(r, "channel %d: append reply", c->self);
1499 /* try to decode a socks5 header */
1500 #define SSH_SOCKS5_AUTHDONE 0x1000
1501 #define SSH_SOCKS5_NOAUTH 0x00
1502 #define SSH_SOCKS5_IPV4 0x01
1503 #define SSH_SOCKS5_DOMAIN 0x03
1504 #define SSH_SOCKS5_IPV6 0x04
1505 #define SSH_SOCKS5_CONNECT 0x01
1506 #define SSH_SOCKS5_SUCCESS 0x00
1509 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1511 /* XXX use get/put_u8 instead of trusting struct padding */
1518 u_int16_t dest_port;
1519 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1521 u_int have, need, i, found, nmethods, addrlen, af;
1524 debug2("channel %d: decode socks5", c->self);
1525 p = sshbuf_ptr(input);
1528 have = sshbuf_len(input);
1529 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1530 /* format: ver | nmethods | methods */
1534 if (have < nmethods + 2)
1536 /* look for method: "NO AUTHENTICATION REQUIRED" */
1537 for (found = 0, i = 2; i < nmethods + 2; i++) {
1538 if (p[i] == SSH_SOCKS5_NOAUTH) {
1544 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1548 if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1549 fatal_fr(r, "channel %d: consume", c->self);
1550 /* version, method */
1551 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1552 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1553 fatal_fr(r, "channel %d: append reply", c->self);
1554 c->flags |= SSH_SOCKS5_AUTHDONE;
1555 debug2("channel %d: socks5 auth done", c->self);
1556 return 0; /* need more */
1558 debug2("channel %d: socks5 post auth", c->self);
1559 if (have < sizeof(s5_req)+1)
1560 return 0; /* need more */
1561 memcpy(&s5_req, p, sizeof(s5_req));
1562 if (s5_req.version != 0x05 ||
1563 s5_req.command != SSH_SOCKS5_CONNECT ||
1564 s5_req.reserved != 0x00) {
1565 debug2("channel %d: only socks5 connect supported", c->self);
1568 switch (s5_req.atyp){
1569 case SSH_SOCKS5_IPV4:
1573 case SSH_SOCKS5_DOMAIN:
1574 addrlen = p[sizeof(s5_req)];
1577 case SSH_SOCKS5_IPV6:
1582 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1585 need = sizeof(s5_req) + addrlen + 2;
1586 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1590 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1591 fatal_fr(r, "channel %d: consume", c->self);
1592 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1593 /* host string length */
1594 if ((r = sshbuf_consume(input, 1)) != 0)
1595 fatal_fr(r, "channel %d: consume", c->self);
1597 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1598 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1599 debug_r(r, "channel %d: parse addr/port", c->self);
1602 dest_addr[addrlen] = '\0';
1605 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1606 if (addrlen >= NI_MAXHOST) {
1607 error("channel %d: dynamic request: socks5 hostname "
1608 "\"%.100s\" too long", c->self, dest_addr);
1611 c->path = xstrdup(dest_addr);
1613 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1615 c->path = xstrdup(ntop);
1617 c->host_port = ntohs(dest_port);
1619 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1620 c->self, c->path, c->host_port, s5_req.command);
1622 s5_rsp.version = 0x05;
1623 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1624 s5_rsp.reserved = 0; /* ignored */
1625 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1626 dest_port = 0; /* ignored */
1628 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1629 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1630 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1631 fatal_fr(r, "channel %d: append reply", c->self);
1636 channel_connect_stdio_fwd(struct ssh *ssh,
1637 const char *host_to_connect, u_short port_to_connect,
1638 int in, int out, int nonblock)
1642 debug_f("%s:%d", host_to_connect, port_to_connect);
1644 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1645 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1646 0, "stdio-forward", nonblock);
1648 c->path = xstrdup(host_to_connect);
1649 c->host_port = port_to_connect;
1650 c->listening_port = 0;
1653 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1654 port_open_helper(ssh, c, "direct-tcpip");
1659 /* dynamic port forwarding */
1661 channel_pre_dynamic(struct ssh *ssh, Channel *c)
1668 have = sshbuf_len(c->input);
1669 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1670 /* sshbuf_dump(c->input, stderr); */
1671 /* check if the fixed size part of the packet is in buffer. */
1674 c->io_want |= SSH_CHAN_IO_RFD;
1677 /* try to guess the protocol */
1678 p = sshbuf_ptr(c->input);
1679 /* XXX sshbuf_peek_u8? */
1682 ret = channel_decode_socks4(c, c->input, c->output);
1685 ret = channel_decode_socks5(c, c->input, c->output);
1692 chan_mark_dead(ssh, c);
1693 } else if (ret == 0) {
1694 debug2("channel %d: pre_dynamic: need more", c->self);
1696 c->io_want |= SSH_CHAN_IO_RFD;
1697 if (sshbuf_len(c->output))
1698 c->io_want |= SSH_CHAN_IO_WFD;
1700 /* switch to the next state */
1701 c->type = SSH_CHANNEL_OPENING;
1702 port_open_helper(ssh, c, "direct-tcpip");
1706 /* simulate read-error */
1708 rdynamic_close(struct ssh *ssh, Channel *c)
1710 c->type = SSH_CHANNEL_OPEN;
1711 channel_force_close(ssh, c, 0);
1714 /* reverse dynamic port forwarding */
1716 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1722 have = sshbuf_len(c->output);
1723 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1724 /* sshbuf_dump(c->output, stderr); */
1726 if (c->flags & CHAN_EOF_RCVD) {
1727 if ((r = sshbuf_consume(c->output, have)) != 0)
1728 fatal_fr(r, "channel %d: consume", c->self);
1729 rdynamic_close(ssh, c);
1732 /* check if the fixed size part of the packet is in buffer. */
1735 /* try to guess the protocol */
1736 p = sshbuf_ptr(c->output);
1739 /* switch input/output for reverse forwarding */
1740 ret = channel_decode_socks4(c, c->output, c->input);
1743 ret = channel_decode_socks5(c, c->output, c->input);
1750 rdynamic_close(ssh, c);
1751 } else if (ret == 0) {
1752 debug2("channel %d: pre_rdynamic: need more", c->self);
1753 /* send socks request to peer */
1754 len = sshbuf_len(c->input);
1755 if (len > 0 && len < c->remote_window) {
1756 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1757 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1758 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1759 (r = sshpkt_send(ssh)) != 0) {
1760 fatal_fr(r, "channel %i: rdynamic", c->self);
1762 if ((r = sshbuf_consume(c->input, len)) != 0)
1763 fatal_fr(r, "channel %d: consume", c->self);
1764 c->remote_window -= len;
1766 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1767 /* the connect failed */
1768 rdynamic_close(ssh, c);
1772 /* This is our fake X11 server socket. */
1774 channel_post_x11_listener(struct ssh *ssh, Channel *c)
1777 struct sockaddr_storage addr;
1778 int r, newsock, oerrno, remote_port;
1780 char buf[16384], *remote_ipaddr;
1782 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1785 debug("X11 connection requested.");
1786 addrlen = sizeof(addr);
1787 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1788 if (c->single_connection) {
1790 debug2("single_connection: closing X11 listener.");
1791 channel_close_fd(ssh, c, &c->sock);
1792 chan_mark_dead(ssh, c);
1795 if (newsock == -1) {
1796 if (errno != EINTR && errno != EWOULDBLOCK &&
1797 errno != ECONNABORTED)
1798 error("accept: %.100s", strerror(errno));
1799 if (errno == EMFILE || errno == ENFILE)
1800 c->notbefore = monotime() + 1;
1803 set_nodelay(newsock);
1804 remote_ipaddr = get_peer_ipaddr(newsock);
1805 remote_port = get_peer_port(newsock);
1806 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1807 remote_ipaddr, remote_port);
1809 nc = channel_new(ssh, "x11-connection",
1810 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1811 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1812 open_preamble(ssh, __func__, nc, "x11");
1813 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1814 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1815 fatal_fr(r, "channel %i: reply", c->self);
1817 if ((r = sshpkt_send(ssh)) != 0)
1818 fatal_fr(r, "channel %i: send", c->self);
1819 free(remote_ipaddr);
1823 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1825 char *local_ipaddr = get_local_ipaddr(c->sock);
1826 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1827 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1828 int remote_port = get_peer_port(c->sock);
1831 if (remote_port == -1) {
1832 /* Fake addr/port to appease peers that validate it (Tectia) */
1833 free(remote_ipaddr);
1834 remote_ipaddr = xstrdup("127.0.0.1");
1835 remote_port = 65535;
1838 free(c->remote_name);
1839 xasprintf(&c->remote_name,
1840 "%s: listening port %d for %.100s port %d, "
1841 "connect from %.200s port %d to %.100s port %d",
1842 rtype, c->listening_port, c->path, c->host_port,
1843 remote_ipaddr, remote_port, local_ipaddr, local_port);
1845 open_preamble(ssh, __func__, c, rtype);
1846 if (strcmp(rtype, "direct-tcpip") == 0) {
1847 /* target host, port */
1848 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1849 (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1850 fatal_fr(r, "channel %i: reply", c->self);
1851 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1853 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1854 fatal_fr(r, "channel %i: reply", c->self);
1855 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1857 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1858 fatal_fr(r, "channel %i: reply", c->self);
1860 /* listen address, port */
1861 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1862 (r = sshpkt_put_u32(ssh, local_port)) != 0)
1863 fatal_fr(r, "channel %i: reply", c->self);
1865 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1866 /* reserved for future owner/mode info */
1867 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1868 fatal_fr(r, "channel %i: reply", c->self);
1870 /* originator host and port */
1871 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1872 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1873 fatal_fr(r, "channel %i: reply", c->self);
1875 if ((r = sshpkt_send(ssh)) != 0)
1876 fatal_fr(r, "channel %i: send", c->self);
1877 free(remote_ipaddr);
1882 channel_set_x11_refuse_time(struct ssh *ssh, time_t refuse_time)
1884 ssh->chanctxt->x11_refuse_time = refuse_time;
1888 * This socket is listening for connections to a forwarded TCP/IP port.
1891 channel_post_port_listener(struct ssh *ssh, Channel *c)
1894 struct sockaddr_storage addr;
1895 int newsock, nextstate;
1899 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1902 debug("Connection to port %d forwarding to %.100s port %d requested.",
1903 c->listening_port, c->path, c->host_port);
1905 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1906 nextstate = SSH_CHANNEL_OPENING;
1907 rtype = "forwarded-tcpip";
1908 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1909 nextstate = SSH_CHANNEL_OPENING;
1910 rtype = "forwarded-streamlocal@openssh.com";
1911 } else if (c->host_port == PORT_STREAMLOCAL) {
1912 nextstate = SSH_CHANNEL_OPENING;
1913 rtype = "direct-streamlocal@openssh.com";
1914 } else if (c->host_port == 0) {
1915 nextstate = SSH_CHANNEL_DYNAMIC;
1916 rtype = "dynamic-tcpip";
1918 nextstate = SSH_CHANNEL_OPENING;
1919 rtype = "direct-tcpip";
1922 addrlen = sizeof(addr);
1923 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1924 if (newsock == -1) {
1925 if (errno != EINTR && errno != EWOULDBLOCK &&
1926 errno != ECONNABORTED)
1927 error("accept: %.100s", strerror(errno));
1928 if (errno == EMFILE || errno == ENFILE)
1929 c->notbefore = monotime() + 1;
1932 if (c->host_port != PORT_STREAMLOCAL)
1933 set_nodelay(newsock);
1934 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1935 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1936 nc->listening_port = c->listening_port;
1937 nc->host_port = c->host_port;
1938 if (c->path != NULL)
1939 nc->path = xstrdup(c->path);
1941 if (nextstate != SSH_CHANNEL_DYNAMIC)
1942 port_open_helper(ssh, nc, rtype);
1946 * This is the authentication agent socket listening for connections from
1950 channel_post_auth_listener(struct ssh *ssh, Channel *c)
1954 struct sockaddr_storage addr;
1957 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1960 addrlen = sizeof(addr);
1961 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1962 if (newsock == -1) {
1963 error("accept from auth socket: %.100s", strerror(errno));
1964 if (errno == EMFILE || errno == ENFILE)
1965 c->notbefore = monotime() + 1;
1968 nc = channel_new(ssh, "agent-connection",
1969 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1970 c->local_window_max, c->local_maxpacket,
1971 0, "accepted auth socket", 1);
1972 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1973 if ((r = sshpkt_send(ssh)) != 0)
1974 fatal_fr(r, "channel %i", c->self);
1978 channel_post_connecting(struct ssh *ssh, Channel *c)
1980 int err = 0, sock, isopen, r;
1981 socklen_t sz = sizeof(err);
1983 if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
1985 if (!c->have_remote_id)
1986 fatal_f("channel %d: no remote id", c->self);
1987 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1988 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1990 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1992 error("getsockopt SO_ERROR failed");
1996 /* Non-blocking connection completed */
1997 debug("channel %d: connected to %s port %d",
1998 c->self, c->connect_ctx.host, c->connect_ctx.port);
1999 channel_connect_ctx_free(&c->connect_ctx);
2000 c->type = SSH_CHANNEL_OPEN;
2001 c->lastused = monotime();
2003 /* no message necessary */
2005 if ((r = sshpkt_start(ssh,
2006 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
2007 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2008 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
2009 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
2010 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
2011 (r = sshpkt_send(ssh)) != 0)
2012 fatal_fr(r, "channel %i open confirm", c->self);
2016 if (err == EINTR || err == EAGAIN || err == EINPROGRESS)
2019 /* Non-blocking connection failed */
2020 debug("channel %d: connection failed: %s", c->self, strerror(err));
2022 /* Try next address, if any */
2023 if ((sock = connect_next(&c->connect_ctx)) == -1) {
2024 /* Exhausted all addresses for this destination */
2025 error("connect_to %.100s port %d: failed.",
2026 c->connect_ctx.host, c->connect_ctx.port);
2027 channel_connect_ctx_free(&c->connect_ctx);
2029 rdynamic_close(ssh, c);
2031 if ((r = sshpkt_start(ssh,
2032 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
2033 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2034 (r = sshpkt_put_u32(ssh,
2035 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
2036 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
2037 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2038 (r = sshpkt_send(ssh)) != 0)
2039 fatal_fr(r, "channel %i: failure", c->self);
2040 chan_mark_dead(ssh, c);
2044 /* New non-blocking connection in progress */
2046 c->sock = c->rfd = c->wfd = sock;
2050 channel_handle_rfd(struct ssh *ssh, Channel *c)
2052 char buf[CHAN_RBUF];
2055 size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
2056 int pty_zeroread = 0;
2059 /* Bug on AIX: read(1) can return 0 for a non-closed fd */
2060 pty_zeroread = c->isatty;
2063 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2065 if (!force && (c->io_ready & SSH_CHAN_IO_RFD) == 0)
2067 if ((avail = sshbuf_avail(c->input)) == 0)
2068 return 1; /* Shouldn't happen */
2071 * For "simple" channels (i.e. not datagram or filtered), we can
2072 * read directly to the channel buffer.
2074 if (!pty_zeroread && c->input_filter == NULL && !c->datagram) {
2075 /* Only OPEN channels have valid rwin */
2076 if (c->type == SSH_CHANNEL_OPEN) {
2077 if ((have = sshbuf_len(c->input)) >= c->remote_window)
2078 return 1; /* shouldn't happen */
2079 if (maxlen > c->remote_window - have)
2080 maxlen = c->remote_window - have;
2084 if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
2085 if (errno == EINTR || (!force &&
2086 (errno == EAGAIN || errno == EWOULDBLOCK)))
2088 debug2("channel %d: read failed rfd %d maxlen %zu: %s",
2089 c->self, c->rfd, maxlen, ssh_err(r));
2093 c->lastused = monotime();
2098 len = read(c->rfd, buf, sizeof(buf));
2099 /* fixup AIX zero-length read with errno set to look more like errors */
2100 if (pty_zeroread && len == 0 && errno != 0)
2102 if (len == -1 && (errno == EINTR ||
2103 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
2105 if (len < 0 || (!pty_zeroread && len == 0)) {
2106 debug2("channel %d: read<=0 rfd %d len %zd: %s",
2107 c->self, c->rfd, len,
2108 len == 0 ? "closed" : strerror(errno));
2110 if (c->type != SSH_CHANNEL_OPEN) {
2111 debug2("channel %d: not open", c->self);
2112 chan_mark_dead(ssh, c);
2115 chan_read_failed(ssh, c);
2119 c->lastused = monotime();
2120 if (c->input_filter != NULL) {
2121 if (c->input_filter(ssh, c, buf, len) == -1) {
2122 debug2("channel %d: filter stops", c->self);
2123 chan_read_failed(ssh, c);
2125 } else if (c->datagram) {
2126 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
2127 fatal_fr(r, "channel %i: put datagram", c->self);
2128 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2129 fatal_fr(r, "channel %i: put data", c->self);
2135 channel_handle_wfd(struct ssh *ssh, Channel *c)
2138 u_char *data = NULL, *buf; /* XXX const; need filter API change */
2139 size_t dlen, olen = 0;
2142 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2144 if (sshbuf_len(c->output) == 0)
2147 /* Send buffered output data to the socket. */
2148 olen = sshbuf_len(c->output);
2149 if (c->output_filter != NULL) {
2150 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2151 debug2("channel %d: filter stops", c->self);
2152 if (c->type != SSH_CHANNEL_OPEN)
2153 chan_mark_dead(ssh, c);
2155 chan_write_failed(ssh, c);
2158 } else if (c->datagram) {
2159 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2160 fatal_fr(r, "channel %i: get datagram", c->self);
2163 buf = data = sshbuf_mutable_ptr(c->output);
2164 dlen = sshbuf_len(c->output);
2168 /* ignore truncated writes, datagrams might get lost */
2169 len = write(c->wfd, buf, dlen);
2171 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2172 errno == EWOULDBLOCK))
2180 /* XXX: Later AIX versions can't push as much data to tty */
2182 dlen = MINIMUM(dlen, 8*1024);
2185 len = write(c->wfd, buf, dlen);
2187 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2191 if (c->type != SSH_CHANNEL_OPEN) {
2192 debug2("channel %d: not open", c->self);
2193 chan_mark_dead(ssh, c);
2196 chan_write_failed(ssh, c);
2200 c->lastused = monotime();
2201 #ifndef BROKEN_TCGETATTR_ICANON
2202 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2203 if (tcgetattr(c->wfd, &tio) == 0 &&
2204 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2206 * Simulate echo to reduce the impact of
2207 * traffic analysis. We need to match the
2208 * size of a SSH2_MSG_CHANNEL_DATA message
2209 * (4 byte channel id + buf)
2211 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2212 (r = sshpkt_send(ssh)) != 0)
2213 fatal_fr(r, "channel %i: ignore", c->self);
2216 #endif /* BROKEN_TCGETATTR_ICANON */
2217 if ((r = sshbuf_consume(c->output, len)) != 0)
2218 fatal_fr(r, "channel %i: consume", c->self);
2220 c->local_consumed += olen - sshbuf_len(c->output);
2226 channel_handle_efd_write(struct ssh *ssh, Channel *c)
2231 if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2233 if (sshbuf_len(c->extended) == 0)
2236 len = write(c->efd, sshbuf_ptr(c->extended),
2237 sshbuf_len(c->extended));
2238 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2239 if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2240 errno == EWOULDBLOCK))
2243 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2244 channel_close_fd(ssh, c, &c->efd);
2246 if ((r = sshbuf_consume(c->extended, len)) != 0)
2247 fatal_fr(r, "channel %i: consume", c->self);
2248 c->local_consumed += len;
2249 c->lastused = monotime();
2255 channel_handle_efd_read(struct ssh *ssh, Channel *c)
2257 char buf[CHAN_RBUF];
2261 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2263 if (!force && (c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2266 len = read(c->efd, buf, sizeof(buf));
2267 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2268 if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2269 errno == EWOULDBLOCK) && !force)))
2272 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2273 channel_close_fd(ssh, c, &c->efd);
2276 c->lastused = monotime();
2277 if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2278 debug3("channel %d: discard efd", c->self);
2279 else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2280 fatal_fr(r, "channel %i: append", c->self);
2285 channel_handle_efd(struct ssh *ssh, Channel *c)
2290 /** XXX handle drain efd, too */
2292 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2293 return channel_handle_efd_write(ssh, c);
2294 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2295 c->extended_usage == CHAN_EXTENDED_IGNORE)
2296 return channel_handle_efd_read(ssh, c);
2302 channel_check_window(struct ssh *ssh, Channel *c)
2306 if (c->type == SSH_CHANNEL_OPEN &&
2307 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2308 ((c->local_window_max - c->local_window >
2309 c->local_maxpacket*3) ||
2310 c->local_window < c->local_window_max/2) &&
2311 c->local_consumed > 0) {
2312 if (!c->have_remote_id)
2313 fatal_f("channel %d: no remote id", c->self);
2314 if ((r = sshpkt_start(ssh,
2315 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2316 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2317 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2318 (r = sshpkt_send(ssh)) != 0) {
2319 fatal_fr(r, "channel %i", c->self);
2321 debug2("channel %d: window %d sent adjust %d", c->self,
2322 c->local_window, c->local_consumed);
2323 c->local_window += c->local_consumed;
2324 c->local_consumed = 0;
2330 channel_post_open(struct ssh *ssh, Channel *c)
2332 channel_handle_rfd(ssh, c);
2333 channel_handle_wfd(ssh, c);
2334 channel_handle_efd(ssh, c);
2335 channel_check_window(ssh, c);
2339 read_mux(struct ssh *ssh, Channel *c, u_int need)
2341 char buf[CHAN_RBUF];
2346 if (sshbuf_len(c->input) < need) {
2347 rlen = need - sshbuf_len(c->input);
2348 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2349 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2350 return sshbuf_len(c->input);
2352 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2353 c->self, c->rfd, len);
2354 chan_read_failed(ssh, c);
2356 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2357 fatal_fr(r, "channel %i: append", c->self);
2359 return sshbuf_len(c->input);
2363 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2367 if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2369 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2375 * Don't not read past the precise end of packets to
2376 * avoid disrupting fd passing.
2378 if (read_mux(ssh, c, 4) < 4) /* read header */
2380 /* XXX sshbuf_peek_u32 */
2381 need = PEEK_U32(sshbuf_ptr(c->input));
2382 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2383 if (need > CHANNEL_MUX_MAX_PACKET) {
2384 debug2("channel %d: packet too big %u > %u",
2385 c->self, CHANNEL_MUX_MAX_PACKET, need);
2386 chan_rcvd_oclose(ssh, c);
2389 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2391 if (c->mux_rcb(ssh, c) != 0) {
2392 debug("channel %d: mux_rcb failed", c->self);
2393 chan_mark_dead(ssh, c);
2399 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2404 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2406 if (sshbuf_len(c->output) == 0)
2409 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2410 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2413 chan_mark_dead(ssh, c);
2416 if ((r = sshbuf_consume(c->output, len)) != 0)
2417 fatal_fr(r, "channel %i: consume", c->self);
2421 channel_post_mux_client(struct ssh *ssh, Channel *c)
2423 channel_post_mux_client_read(ssh, c);
2424 channel_post_mux_client_write(ssh, c);
2428 channel_post_mux_listener(struct ssh *ssh, Channel *c)
2431 struct sockaddr_storage addr;
2437 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2440 debug("multiplexing control connection");
2443 * Accept connection on control socket
2445 memset(&addr, 0, sizeof(addr));
2446 addrlen = sizeof(addr);
2447 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2449 error_f("accept: %s", strerror(errno));
2450 if (errno == EMFILE || errno == ENFILE)
2451 c->notbefore = monotime() + 1;
2455 if (getpeereid(newsock, &euid, &egid) == -1) {
2456 error_f("getpeereid failed: %s", strerror(errno));
2460 if ((euid != 0) && (getuid() != euid)) {
2461 error("multiplex uid mismatch: peer euid %u != uid %u",
2462 (u_int)euid, (u_int)getuid());
2466 nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
2467 newsock, newsock, -1, c->local_window_max,
2468 c->local_maxpacket, 0, "mux-control", 1);
2469 nc->mux_rcb = c->mux_rcb;
2470 debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2471 /* establish state */
2472 nc->mux_rcb(ssh, nc);
2473 /* mux state transitions must not elicit protocol messages */
2474 nc->flags |= CHAN_LOCAL;
2478 channel_handler_init(struct ssh_channels *sc)
2480 chan_fn **pre, **post;
2482 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2483 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2484 fatal_f("allocation failed");
2486 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2487 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2488 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2489 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2490 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2491 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2492 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2493 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2494 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2495 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2496 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2497 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2498 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2500 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2501 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2502 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2503 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2504 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2505 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2506 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2507 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2508 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2509 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2510 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2511 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2513 sc->channel_pre = pre;
2514 sc->channel_post = post;
2517 /* gc dead channels */
2519 channel_garbage_collect(struct ssh *ssh, Channel *c)
2523 if (c->detach_user != NULL) {
2524 if (!chan_is_dead(ssh, c, c->detach_close))
2527 debug2("channel %d: gc: notify user", c->self);
2528 c->detach_user(ssh, c->self, 0, NULL);
2529 /* if we still have a callback */
2530 if (c->detach_user != NULL)
2532 debug2("channel %d: gc: user detached", c->self);
2534 if (!chan_is_dead(ssh, c, 1))
2536 debug2("channel %d: garbage collecting", c->self);
2537 channel_free(ssh, c);
2540 enum channel_table { CHAN_PRE, CHAN_POST };
2543 channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
2545 struct ssh_channels *sc = ssh->chanctxt;
2546 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2552 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2553 c = sc->channels[i];
2556 /* Try to keep IO going while rekeying */
2557 if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
2560 if (table == CHAN_PRE)
2565 if (ftab[c->type] != NULL) {
2566 if (table == CHAN_PRE &&
2567 c->type == SSH_CHANNEL_OPEN &&
2568 c->inactive_deadline != 0 && c->lastused != 0 &&
2569 now >= c->lastused + c->inactive_deadline) {
2570 /* channel closed for inactivity */
2571 verbose("channel %d: closing after %u seconds "
2572 "of inactivity", c->self,
2573 c->inactive_deadline);
2574 channel_force_close(ssh, c, 1);
2575 } else if (c->notbefore <= now) {
2576 /* Run handlers that are not paused. */
2577 (*ftab[c->type])(ssh, c);
2578 /* inactivity timeouts must interrupt poll() */
2579 if (timeout != NULL &&
2580 c->type == SSH_CHANNEL_OPEN &&
2582 c->inactive_deadline != 0) {
2583 ptimeout_deadline_monotime(timeout,
2584 c->lastused + c->inactive_deadline);
2586 } else if (timeout != NULL) {
2588 * Arrange for poll() wakeup when channel pause
2591 ptimeout_deadline_monotime(timeout,
2595 channel_garbage_collect(ssh, c);
2600 * Create sockets before preparing IO.
2601 * This is necessary for things that need to happen after reading
2602 * the network-input but need to be completed before IO event setup, e.g.
2603 * because they may create new channels.
2606 channel_before_prepare_io(struct ssh *ssh)
2608 struct ssh_channels *sc = ssh->chanctxt;
2612 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2613 c = sc->channels[i];
2616 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2617 channel_before_prepare_io_rdynamic(ssh, c);
2622 dump_channel_poll(const char *func, const char *what, Channel *c,
2623 u_int pollfd_offset, struct pollfd *pfd)
2625 #ifdef DEBUG_CHANNEL_POLL
2626 debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2627 "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2628 "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2629 c->rfd, c->wfd, c->efd, c->sock,
2630 c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2631 c->io_want, c->io_ready,
2632 pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2636 /* Prepare pollfd entries for a single channel */
2638 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2639 struct pollfd *pfd, u_int npfd)
2641 u_int ev, p = *next_pollfd;
2646 /* Shouldn't happen */
2647 fatal_f("channel %d: bad pfd offset %u (max %u)",
2650 c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2654 * This is a special case, since c->rfd might be the same as
2655 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2660 if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2663 if (c->wfd == c->rfd) {
2664 if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2668 if (c->efd == c->rfd) {
2669 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2671 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2675 if (c->sock == c->rfd) {
2676 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2678 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2681 /* Pack a pfd entry if any event armed for this fd */
2686 dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2690 /* prepare c->wfd if wanting IO and not already handled above */
2691 if (c->wfd != -1 && c->rfd != c->wfd) {
2693 if ((c->io_want & SSH_CHAN_IO_WFD))
2695 /* Pack a pfd entry if any event armed for this fd */
2700 dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2704 /* prepare c->efd if wanting IO and not already handled above */
2705 if (c->efd != -1 && c->rfd != c->efd) {
2707 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2709 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2711 /* Pack a pfd entry if any event armed for this fd */
2716 dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2720 /* prepare c->sock if wanting IO and not already handled above */
2721 if (c->sock != -1 && c->rfd != c->sock) {
2723 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2725 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2727 /* Pack a pfd entry if any event armed for this fd */
2730 pfd[p].fd = c->sock;
2732 dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2739 /* * Allocate/prepare poll structure */
2741 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2742 u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
2744 struct ssh_channels *sc = ssh->chanctxt;
2745 u_int i, oalloc, p, npfd = npfd_reserved;
2747 channel_before_prepare_io(ssh); /* might create a new channel */
2748 /* clear out I/O flags from last poll */
2749 for (i = 0; i < sc->channels_alloc; i++) {
2750 if (sc->channels[i] == NULL)
2752 sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2754 /* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2755 if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2756 fatal_f("too many channels"); /* shouldn't happen */
2757 npfd += sc->channels_alloc * 4;
2758 if (npfd > *npfd_allocp) {
2759 *pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2760 npfd, sizeof(**pfdp));
2761 *npfd_allocp = npfd;
2763 *npfd_activep = npfd_reserved;
2764 oalloc = sc->channels_alloc;
2766 channel_handler(ssh, CHAN_PRE, timeout);
2768 if (oalloc != sc->channels_alloc) {
2769 /* shouldn't happen */
2770 fatal_f("channels_alloc changed during CHAN_PRE "
2771 "(was %u, now %u)", oalloc, sc->channels_alloc);
2774 /* Prepare pollfd */
2776 for (i = 0; i < sc->channels_alloc; i++)
2777 channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2782 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2783 const char *what, u_int revents_mask, u_int ready)
2785 struct pollfd *pfd = &pfds[p];
2789 if (p == -1 || (u_int)p >= npfd)
2790 fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2791 dump_channel_poll(__func__, what, c, p, pfd);
2792 if (pfd->fd != fd) {
2793 fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2794 "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2795 c->rfd, c->wfd, c->efd, c->sock);
2797 if ((pfd->revents & POLLNVAL) != 0) {
2798 fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2799 c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2801 if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2802 c->io_ready |= ready & c->io_want;
2806 * After poll, perform any appropriate operations for channels which have
2810 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2812 struct ssh_channels *sc = ssh->chanctxt;
2817 #ifdef DEBUG_CHANNEL_POLL
2818 for (p = 0; p < (int)npfd; p++) {
2819 if (pfd[p].revents == 0)
2821 debug_f("pfd[%u].fd %d rev 0x%04x",
2822 p, pfd[p].fd, pfd[p].revents);
2826 /* Convert pollfd into c->io_ready */
2827 for (i = 0; i < sc->channels_alloc; i++) {
2828 c = sc->channels[i];
2831 /* if rfd is shared with efd/sock then wfd should be too */
2832 if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2833 (c->rfd == c->efd || c->rfd == c->sock)) {
2834 /* Shouldn't happen */
2835 fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2836 c->self, c->rfd, c->wfd, c->efd, c->sock);
2839 /* rfd, potentially shared with wfd, efd and sock */
2840 if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2841 fd_ready(c, p, pfd, npfd, c->rfd,
2842 "rfd", POLLIN, SSH_CHAN_IO_RFD);
2843 if (c->rfd == c->wfd) {
2844 fd_ready(c, p, pfd, npfd, c->wfd,
2845 "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2847 if (c->rfd == c->efd) {
2848 fd_ready(c, p, pfd, npfd, c->efd,
2849 "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2850 fd_ready(c, p, pfd, npfd, c->efd,
2851 "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2853 if (c->rfd == c->sock) {
2854 fd_ready(c, p, pfd, npfd, c->sock,
2855 "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2856 fd_ready(c, p, pfd, npfd, c->sock,
2857 "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2859 dump_channel_poll(__func__, "rfd", c, p, pfd);
2862 if (c->wfd != -1 && c->wfd != c->rfd &&
2863 (p = c->pfds[1]) != -1) {
2864 fd_ready(c, p, pfd, npfd, c->wfd,
2865 "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2866 dump_channel_poll(__func__, "wfd", c, p, pfd);
2869 if (c->efd != -1 && c->efd != c->rfd &&
2870 (p = c->pfds[2]) != -1) {
2871 fd_ready(c, p, pfd, npfd, c->efd,
2872 "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2873 fd_ready(c, p, pfd, npfd, c->efd,
2874 "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2875 dump_channel_poll(__func__, "efd", c, p, pfd);
2878 if (c->sock != -1 && c->sock != c->rfd &&
2879 (p = c->pfds[3]) != -1) {
2880 fd_ready(c, p, pfd, npfd, c->sock,
2881 "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2882 fd_ready(c, p, pfd, npfd, c->sock,
2883 "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2884 dump_channel_poll(__func__, "sock", c, p, pfd);
2887 channel_handler(ssh, CHAN_POST, NULL);
2891 * Enqueue data for channels with open or draining c->input.
2894 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2900 if ((len = sshbuf_len(c->input)) == 0) {
2901 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2903 * input-buffer is empty and read-socket shutdown:
2904 * tell peer, that we will not send more data:
2906 * hack for extended data: delay EOF if EFD still
2909 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2910 debug2("channel %d: "
2911 "ibuf_empty delayed efd %d/(%zu)",
2912 c->self, c->efd, sshbuf_len(c->extended));
2914 chan_ibuf_empty(ssh, c);
2919 if (!c->have_remote_id)
2920 fatal_f("channel %d: no remote id", c->self);
2923 /* Check datagram will fit; drop if not */
2924 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2925 fatal_fr(r, "channel %i: get datagram", c->self);
2927 * XXX this does tail-drop on the datagram queue which is
2928 * usually suboptimal compared to head-drop. Better to have
2929 * backpressure at read time? (i.e. read + discard)
2931 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2932 debug("channel %d: datagram too big", c->self);
2936 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2937 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2938 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2939 (r = sshpkt_send(ssh)) != 0)
2940 fatal_fr(r, "channel %i: send datagram", c->self);
2941 c->remote_window -= plen;
2945 /* Enqueue packet for buffered data. */
2946 if (len > c->remote_window)
2947 len = c->remote_window;
2948 if (len > c->remote_maxpacket)
2949 len = c->remote_maxpacket;
2952 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2953 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2954 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2955 (r = sshpkt_send(ssh)) != 0)
2956 fatal_fr(r, "channel %i: send data", c->self);
2957 if ((r = sshbuf_consume(c->input, len)) != 0)
2958 fatal_fr(r, "channel %i: consume", c->self);
2959 c->remote_window -= len;
2963 * Enqueue data for channels with open c->extended in read mode.
2966 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2971 if ((len = sshbuf_len(c->extended)) == 0)
2974 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2975 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2976 if (len > c->remote_window)
2977 len = c->remote_window;
2978 if (len > c->remote_maxpacket)
2979 len = c->remote_maxpacket;
2982 if (!c->have_remote_id)
2983 fatal_f("channel %d: no remote id", c->self);
2984 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2985 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2986 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2987 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2988 (r = sshpkt_send(ssh)) != 0)
2989 fatal_fr(r, "channel %i: data", c->self);
2990 if ((r = sshbuf_consume(c->extended, len)) != 0)
2991 fatal_fr(r, "channel %i: consume", c->self);
2992 c->remote_window -= len;
2993 debug2("channel %d: sent ext data %zu", c->self, len);
2996 /* If there is data to send to the connection, enqueue some of it now. */
2998 channel_output_poll(struct ssh *ssh)
3000 struct ssh_channels *sc = ssh->chanctxt;
3004 for (i = 0; i < sc->channels_alloc; i++) {
3005 c = sc->channels[i];
3010 * We are only interested in channels that can have buffered
3013 if (c->type != SSH_CHANNEL_OPEN)
3015 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
3016 /* XXX is this true? */
3017 debug3("channel %d: will not send data after close",
3022 /* Get the amount of buffered data for this channel. */
3023 if (c->istate == CHAN_INPUT_OPEN ||
3024 c->istate == CHAN_INPUT_WAIT_DRAIN)
3025 channel_output_poll_input_open(ssh, c);
3026 /* Send extended data, i.e. stderr */
3027 if (!(c->flags & CHAN_EOF_SENT) &&
3028 c->extended_usage == CHAN_EXTENDED_READ)
3029 channel_output_poll_extended_read(ssh, c);
3033 /* -- mux proxy support */
3036 * When multiplexing channel messages for mux clients we have to deal
3037 * with downstream messages from the mux client and upstream messages
3038 * from the ssh server:
3039 * 1) Handling downstream messages is straightforward and happens
3040 * in channel_proxy_downstream():
3041 * - We forward all messages (mostly) unmodified to the server.
3042 * - However, in order to route messages from upstream to the correct
3043 * downstream client, we have to replace the channel IDs used by the
3044 * mux clients with a unique channel ID because the mux clients might
3045 * use conflicting channel IDs.
3046 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
3047 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
3048 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
3049 * with the newly allocated channel ID.
3050 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
3051 * channels and processed by channel_proxy_upstream(). The local channel ID
3052 * is then translated back to the original mux client ID.
3053 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
3054 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
3055 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
3056 * downstream mux client are removed.
3057 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
3058 * requires more work, because they are not addressed to a specific
3059 * channel. E.g. client_request_forwarded_tcpip() needs to figure
3060 * out whether the request is addressed to the local client or a
3061 * specific downstream client based on the listen-address/port.
3062 * 6) Agent and X11-Forwarding have a similar problem and are currently
3063 * not supported as the matching session/channel cannot be identified
3068 * receive packets from downstream mux clients:
3069 * channel callback fired on read from mux client, creates
3070 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
3071 * on channel creation.
3074 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
3077 struct sshbuf *original = NULL, *modified = NULL;
3079 char *ctype = NULL, *listen_host = NULL;
3083 u_int id, remote_id, listen_port;
3085 /* sshbuf_dump(downstream->input, stderr); */
3086 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
3088 error_fr(r, "parse");
3092 error_f("short message");
3096 /* skip padlen + type */
3099 if (ssh_packet_log_type(type))
3100 debug3_f("channel %u: down->up: type %u",
3101 downstream->self, type);
3104 case SSH2_MSG_CHANNEL_OPEN:
3105 if ((original = sshbuf_from(cp, have)) == NULL ||
3106 (modified = sshbuf_new()) == NULL) {
3110 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
3111 (r = sshbuf_get_u32(original, &id)) != 0) {
3112 error_fr(r, "parse");
3115 c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3116 -1, -1, -1, 0, 0, 0, ctype, 1);
3117 c->mux_ctx = downstream; /* point to mux client */
3118 c->mux_downstream_id = id; /* original downstream id */
3119 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
3120 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3121 (r = sshbuf_putb(modified, original)) != 0) {
3122 error_fr(r, "compose");
3123 channel_free(ssh, c);
3127 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3129 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
3130 * need to parse 'remote_id' instead of 'ctype'.
3132 if ((original = sshbuf_from(cp, have)) == NULL ||
3133 (modified = sshbuf_new()) == NULL) {
3137 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
3138 (r = sshbuf_get_u32(original, &id)) != 0) {
3139 error_fr(r, "parse");
3142 c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3143 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3144 c->mux_ctx = downstream; /* point to mux client */
3145 c->mux_downstream_id = id;
3146 c->remote_id = remote_id;
3147 c->have_remote_id = 1;
3148 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3149 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3150 (r = sshbuf_putb(modified, original)) != 0) {
3151 error_fr(r, "compose");
3152 channel_free(ssh, c);
3156 case SSH2_MSG_GLOBAL_REQUEST:
3157 if ((original = sshbuf_from(cp, have)) == NULL) {
3161 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3162 error_fr(r, "parse");
3165 if (strcmp(ctype, "tcpip-forward") != 0) {
3166 error_f("unsupported request %s", ctype);
3169 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3170 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3171 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3172 error_fr(r, "parse");
3175 if (listen_port > 65535) {
3176 error_f("tcpip-forward for %s: bad port %u",
3177 listen_host, listen_port);
3180 /* Record that connection to this host/port is permitted. */
3181 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3182 listen_host, NULL, (int)listen_port, downstream);
3185 case SSH2_MSG_CHANNEL_CLOSE:
3188 remote_id = PEEK_U32(cp);
3189 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3190 if (c->flags & CHAN_CLOSE_RCVD)
3191 channel_free(ssh, c);
3193 c->flags |= CHAN_CLOSE_SENT;
3198 if ((r = sshpkt_start(ssh, type)) != 0 ||
3199 (r = sshpkt_putb(ssh, modified)) != 0 ||
3200 (r = sshpkt_send(ssh)) != 0) {
3201 error_fr(r, "send");
3205 if ((r = sshpkt_start(ssh, type)) != 0 ||
3206 (r = sshpkt_put(ssh, cp, have)) != 0 ||
3207 (r = sshpkt_send(ssh)) != 0) {
3208 error_fr(r, "send");
3216 sshbuf_free(original);
3217 sshbuf_free(modified);
3222 * receive packets from upstream server and de-multiplex packets
3223 * to correct downstream:
3224 * implemented as a helper for channel input handlers,
3225 * replaces local (proxy) channel ID with downstream channel ID.
3228 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3230 struct sshbuf *b = NULL;
3231 Channel *downstream;
3232 const u_char *cp = NULL;
3237 * When receiving packets from the peer we need to check whether we
3238 * need to forward the packets to the mux client. In this case we
3239 * restore the original channel id and keep track of CLOSE messages,
3240 * so we can cleanup the channel.
3242 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3244 if ((downstream = c->mux_ctx) == NULL)
3247 case SSH2_MSG_CHANNEL_CLOSE:
3248 case SSH2_MSG_CHANNEL_DATA:
3249 case SSH2_MSG_CHANNEL_EOF:
3250 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3251 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3252 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3253 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3254 case SSH2_MSG_CHANNEL_SUCCESS:
3255 case SSH2_MSG_CHANNEL_FAILURE:
3256 case SSH2_MSG_CHANNEL_REQUEST:
3259 debug2_f("channel %u: unsupported type %u", c->self, type);
3262 if ((b = sshbuf_new()) == NULL) {
3263 error_f("alloc reply");
3266 /* get remaining payload (after id) */
3267 cp = sshpkt_ptr(ssh, &len);
3269 error_f("no packet");
3272 /* translate id and send to muxclient */
3273 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
3274 (r = sshbuf_put_u8(b, type)) != 0 ||
3275 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3276 (r = sshbuf_put(b, cp, len)) != 0 ||
3277 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3278 error_fr(r, "compose muxclient");
3281 /* sshbuf_dump(b, stderr); */
3282 if (ssh_packet_log_type(type))
3283 debug3_f("channel %u: up->down: type %u", c->self, type);
3287 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3288 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3289 if (cp && len > 4) {
3290 c->remote_id = PEEK_U32(cp);
3291 c->have_remote_id = 1;
3294 case SSH2_MSG_CHANNEL_CLOSE:
3295 if (c->flags & CHAN_CLOSE_SENT)
3296 channel_free(ssh, c);
3298 c->flags |= CHAN_CLOSE_RCVD;
3305 /* -- protocol input */
3307 /* Parse a channel ID from the current packet */
3309 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3314 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3315 error_r(r, "%s: parse id", where);
3316 ssh_packet_disconnect(ssh, "Invalid %s message", what);
3319 error_r(r, "%s: bad channel id %u", where, id);
3320 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3325 /* Lookup a channel from an ID in the current packet */
3327 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3329 int id = channel_parse_id(ssh, where, what);
3332 if ((c = channel_lookup(ssh, id)) == NULL) {
3333 ssh_packet_disconnect(ssh,
3334 "%s packet referred to nonexistent channel %d", what, id);
3340 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3343 size_t data_len, win_len;
3344 Channel *c = channel_from_packet_id(ssh, __func__, "data");
3347 if (channel_proxy_upstream(c, type, seq, ssh))
3350 /* Ignore any data for non-open channels (might happen on close) */
3351 if (c->type != SSH_CHANNEL_OPEN &&
3352 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3353 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3354 c->type != SSH_CHANNEL_X11_OPEN)
3358 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3359 (r = sshpkt_get_end(ssh)) != 0)
3360 fatal_fr(r, "channel %i: get data", c->self);
3364 win_len += 4; /* string length header */
3367 * The sending side reduces its window as it sends data, so we
3368 * must 'fake' consumption of the data in order to ensure that window
3369 * updates are sent back. Otherwise the connection might deadlock.
3371 if (c->ostate != CHAN_OUTPUT_OPEN) {
3372 c->local_window -= win_len;
3373 c->local_consumed += win_len;
3377 if (win_len > c->local_maxpacket) {
3378 logit("channel %d: rcvd big packet %zu, maxpack %u",
3379 c->self, win_len, c->local_maxpacket);
3382 if (win_len > c->local_window) {
3383 logit("channel %d: rcvd too much data %zu, win %u",
3384 c->self, win_len, c->local_window);
3387 c->local_window -= win_len;
3390 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3391 fatal_fr(r, "channel %i: append datagram", c->self);
3392 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3393 fatal_fr(r, "channel %i: append data", c->self);
3399 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3404 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3407 if (channel_proxy_upstream(c, type, seq, ssh))
3409 if (c->type != SSH_CHANNEL_OPEN) {
3410 logit("channel %d: ext data for non open", c->self);
3413 if (c->flags & CHAN_EOF_RCVD) {
3414 if (ssh->compat & SSH_BUG_EXTEOF)
3415 debug("channel %d: accepting ext data after eof",
3418 ssh_packet_disconnect(ssh, "Received extended_data "
3419 "after EOF on channel %d.", c->self);
3422 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3423 error_fr(r, "parse tcode");
3424 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3427 c->extended_usage != CHAN_EXTENDED_WRITE ||
3428 tcode != SSH2_EXTENDED_DATA_STDERR) {
3429 logit("channel %d: bad ext data", c->self);
3432 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3433 (r = sshpkt_get_end(ssh)) != 0) {
3434 error_fr(r, "parse data");
3435 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3438 if (data_len > c->local_window) {
3439 logit("channel %d: rcvd too much extended_data %zu, win %u",
3440 c->self, data_len, c->local_window);
3443 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3444 /* XXX sshpkt_getb? */
3445 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3446 error_fr(r, "append");
3447 c->local_window -= data_len;
3452 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3454 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3457 if ((r = sshpkt_get_end(ssh)) != 0) {
3458 error_fr(r, "parse data");
3459 ssh_packet_disconnect(ssh, "Invalid ieof message");
3462 if (channel_proxy_upstream(c, type, seq, ssh))
3464 chan_rcvd_ieof(ssh, c);
3466 /* XXX force input close */
3467 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3468 debug("channel %d: FORCE input drain", c->self);
3469 c->istate = CHAN_INPUT_WAIT_DRAIN;
3470 if (sshbuf_len(c->input) == 0)
3471 chan_ibuf_empty(ssh, c);
3477 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3479 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3482 if (channel_proxy_upstream(c, type, seq, ssh))
3484 if ((r = sshpkt_get_end(ssh)) != 0) {
3485 error_fr(r, "parse data");
3486 ssh_packet_disconnect(ssh, "Invalid oclose message");
3488 chan_rcvd_oclose(ssh, c);
3493 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3495 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3496 u_int32_t remote_window, remote_maxpacket;
3499 if (channel_proxy_upstream(c, type, seq, ssh))
3501 if (c->type != SSH_CHANNEL_OPENING)
3502 ssh_packet_disconnect(ssh, "Received open confirmation for "
3503 "non-opening channel %d.", c->self);
3505 * Record the remote channel number and mark that the channel
3508 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3509 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3510 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3511 (r = sshpkt_get_end(ssh)) != 0) {
3512 error_fr(r, "window/maxpacket");
3513 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3516 c->have_remote_id = 1;
3517 c->remote_window = remote_window;
3518 c->remote_maxpacket = remote_maxpacket;
3519 c->type = SSH_CHANNEL_OPEN;
3520 if (c->open_confirm) {
3521 debug2_f("channel %d: callback start", c->self);
3522 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3523 debug2_f("channel %d: callback done", c->self);
3525 c->lastused = monotime();
3526 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3527 c->remote_window, c->remote_maxpacket);
3532 reason2txt(int reason)
3535 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3536 return "administratively prohibited";
3537 case SSH2_OPEN_CONNECT_FAILED:
3538 return "connect failed";
3539 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3540 return "unknown channel type";
3541 case SSH2_OPEN_RESOURCE_SHORTAGE:
3542 return "resource shortage";
3544 return "unknown reason";
3548 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3550 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3555 if (channel_proxy_upstream(c, type, seq, ssh))
3557 if (c->type != SSH_CHANNEL_OPENING)
3558 ssh_packet_disconnect(ssh, "Received open failure for "
3559 "non-opening channel %d.", c->self);
3560 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3561 error_fr(r, "parse reason");
3562 ssh_packet_disconnect(ssh, "Invalid open failure message");
3565 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3566 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3567 (r = sshpkt_get_end(ssh)) != 0) {
3568 error_fr(r, "parse msg/lang");
3569 ssh_packet_disconnect(ssh, "Invalid open failure message");
3571 logit("channel %d: open failed: %s%s%s", c->self,
3572 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3574 if (c->open_confirm) {
3575 debug2_f("channel %d: callback start", c->self);
3576 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3577 debug2_f("channel %d: callback done", c->self);
3579 /* Schedule the channel for cleanup/deletion. */
3580 chan_mark_dead(ssh, c);
3585 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3587 int id = channel_parse_id(ssh, __func__, "window adjust");
3593 if ((c = channel_lookup(ssh, id)) == NULL) {
3594 logit("Received window adjust for non-open channel %d.", id);
3598 if (channel_proxy_upstream(c, type, seq, ssh))
3600 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3601 (r = sshpkt_get_end(ssh)) != 0) {
3602 error_fr(r, "parse adjust");
3603 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3605 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3606 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3607 fatal("channel %d: adjust %u overflows remote window %u",
3608 c->self, adjust, c->remote_window);
3610 c->remote_window = new_rwin;
3615 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3617 int id = channel_parse_id(ssh, __func__, "status confirm");
3619 struct channel_confirm *cc;
3621 /* Reset keepalive timeout */
3622 ssh_packet_set_alive_timeouts(ssh, 0);
3624 debug2_f("type %d id %d", type, id);
3626 if ((c = channel_lookup(ssh, id)) == NULL) {
3627 logit_f("%d: unknown", id);
3630 if (channel_proxy_upstream(c, type, seq, ssh))
3632 if (sshpkt_get_end(ssh) != 0)
3633 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3634 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3636 cc->cb(ssh, type, c, cc->ctx);
3637 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3638 freezero(cc, sizeof(*cc));
3642 /* -- tcp forwarding */
3645 channel_set_af(struct ssh *ssh, int af)
3647 ssh->chanctxt->IPv4or6 = af;
3652 * Determine whether or not a port forward listens to loopback, the
3653 * specified address or wildcard. On the client, a specified bind
3654 * address will always override gateway_ports. On the server, a
3655 * gateway_ports of 1 (``yes'') will override the client's specification
3656 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3657 * will bind to whatever address the client asked for.
3659 * Special-case listen_addrs are:
3661 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3662 * "" (empty string), "*" -> wildcard v4/v6
3663 * "localhost" -> loopback v4/v6
3664 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3667 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3668 int is_client, struct ForwardOptions *fwd_opts)
3670 const char *addr = NULL;
3673 if (listen_addr == NULL) {
3674 /* No address specified: default to gateway_ports setting */
3675 if (fwd_opts->gateway_ports)
3677 } else if (fwd_opts->gateway_ports || is_client) {
3678 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3679 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3680 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3681 (!is_client && fwd_opts->gateway_ports == 1)) {
3684 * Notify client if they requested a specific listen
3685 * address and it was overridden.
3687 if (*listen_addr != '\0' &&
3688 strcmp(listen_addr, "0.0.0.0") != 0 &&
3689 strcmp(listen_addr, "*") != 0) {
3690 ssh_packet_send_debug(ssh,
3691 "Forwarding listen address "
3692 "\"%s\" overridden by server "
3693 "GatewayPorts", listen_addr);
3695 } else if (strcmp(listen_addr, "localhost") != 0 ||
3696 strcmp(listen_addr, "127.0.0.1") == 0 ||
3697 strcmp(listen_addr, "::1") == 0) {
3699 * Accept explicit localhost address when
3700 * GatewayPorts=yes. The "localhost" hostname is
3701 * deliberately skipped here so it will listen on all
3702 * available local address families.
3706 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3707 strcmp(listen_addr, "::1") == 0) {
3709 * If a specific IPv4/IPv6 localhost address has been
3710 * requested then accept it even if gateway_ports is in
3711 * effect. This allows the client to prefer IPv4 or IPv6.
3715 if (wildcardp != NULL)
3716 *wildcardp = wildcard;
3721 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3722 struct Forward *fwd, int *allocated_listen_port,
3723 struct ForwardOptions *fwd_opts)
3726 int sock, r, success = 0, wildcard = 0, is_client;
3727 struct addrinfo hints, *ai, *aitop;
3728 const char *host, *addr;
3729 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3732 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3734 if (is_client && fwd->connect_path != NULL) {
3735 host = fwd->connect_path;
3737 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3738 fwd->listen_host : fwd->connect_host;
3740 error("No forward host name.");
3743 if (strlen(host) >= NI_MAXHOST) {
3744 error("Forward host name too long.");
3749 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3750 addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3751 is_client, fwd_opts);
3752 debug3_f("type %d wildcard %d addr %s", type, wildcard,
3753 (addr == NULL) ? "NULL" : addr);
3756 * getaddrinfo returns a loopback address if the hostname is
3757 * set to NULL and hints.ai_flags is not AI_PASSIVE
3759 memset(&hints, 0, sizeof(hints));
3760 hints.ai_family = ssh->chanctxt->IPv4or6;
3761 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3762 hints.ai_socktype = SOCK_STREAM;
3763 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3764 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3766 /* This really shouldn't happen */
3767 ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3768 ssh_gai_strerror(r));
3770 error_f("getaddrinfo(%.64s): %s", addr,
3771 ssh_gai_strerror(r));
3775 if (allocated_listen_port != NULL)
3776 *allocated_listen_port = 0;
3777 for (ai = aitop; ai; ai = ai->ai_next) {
3778 switch (ai->ai_family) {
3780 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3784 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3791 * If allocating a port for -R forwards, then use the
3792 * same port for all address families.
3794 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3795 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3796 *allocated_listen_port > 0)
3797 *lport_p = htons(*allocated_listen_port);
3799 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3800 strport, sizeof(strport),
3801 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3802 error_f("getnameinfo failed");
3805 /* Create a port to listen for the host. */
3806 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3808 /* this is no error since kernel may not support ipv6 */
3809 verbose("socket [%s]:%s: %.100s", ntop, strport,
3814 set_reuseaddr(sock);
3815 if (ai->ai_family == AF_INET6)
3816 sock_set_v6only(sock);
3818 debug("Local forwarding listening on %s port %s.",
3821 /* Bind the socket to the address. */
3822 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3824 * address can be in if use ipv6 address is
3828 error("bind [%s]:%s: %.100s",
3829 ntop, strport, strerror(errno));
3831 verbose("bind [%s]:%s: %.100s",
3832 ntop, strport, strerror(errno));
3837 /* Start listening for connections on the socket. */
3838 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3839 error("listen [%s]:%s: %.100s", ntop, strport,
3846 * fwd->listen_port == 0 requests a dynamically allocated port -
3847 * record what we got.
3849 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3850 fwd->listen_port == 0 &&
3851 allocated_listen_port != NULL &&
3852 *allocated_listen_port == 0) {
3853 *allocated_listen_port = get_local_port(sock);
3854 debug("Allocated listen port %d",
3855 *allocated_listen_port);
3858 /* Allocate a channel number for the socket. */
3859 c = channel_new(ssh, "port-listener", type, sock, sock, -1,
3860 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3861 0, "port listener", 1);
3862 c->path = xstrdup(host);
3863 c->host_port = fwd->connect_port;
3864 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3865 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3866 !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3867 c->listening_port = *allocated_listen_port;
3869 c->listening_port = fwd->listen_port;
3873 error_f("cannot listen to port: %d", fwd->listen_port);
3874 freeaddrinfo(aitop);
3879 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3880 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3882 struct sockaddr_un sunaddr;
3889 case SSH_CHANNEL_UNIX_LISTENER:
3890 if (fwd->connect_path != NULL) {
3891 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3892 error("Local connecting path too long: %s",
3896 path = fwd->connect_path;
3897 port = PORT_STREAMLOCAL;
3899 if (fwd->connect_host == NULL) {
3900 error("No forward host name.");
3903 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3904 error("Forward host name too long.");
3907 path = fwd->connect_host;
3908 port = fwd->connect_port;
3911 case SSH_CHANNEL_RUNIX_LISTENER:
3912 path = fwd->listen_path;
3913 port = PORT_STREAMLOCAL;
3916 error_f("unexpected channel type %d", type);
3920 if (fwd->listen_path == NULL) {
3921 error("No forward path name.");
3924 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3925 error("Local listening path too long: %s", fwd->listen_path);
3929 debug3_f("type %d path %s", type, fwd->listen_path);
3931 /* Start a Unix domain listener. */
3932 omask = umask(fwd_opts->streamlocal_bind_mask);
3933 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3934 fwd_opts->streamlocal_bind_unlink);
3939 debug("Local forwarding listening on path %s.", fwd->listen_path);
3941 /* Allocate a channel number for the socket. */
3942 c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
3943 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3944 0, "unix listener", 1);
3945 c->path = xstrdup(path);
3946 c->host_port = port;
3947 c->listening_port = PORT_STREAMLOCAL;
3948 c->listening_addr = xstrdup(fwd->listen_path);
3953 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3954 const char *host, u_short port)
3959 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3960 Channel *c = ssh->chanctxt->channels[i];
3961 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3963 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3964 debug2_f("close channel %d", i);
3965 channel_free(ssh, c);
3974 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3979 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3980 Channel *c = ssh->chanctxt->channels[i];
3981 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3983 if (c->path == NULL)
3985 if (strcmp(c->path, path) == 0) {
3986 debug2_f("close channel %d", i);
3987 channel_free(ssh, c);
3996 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3998 if (fwd->listen_path != NULL) {
3999 return channel_cancel_rport_listener_streamlocal(ssh,
4002 return channel_cancel_rport_listener_tcpip(ssh,
4003 fwd->listen_host, fwd->listen_port);
4008 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
4009 const char *lhost, u_short lport, int cport,
4010 struct ForwardOptions *fwd_opts)
4014 const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
4016 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4017 Channel *c = ssh->chanctxt->channels[i];
4018 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
4020 if (c->listening_port != lport)
4022 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
4023 /* skip dynamic forwardings */
4024 if (c->host_port == 0)
4027 if (c->host_port != cport)
4030 if ((c->listening_addr == NULL && addr != NULL) ||
4031 (c->listening_addr != NULL && addr == NULL))
4033 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
4034 debug2_f("close channel %d", i);
4035 channel_free(ssh, c);
4044 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
4050 error_f("no path specified.");
4054 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4055 Channel *c = ssh->chanctxt->channels[i];
4056 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
4058 if (c->listening_addr == NULL)
4060 if (strcmp(c->listening_addr, path) == 0) {
4061 debug2_f("close channel %d", i);
4062 channel_free(ssh, c);
4071 channel_cancel_lport_listener(struct ssh *ssh,
4072 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
4074 if (fwd->listen_path != NULL) {
4075 return channel_cancel_lport_listener_streamlocal(ssh,
4078 return channel_cancel_lport_listener_tcpip(ssh,
4079 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
4083 /* protocol local port fwd, used by ssh */
4085 channel_setup_local_fwd_listener(struct ssh *ssh,
4086 struct Forward *fwd, struct ForwardOptions *fwd_opts)
4088 if (fwd->listen_path != NULL) {
4089 return channel_setup_fwd_listener_streamlocal(ssh,
4090 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
4092 return channel_setup_fwd_listener_tcpip(ssh,
4093 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
4097 /* Matches a remote forwarding permission against a requested forwarding */
4099 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
4104 /* XXX add ACLs for streamlocal */
4105 if (fwd->listen_path != NULL)
4108 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
4111 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
4112 allowed_open->listen_port != fwd->listen_port)
4115 /* Match hostnames case-insensitively */
4116 lhost = xstrdup(fwd->listen_host);
4118 ret = match_pattern(lhost, allowed_open->listen_host);
4124 /* Checks whether a requested remote forwarding is permitted */
4126 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
4128 struct ssh_channels *sc = ssh->chanctxt;
4129 struct permission_set *pset = &sc->remote_perms;
4130 u_int i, permit, permit_adm = 1;
4131 struct permission *perm;
4133 /* XXX apply GatewayPorts override before checking? */
4135 permit = pset->all_permitted;
4137 for (i = 0; i < pset->num_permitted_user; i++) {
4138 perm = &pset->permitted_user[i];
4139 if (remote_open_match(perm, fwd)) {
4146 if (pset->num_permitted_admin > 0) {
4148 for (i = 0; i < pset->num_permitted_admin; i++) {
4149 perm = &pset->permitted_admin[i];
4150 if (remote_open_match(perm, fwd)) {
4157 return permit && permit_adm;
4160 /* protocol v2 remote port fwd, used by sshd */
4162 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4163 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4165 if (!check_rfwd_permission(ssh, fwd)) {
4166 ssh_packet_send_debug(ssh, "port forwarding refused");
4167 if (fwd->listen_path != NULL)
4168 /* XXX always allowed, see remote_open_match() */
4169 logit("Received request from %.100s port %d to "
4170 "remote forward to path \"%.100s\", "
4171 "but the request was denied.",
4172 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4174 else if(fwd->listen_host != NULL)
4175 logit("Received request from %.100s port %d to "
4176 "remote forward to host %.100s port %d, "
4177 "but the request was denied.",
4178 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4179 fwd->listen_host, fwd->listen_port );
4181 logit("Received request from %.100s port %d to remote "
4182 "forward, but the request was denied.",
4183 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4186 if (fwd->listen_path != NULL) {
4187 return channel_setup_fwd_listener_streamlocal(ssh,
4188 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4190 return channel_setup_fwd_listener_tcpip(ssh,
4191 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4197 * Translate the requested rfwd listen host to something usable for
4201 channel_rfwd_bind_host(const char *listen_host)
4203 if (listen_host == NULL) {
4205 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4212 * Initiate forwarding of connections to port "port" on remote host through
4213 * the secure channel to host:port from local side.
4214 * Returns handle (index) for updating the dynamic listen port with
4215 * channel_update_permission().
4218 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4220 int r, success = 0, idx = -1;
4221 const char *host_to_connect, *listen_host, *listen_path;
4222 int port_to_connect, listen_port;
4224 /* Send the forward request to the remote side. */
4225 if (fwd->listen_path != NULL) {
4226 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4227 (r = sshpkt_put_cstring(ssh,
4228 "streamlocal-forward@openssh.com")) != 0 ||
4229 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4230 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4231 (r = sshpkt_send(ssh)) != 0 ||
4232 (r = ssh_packet_write_wait(ssh)) != 0)
4233 fatal_fr(r, "request streamlocal");
4235 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4236 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4237 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4238 (r = sshpkt_put_cstring(ssh,
4239 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4240 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4241 (r = sshpkt_send(ssh)) != 0 ||
4242 (r = ssh_packet_write_wait(ssh)) != 0)
4243 fatal_fr(r, "request tcpip-forward");
4245 /* Assume that server accepts the request */
4248 /* Record that connection to this host/port is permitted. */
4249 host_to_connect = listen_host = listen_path = NULL;
4250 port_to_connect = listen_port = 0;
4251 if (fwd->connect_path != NULL) {
4252 host_to_connect = fwd->connect_path;
4253 port_to_connect = PORT_STREAMLOCAL;
4255 host_to_connect = fwd->connect_host;
4256 port_to_connect = fwd->connect_port;
4258 if (fwd->listen_path != NULL) {
4259 listen_path = fwd->listen_path;
4260 listen_port = PORT_STREAMLOCAL;
4262 listen_host = fwd->listen_host;
4263 listen_port = fwd->listen_port;
4265 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4266 host_to_connect, port_to_connect,
4267 listen_host, listen_path, listen_port, NULL);
4273 open_match(struct permission *allowed_open, const char *requestedhost,
4276 if (allowed_open->host_to_connect == NULL)
4278 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4279 allowed_open->port_to_connect != requestedport)
4281 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4282 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4288 * Note that in the listen host/port case
4289 * we don't support FWD_PERMIT_ANY_PORT and
4290 * need to translate between the configured-host (listen_host)
4291 * and what we've sent to the remote server (channel_rfwd_bind_host)
4294 open_listen_match_tcpip(struct permission *allowed_open,
4295 const char *requestedhost, u_short requestedport, int translate)
4297 const char *allowed_host;
4299 if (allowed_open->host_to_connect == NULL)
4301 if (allowed_open->listen_port != requestedport)
4303 if (!translate && allowed_open->listen_host == NULL &&
4304 requestedhost == NULL)
4306 allowed_host = translate ?
4307 channel_rfwd_bind_host(allowed_open->listen_host) :
4308 allowed_open->listen_host;
4309 if (allowed_host == NULL || requestedhost == NULL ||
4310 strcmp(allowed_host, requestedhost) != 0)
4316 open_listen_match_streamlocal(struct permission *allowed_open,
4317 const char *requestedpath)
4319 if (allowed_open->host_to_connect == NULL)
4321 if (allowed_open->listen_port != PORT_STREAMLOCAL)
4323 if (allowed_open->listen_path == NULL ||
4324 strcmp(allowed_open->listen_path, requestedpath) != 0)
4330 * Request cancellation of remote forwarding of connection host:port from
4334 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4335 const char *host, u_short port)
4337 struct ssh_channels *sc = ssh->chanctxt;
4338 struct permission_set *pset = &sc->local_perms;
4341 struct permission *perm = NULL;
4343 for (i = 0; i < pset->num_permitted_user; i++) {
4344 perm = &pset->permitted_user[i];
4345 if (open_listen_match_tcpip(perm, host, port, 0))
4350 debug_f("requested forward not found");
4353 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4354 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4355 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4356 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4357 (r = sshpkt_put_u32(ssh, port)) != 0 ||
4358 (r = sshpkt_send(ssh)) != 0)
4359 fatal_fr(r, "send cancel");
4361 fwd_perm_clear(perm); /* unregister */
4367 * Request cancellation of remote forwarding of Unix domain socket
4368 * path from local side.
4371 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4373 struct ssh_channels *sc = ssh->chanctxt;
4374 struct permission_set *pset = &sc->local_perms;
4377 struct permission *perm = NULL;
4379 for (i = 0; i < pset->num_permitted_user; i++) {
4380 perm = &pset->permitted_user[i];
4381 if (open_listen_match_streamlocal(perm, path))
4386 debug_f("requested forward not found");
4389 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4390 (r = sshpkt_put_cstring(ssh,
4391 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4392 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4393 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4394 (r = sshpkt_send(ssh)) != 0)
4395 fatal_fr(r, "send cancel");
4397 fwd_perm_clear(perm); /* unregister */
4403 * Request cancellation of remote forwarding of a connection from local side.
4406 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4408 if (fwd->listen_path != NULL) {
4409 return channel_request_rforward_cancel_streamlocal(ssh,
4412 return channel_request_rforward_cancel_tcpip(ssh,
4414 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4419 * Permits opening to any host/port if permitted_user[] is empty. This is
4420 * usually called by the server, because the user could connect to any port
4421 * anyway, and the server has no way to know but to trust the client anyway.
4424 channel_permit_all(struct ssh *ssh, int where)
4426 struct permission_set *pset = permission_set_get(ssh, where);
4428 if (pset->num_permitted_user == 0)
4429 pset->all_permitted = 1;
4433 * Permit the specified host/port for forwarding.
4436 channel_add_permission(struct ssh *ssh, int who, int where,
4437 char *host, int port)
4439 int local = where == FORWARD_LOCAL;
4440 struct permission_set *pset = permission_set_get(ssh, where);
4442 debug("allow %s forwarding to host %s port %d",
4443 fwd_ident(who, where), host, port);
4445 * Remote forwards set listen_host/port, local forwards set
4446 * host/port_to_connect.
4448 permission_set_add(ssh, who, where,
4449 local ? host : 0, local ? port : 0,
4450 local ? NULL : host, NULL, local ? 0 : port, NULL);
4451 pset->all_permitted = 0;
4455 * Administratively disable forwarding.
4458 channel_disable_admin(struct ssh *ssh, int where)
4460 channel_clear_permission(ssh, FORWARD_ADM, where);
4461 permission_set_add(ssh, FORWARD_ADM, where,
4462 NULL, 0, NULL, NULL, 0, NULL);
4466 * Clear a list of permitted opens.
4469 channel_clear_permission(struct ssh *ssh, int who, int where)
4471 struct permission **permp;
4474 permission_set_get_array(ssh, who, where, &permp, &npermp);
4475 *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4480 * Update the listen port for a dynamic remote forward, after
4481 * the actual 'newport' has been allocated. If 'newport' < 0 is
4482 * passed then they entry will be invalidated.
4485 channel_update_permission(struct ssh *ssh, int idx, int newport)
4487 struct permission_set *pset = &ssh->chanctxt->local_perms;
4489 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4490 debug_f("index out of range: %d num_permitted_user %d",
4491 idx, pset->num_permitted_user);
4494 debug("%s allowed port %d for forwarding to host %s port %d",
4495 newport > 0 ? "Updating" : "Removing",
4497 pset->permitted_user[idx].host_to_connect,
4498 pset->permitted_user[idx].port_to_connect);
4500 fwd_perm_clear(&pset->permitted_user[idx]);
4502 pset->permitted_user[idx].listen_port =
4503 (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4507 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4509 permitopen_port(const char *p)
4513 if (strcmp(p, "*") == 0)
4514 return FWD_PERMIT_ANY_PORT;
4515 if ((port = a2port(p)) > 0)
4520 /* Try to start non-blocking connect to next host in cctx list */
4522 connect_next(struct channel_connect *cctx)
4524 int sock, saved_errno;
4525 struct sockaddr_un *sunaddr;
4526 char ntop[NI_MAXHOST];
4527 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4529 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4530 switch (cctx->ai->ai_family) {
4532 /* unix:pathname instead of host:port */
4533 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4534 strlcpy(ntop, "unix", sizeof(ntop));
4535 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4539 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4540 ntop, sizeof(ntop), strport, sizeof(strport),
4541 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4542 error_f("getnameinfo failed");
4549 debug_f("start for host %.100s ([%.100s]:%s)",
4550 cctx->host, ntop, strport);
4551 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4552 cctx->ai->ai_protocol)) == -1) {
4553 if (cctx->ai->ai_next == NULL)
4554 error("socket: %.100s", strerror(errno));
4556 verbose("socket: %.100s", strerror(errno));
4559 if (set_nonblock(sock) == -1)
4560 fatal_f("set_nonblock(%d)", sock);
4561 if (connect(sock, cctx->ai->ai_addr,
4562 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4563 debug_f("host %.100s ([%.100s]:%s): %.100s",
4564 cctx->host, ntop, strport, strerror(errno));
4565 saved_errno = errno;
4567 errno = saved_errno;
4568 continue; /* fail -- try next */
4570 if (cctx->ai->ai_family != AF_UNIX)
4572 debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
4573 cctx->host, ntop, strport, sock);
4574 cctx->ai = cctx->ai->ai_next;
4581 channel_connect_ctx_free(struct channel_connect *cctx)
4585 if (cctx->aitop->ai_family == AF_UNIX)
4588 freeaddrinfo(cctx->aitop);
4590 memset(cctx, 0, sizeof(*cctx));
4594 * Return connecting socket to remote host:port or local socket path,
4595 * passing back the failure reason if appropriate.
4598 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4599 char *ctype, char *rname, struct channel_connect *cctx,
4600 int *reason, const char **errmsg)
4602 struct addrinfo hints;
4605 char strport[NI_MAXSERV];
4607 if (port == PORT_STREAMLOCAL) {
4608 struct sockaddr_un *sunaddr;
4609 struct addrinfo *ai;
4611 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4612 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4617 * Fake up a struct addrinfo for AF_UNIX connections.
4618 * channel_connect_ctx_free() must check ai_family
4619 * and use free() not freeaddirinfo() for AF_UNIX.
4621 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4622 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4623 ai->ai_addr = (struct sockaddr *)(ai + 1);
4624 ai->ai_addrlen = sizeof(*sunaddr);
4625 ai->ai_family = AF_UNIX;
4626 ai->ai_socktype = socktype;
4627 ai->ai_protocol = PF_UNSPEC;
4628 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4629 sunaddr->sun_family = AF_UNIX;
4630 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4633 memset(&hints, 0, sizeof(hints));
4634 hints.ai_family = ssh->chanctxt->IPv4or6;
4635 hints.ai_socktype = socktype;
4636 snprintf(strport, sizeof strport, "%d", port);
4637 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4640 *errmsg = ssh_gai_strerror(gaierr);
4642 *reason = SSH2_OPEN_CONNECT_FAILED;
4643 error("connect_to %.100s: unknown host (%s)", name,
4644 ssh_gai_strerror(gaierr));
4649 cctx->host = xstrdup(name);
4651 cctx->ai = cctx->aitop;
4653 if ((sock = connect_next(cctx)) == -1) {
4654 error("connect to %.100s port %d failed: %s",
4655 name, port, strerror(errno));
4662 /* Return CONNECTING channel to remote host:port or local socket path */
4664 connect_to(struct ssh *ssh, const char *host, int port,
4665 char *ctype, char *rname)
4667 struct channel_connect cctx;
4671 memset(&cctx, 0, sizeof(cctx));
4672 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4675 channel_connect_ctx_free(&cctx);
4678 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4679 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4680 c->host_port = port;
4681 c->path = xstrdup(host);
4682 c->connect_ctx = cctx;
4688 * returns either the newly connected channel or the downstream channel
4689 * that needs to deal with this connection.
4692 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4693 u_short listen_port, char *ctype, char *rname)
4695 struct ssh_channels *sc = ssh->chanctxt;
4696 struct permission_set *pset = &sc->local_perms;
4698 struct permission *perm;
4700 for (i = 0; i < pset->num_permitted_user; i++) {
4701 perm = &pset->permitted_user[i];
4702 if (open_listen_match_tcpip(perm,
4703 listen_host, listen_port, 1)) {
4704 if (perm->downstream)
4705 return perm->downstream;
4706 if (perm->port_to_connect == 0)
4707 return rdynamic_connect_prepare(ssh,
4709 return connect_to(ssh,
4710 perm->host_to_connect, perm->port_to_connect,
4714 error("WARNING: Server requests forwarding for unknown listen_port %d",
4720 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4721 char *ctype, char *rname)
4723 struct ssh_channels *sc = ssh->chanctxt;
4724 struct permission_set *pset = &sc->local_perms;
4726 struct permission *perm;
4728 for (i = 0; i < pset->num_permitted_user; i++) {
4729 perm = &pset->permitted_user[i];
4730 if (open_listen_match_streamlocal(perm, path)) {
4731 return connect_to(ssh,
4732 perm->host_to_connect, perm->port_to_connect,
4736 error("WARNING: Server requests forwarding for unknown path %.100s",
4741 /* Check if connecting to that port is permitted and connect. */
4743 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4744 char *ctype, char *rname, int *reason, const char **errmsg)
4746 struct ssh_channels *sc = ssh->chanctxt;
4747 struct permission_set *pset = &sc->local_perms;
4748 struct channel_connect cctx;
4750 u_int i, permit, permit_adm = 1;
4752 struct permission *perm;
4754 permit = pset->all_permitted;
4756 for (i = 0; i < pset->num_permitted_user; i++) {
4757 perm = &pset->permitted_user[i];
4758 if (open_match(perm, host, port)) {
4765 if (pset->num_permitted_admin > 0) {
4767 for (i = 0; i < pset->num_permitted_admin; i++) {
4768 perm = &pset->permitted_admin[i];
4769 if (open_match(perm, host, port)) {
4776 if (!permit || !permit_adm) {
4777 logit("Received request from %.100s port %d to connect to "
4778 "host %.100s port %d, but the request was denied.",
4779 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4781 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4785 memset(&cctx, 0, sizeof(cctx));
4786 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4787 &cctx, reason, errmsg);
4789 channel_connect_ctx_free(&cctx);
4793 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4794 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4795 c->host_port = port;
4796 c->path = xstrdup(host);
4797 c->connect_ctx = cctx;
4802 /* Check if connecting to that path is permitted and connect. */
4804 channel_connect_to_path(struct ssh *ssh, const char *path,
4805 char *ctype, char *rname)
4807 struct ssh_channels *sc = ssh->chanctxt;
4808 struct permission_set *pset = &sc->local_perms;
4809 u_int i, permit, permit_adm = 1;
4810 struct permission *perm;
4812 permit = pset->all_permitted;
4814 for (i = 0; i < pset->num_permitted_user; i++) {
4815 perm = &pset->permitted_user[i];
4816 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4823 if (pset->num_permitted_admin > 0) {
4825 for (i = 0; i < pset->num_permitted_admin; i++) {
4826 perm = &pset->permitted_admin[i];
4827 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4834 if (!permit || !permit_adm) {
4835 logit("Received request to connect to path %.100s, "
4836 "but the request was denied.", path);
4839 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4843 channel_send_window_changes(struct ssh *ssh)
4845 struct ssh_channels *sc = ssh->chanctxt;
4850 for (i = 0; i < sc->channels_alloc; i++) {
4851 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4852 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4854 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4856 channel_request_start(ssh, i, "window-change", 0);
4857 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4858 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4859 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4860 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4861 (r = sshpkt_send(ssh)) != 0)
4862 fatal_fr(r, "channel %u; send window-change", i);
4866 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4868 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4873 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4874 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4879 * We need to open the channel before we have a FD,
4880 * so that we can get SOCKS header from peer.
4882 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4883 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4884 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4885 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4886 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4887 fatal_fr(r, "channel %i; confirm", c->self);
4891 /* Return CONNECTING socket to remote host:port or local socket path */
4893 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4895 struct ssh_channels *sc = ssh->chanctxt;
4896 struct permission_set *pset = &sc->local_perms;
4897 struct permission *perm;
4898 struct channel_connect cctx;
4899 u_int i, permit_adm = 1;
4902 if (pset->num_permitted_admin > 0) {
4904 for (i = 0; i < pset->num_permitted_admin; i++) {
4905 perm = &pset->permitted_admin[i];
4906 if (open_match(perm, c->path, c->host_port)) {
4913 debug_f("requested forward not permitted");
4917 memset(&cctx, 0, sizeof(cctx));
4918 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4919 NULL, &cctx, NULL, NULL);
4921 channel_connect_ctx_free(&cctx);
4923 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4924 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4925 c->connect_ctx = cctx;
4926 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4931 /* -- X11 forwarding */
4934 * Creates an internet domain socket for listening for X11 connections.
4935 * Returns 0 and a suitable display number for the DISPLAY variable
4936 * stored in display_numberp , or -1 if an error occurs.
4939 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4940 int x11_use_localhost, int single_connection,
4941 u_int *display_numberp, int **chanids)
4944 int display_number, sock;
4946 struct addrinfo hints, *ai, *aitop;
4947 char strport[NI_MAXSERV];
4948 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4950 if (chanids == NULL)
4953 for (display_number = x11_display_offset;
4954 display_number < MAX_DISPLAYS;
4956 port = 6000 + display_number;
4957 memset(&hints, 0, sizeof(hints));
4958 hints.ai_family = ssh->chanctxt->IPv4or6;
4959 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4960 hints.ai_socktype = SOCK_STREAM;
4961 snprintf(strport, sizeof strport, "%d", port);
4962 if ((gaierr = getaddrinfo(NULL, strport,
4963 &hints, &aitop)) != 0) {
4964 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4967 for (ai = aitop; ai; ai = ai->ai_next) {
4968 if (ai->ai_family != AF_INET &&
4969 ai->ai_family != AF_INET6)
4971 sock = socket(ai->ai_family, ai->ai_socktype,
4974 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4976 && (errno != EPFNOSUPPORT)
4979 error("socket: %.100s", strerror(errno));
4980 freeaddrinfo(aitop);
4983 debug("x11_create_display_inet: Socket family %d not supported",
4988 if (ai->ai_family == AF_INET6)
4989 sock_set_v6only(sock);
4990 if (x11_use_localhost)
4991 set_reuseaddr(sock);
4992 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4993 debug2_f("bind port %d: %.100s", port,
4996 for (n = 0; n < num_socks; n++)
5001 socks[num_socks++] = sock;
5002 if (num_socks == NUM_SOCKS)
5005 freeaddrinfo(aitop);
5009 if (display_number >= MAX_DISPLAYS) {
5010 error("Failed to allocate internet-domain X11 display socket.");
5013 /* Start listening for connections on the socket. */
5014 for (n = 0; n < num_socks; n++) {
5016 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
5017 error("listen: %.100s", strerror(errno));
5023 /* Allocate a channel for each socket. */
5024 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
5025 for (n = 0; n < num_socks; n++) {
5027 nc = channel_new(ssh, "x11-listener",
5028 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
5029 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
5030 0, "X11 inet listener", 1);
5031 nc->single_connection = single_connection;
5032 (*chanids)[n] = nc->self;
5036 /* Return the display number for the DISPLAY environment variable. */
5037 *display_numberp = display_number;
5042 connect_local_xsocket_path(const char *pathname)
5045 struct sockaddr_un addr;
5047 sock = socket(AF_UNIX, SOCK_STREAM, 0);
5049 error("socket: %.100s", strerror(errno));
5050 memset(&addr, 0, sizeof(addr));
5051 addr.sun_family = AF_UNIX;
5052 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
5053 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
5056 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
5061 connect_local_xsocket(u_int dnr)
5064 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
5065 return connect_local_xsocket_path(buf);
5070 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
5074 if (strlcpy(path, display, pathlen) >= pathlen) {
5075 error("%s: display path too long", __func__);
5078 if (display[0] != '/')
5080 if (stat(path, &sbuf) == 0) {
5083 char *dot = strrchr(path, '.');
5086 if (stat(path, &sbuf) == 0) {
5096 x11_connect_display(struct ssh *ssh)
5098 u_int display_number;
5099 const char *display;
5100 char buf[1024], *cp;
5101 struct addrinfo hints, *ai, *aitop;
5102 char strport[NI_MAXSERV];
5103 int gaierr, sock = 0;
5105 /* Try to open a socket for the local X server. */
5106 display = getenv("DISPLAY");
5108 error("DISPLAY not set.");
5112 * Now we decode the value of the DISPLAY variable and make a
5113 * connection to the real X server.
5117 /* Check if display is a path to a socket (as set by launchd). */
5119 char path[PATH_MAX];
5121 if (is_path_to_xsocket(display, path, sizeof(path))) {
5122 debug("x11_connect_display: $DISPLAY is launchd");
5124 /* Create a socket. */
5125 sock = connect_local_xsocket_path(path);
5129 /* OK, we now have a connection to the display. */
5135 * Check if it is a unix domain socket. Unix domain displays are in
5136 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
5138 if (strncmp(display, "unix:", 5) == 0 ||
5139 display[0] == ':') {
5140 /* Connect to the unix domain socket. */
5141 if (sscanf(strrchr(display, ':') + 1, "%u",
5142 &display_number) != 1) {
5143 error("Could not parse display number from DISPLAY: "
5147 /* Create a socket. */
5148 sock = connect_local_xsocket(display_number);
5152 /* OK, we now have a connection to the display. */
5156 * Connect to an inet socket. The DISPLAY value is supposedly
5157 * hostname:d[.s], where hostname may also be numeric IP address.
5159 strlcpy(buf, display, sizeof(buf));
5160 cp = strchr(buf, ':');
5162 error("Could not find ':' in DISPLAY: %.100s", display);
5167 * buf now contains the host name. But first we parse the
5170 if (sscanf(cp + 1, "%u", &display_number) != 1) {
5171 error("Could not parse display number from DISPLAY: %.100s",
5176 /* Look up the host address */
5177 memset(&hints, 0, sizeof(hints));
5178 hints.ai_family = ssh->chanctxt->IPv4or6;
5179 hints.ai_socktype = SOCK_STREAM;
5180 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5181 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5182 error("%.100s: unknown host. (%s)", buf,
5183 ssh_gai_strerror(gaierr));
5186 for (ai = aitop; ai; ai = ai->ai_next) {
5187 /* Create a socket. */
5188 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5190 debug2("socket: %.100s", strerror(errno));
5193 /* Connect it to the display. */
5194 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5195 debug2("connect %.100s port %u: %.100s", buf,
5196 6000 + display_number, strerror(errno));
5203 freeaddrinfo(aitop);
5205 error("connect %.100s port %u: %.100s", buf,
5206 6000 + display_number, strerror(errno));
5214 * Requests forwarding of X11 connections, generates fake authentication
5215 * data, and enables authentication spoofing.
5216 * This should be called in the client only.
5219 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5220 const char *disp, const char *proto, const char *data, int want_reply)
5222 struct ssh_channels *sc = ssh->chanctxt;
5223 u_int data_len = (u_int) strlen(data) / 2;
5227 int r, screen_number;
5229 if (sc->x11_saved_display == NULL)
5230 sc->x11_saved_display = xstrdup(disp);
5231 else if (strcmp(disp, sc->x11_saved_display) != 0) {
5232 error("x11_request_forwarding_with_spoofing: different "
5233 "$DISPLAY already forwarded");
5237 cp = strchr(disp, ':');
5239 cp = strchr(cp, '.');
5241 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5245 if (sc->x11_saved_proto == NULL) {
5246 /* Save protocol name. */
5247 sc->x11_saved_proto = xstrdup(proto);
5249 /* Extract real authentication data. */
5250 sc->x11_saved_data = xmalloc(data_len);
5251 for (i = 0; i < data_len; i++) {
5252 if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5253 fatal("x11_request_forwarding: bad "
5254 "authentication data: %.100s", data);
5256 sc->x11_saved_data[i] = value;
5258 sc->x11_saved_data_len = data_len;
5260 /* Generate fake data of the same length. */
5261 sc->x11_fake_data = xmalloc(data_len);
5262 arc4random_buf(sc->x11_fake_data, data_len);
5263 sc->x11_fake_data_len = data_len;
5266 /* Convert the fake data into hex. */
5267 new_data = tohex(sc->x11_fake_data, data_len);
5269 /* Send the request packet. */
5270 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5271 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5272 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5273 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5274 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5275 (r = sshpkt_send(ssh)) != 0 ||
5276 (r = ssh_packet_write_wait(ssh)) != 0)
5277 fatal_fr(r, "send x11-req");