1 /* $OpenBSD: channels.c,v 1.379 2018/02/05 05:36:49 tb Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
70 #include "openbsd-compat/sys-queue.h"
84 #include "pathnames.h"
86 /* -- agent forwarding */
89 /* -- tcp forwarding */
90 /* special-case port number meaning allow any port */
91 #define FWD_PERMIT_ANY_PORT 0
93 /* special-case wildcard meaning allow any host */
94 #define FWD_PERMIT_ANY_HOST "*"
96 /* -- X11 forwarding */
97 /* Maximum number of fake X11 displays to try. */
98 #define MAX_DISPLAYS 1000
101 * Data structure for storing which hosts are permitted for forward requests.
102 * The local sides of any remote forwards are stored in this array to prevent
103 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
104 * network (which might be behind a firewall).
106 /* XXX: streamlocal wants a path instead of host:port */
107 /* Overload host_to_connect; we could just make this match Forward */
108 /* XXX - can we use listen_host instead of listen_path? */
110 char *host_to_connect; /* Connect to 'host'. */
111 int port_to_connect; /* Connect to 'port'. */
112 char *listen_host; /* Remote side should listen address. */
113 char *listen_path; /* Remote side should listen path. */
114 int listen_port; /* Remote side should listen port. */
115 Channel *downstream; /* Downstream mux*/
118 typedef void chan_fn(struct ssh *, Channel *c,
119 fd_set *readset, fd_set *writeset);
121 /* Master structure for channels state */
122 struct ssh_channels {
124 * Pointer to an array containing all allocated channels. The array
125 * is dynamically extended as needed.
130 * Size of the channel array. All slots of the array must always be
131 * initialized (at least the type field); unused slots set to NULL
133 u_int channels_alloc;
136 * Maximum file descriptor value used in any of the channels. This is
137 * updated in channel_new.
142 * 'channel_pre*' are called just before select() to add any bits
143 * relevant to channels in the select bitmasks.
145 * 'channel_post*': perform any appropriate operations for
146 * channels which have events pending.
148 chan_fn **channel_pre;
149 chan_fn **channel_post;
151 /* -- tcp forwarding */
153 /* List of all permitted host/port pairs to connect by the user. */
154 ForwardPermission *permitted_opens;
156 /* List of all permitted host/port pairs to connect by the admin. */
157 ForwardPermission *permitted_adm_opens;
160 * Number of permitted host/port pairs in the array permitted by
163 u_int num_permitted_opens;
166 * Number of permitted host/port pair in the array permitted by
169 u_int num_adm_permitted_opens;
172 * If this is true, all opens are permitted. This is the case on
173 * the server on which we have to trust the client anyway, and the
174 * user could do anything after logging in anyway.
176 int all_opens_permitted;
178 /* -- X11 forwarding */
180 /* Saved X11 local (client) display. */
181 char *x11_saved_display;
183 /* Saved X11 authentication protocol name. */
184 char *x11_saved_proto;
186 /* Saved X11 authentication data. This is the real data. */
187 char *x11_saved_data;
188 u_int x11_saved_data_len;
190 /* Deadline after which all X11 connections are refused */
191 u_int x11_refuse_time;
194 * Fake X11 authentication data. This is what the server will be
195 * sending us; we should replace any occurrences of this by the
198 u_char *x11_fake_data;
199 u_int x11_fake_data_len;
201 /* AF_UNSPEC or AF_INET or AF_INET6 */
206 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
207 static const char *channel_rfwd_bind_host(const char *listen_host);
209 /* non-blocking connect helpers */
210 static int connect_next(struct channel_connect *);
211 static void channel_connect_ctx_free(struct channel_connect *);
212 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
213 static int rdynamic_connect_finish(struct ssh *, Channel *);
216 static void channel_handler_init(struct ssh_channels *sc);
218 /* -- channel core */
221 channel_init_channels(struct ssh *ssh)
223 struct ssh_channels *sc;
225 if ((sc = calloc(1, sizeof(*sc))) == NULL ||
226 (sc->channel_pre = calloc(SSH_CHANNEL_MAX_TYPE,
227 sizeof(*sc->channel_pre))) == NULL ||
228 (sc->channel_post = calloc(SSH_CHANNEL_MAX_TYPE,
229 sizeof(*sc->channel_post))) == NULL)
230 fatal("%s: allocation failed", __func__);
231 sc->channels_alloc = 10;
232 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
233 sc->IPv4or6 = AF_UNSPEC;
234 channel_handler_init(sc);
240 channel_by_id(struct ssh *ssh, int id)
244 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
245 logit("%s: %d: bad id", __func__, id);
248 c = ssh->chanctxt->channels[id];
250 logit("%s: %d: bad id: channel free", __func__, id);
257 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
262 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
263 c = ssh->chanctxt->channels[i];
264 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
271 * Returns the channel if it is allowed to receive protocol messages.
272 * Private channels, like listening sockets, may not receive messages.
275 channel_lookup(struct ssh *ssh, int id)
279 if ((c = channel_by_id(ssh, id)) == NULL)
283 case SSH_CHANNEL_X11_OPEN:
284 case SSH_CHANNEL_LARVAL:
285 case SSH_CHANNEL_CONNECTING:
286 case SSH_CHANNEL_DYNAMIC:
287 case SSH_CHANNEL_RDYNAMIC_OPEN:
288 case SSH_CHANNEL_RDYNAMIC_FINISH:
289 case SSH_CHANNEL_OPENING:
290 case SSH_CHANNEL_OPEN:
291 case SSH_CHANNEL_ABANDONED:
292 case SSH_CHANNEL_MUX_PROXY:
295 logit("Non-public channel %d, type %d.", id, c->type);
300 * Register filedescriptors for a channel, used when allocating a channel or
301 * when the channel consumer/producer is ready, e.g. shell exec'd
304 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
305 int extusage, int nonblock, int is_tty)
307 struct ssh_channels *sc = ssh->chanctxt;
309 /* Update the maximum file descriptor value. */
310 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
311 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
312 sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
315 fcntl(rfd, F_SETFD, FD_CLOEXEC);
316 if (wfd != -1 && wfd != rfd)
317 fcntl(wfd, F_SETFD, FD_CLOEXEC);
318 if (efd != -1 && efd != rfd && efd != wfd)
319 fcntl(efd, F_SETFD, FD_CLOEXEC);
323 c->sock = (rfd == wfd) ? rfd : -1;
325 c->extended_usage = extusage;
327 if ((c->isatty = is_tty) != 0)
328 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
330 /* XXX: Later AIX versions can't push as much data to tty */
331 c->wfd_isatty = is_tty || isatty(c->wfd);
334 /* enable nonblocking mode */
346 * Allocate a new channel object and set its type and socket. This will cause
347 * remote_name to be freed.
350 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
351 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
353 struct ssh_channels *sc = ssh->chanctxt;
357 /* Try to find a free slot where to put the new channel. */
358 for (i = 0; i < sc->channels_alloc; i++) {
359 if (sc->channels[i] == NULL) {
360 /* Found a free slot. */
365 if (i >= sc->channels_alloc) {
367 * There are no free slots. Take last+1 slot and expand
370 found = sc->channels_alloc;
371 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
372 fatal("%s: internal error: channels_alloc %d too big",
373 __func__, sc->channels_alloc);
374 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
375 sc->channels_alloc + 10, sizeof(*sc->channels));
376 sc->channels_alloc += 10;
377 debug2("channel: expanding %d", sc->channels_alloc);
379 /* Initialize and return new channel. */
380 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
381 if ((c->input = sshbuf_new()) == NULL ||
382 (c->output = sshbuf_new()) == NULL ||
383 (c->extended = sshbuf_new()) == NULL)
384 fatal("%s: sshbuf_new failed", __func__);
385 c->ostate = CHAN_OUTPUT_OPEN;
386 c->istate = CHAN_INPUT_OPEN;
387 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
391 c->local_window = window;
392 c->local_window_max = window;
393 c->local_maxpacket = maxpack;
394 c->remote_name = xstrdup(remote_name);
396 c->delayed = 1; /* prevent call to channel_post handler */
397 TAILQ_INIT(&c->status_confirms);
398 debug("channel %d: new [%s]", found, remote_name);
403 channel_find_maxfd(struct ssh_channels *sc)
409 for (i = 0; i < sc->channels_alloc; i++) {
412 max = MAXIMUM(max, c->rfd);
413 max = MAXIMUM(max, c->wfd);
414 max = MAXIMUM(max, c->efd);
417 sc->channel_max_fd = max;
421 channel_close_fd(struct ssh *ssh, int *fdp)
423 struct ssh_channels *sc = ssh->chanctxt;
424 int ret = 0, fd = *fdp;
429 if (fd == sc->channel_max_fd)
430 channel_find_maxfd(sc);
435 /* Close all channel fd/socket. */
437 channel_close_fds(struct ssh *ssh, Channel *c)
439 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
441 channel_close_fd(ssh, &c->sock);
443 channel_close_fd(ssh, &c->rfd);
444 if (wfd != sock && wfd != rfd)
445 channel_close_fd(ssh, &c->wfd);
446 if (efd != sock && efd != rfd && efd != wfd)
447 channel_close_fd(ssh, &c->efd);
451 fwd_perm_clear(ForwardPermission *fp)
453 free(fp->host_to_connect);
454 free(fp->listen_host);
455 free(fp->listen_path);
456 bzero(fp, sizeof(*fp));
459 enum { FWDPERM_USER, FWDPERM_ADMIN };
462 fwd_perm_list_add(struct ssh *ssh, int which,
463 const char *host_to_connect, int port_to_connect,
464 const char *listen_host, const char *listen_path, int listen_port,
467 ForwardPermission **fpl;
472 fpl = &ssh->chanctxt->permitted_opens;
473 nfpl = &ssh->chanctxt->num_permitted_opens;
476 fpl = &ssh->chanctxt->permitted_adm_opens;
477 nfpl = &ssh->chanctxt->num_adm_permitted_opens;
480 fatal("%s: invalid list %d", __func__, which);
483 if (*nfpl >= INT_MAX)
484 fatal("%s: overflow", __func__);
486 *fpl = xrecallocarray(*fpl, *nfpl, *nfpl + 1, sizeof(**fpl));
488 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
489 (*fpl)[n].host_to_connect = MAYBE_DUP(host_to_connect);
490 (*fpl)[n].port_to_connect = port_to_connect;
491 (*fpl)[n].listen_host = MAYBE_DUP(listen_host);
492 (*fpl)[n].listen_path = MAYBE_DUP(listen_path);
493 (*fpl)[n].listen_port = listen_port;
494 (*fpl)[n].downstream = downstream;
500 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
502 struct ssh_channels *sc = ssh->chanctxt;
503 ForwardPermission *fp;
507 for (i = 0; i < sc->num_permitted_opens; i++) {
508 fp = &sc->permitted_opens[i];
509 if (fp->downstream != c)
512 /* cancel on the server, since mux client is gone */
513 debug("channel %d: cleanup remote forward for %s:%u",
514 c->self, fp->listen_host, fp->listen_port);
515 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
516 (r = sshpkt_put_cstring(ssh,
517 "cancel-tcpip-forward")) != 0 ||
518 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
519 (r = sshpkt_put_cstring(ssh,
520 channel_rfwd_bind_host(fp->listen_host))) != 0 ||
521 (r = sshpkt_put_u32(ssh, fp->listen_port)) != 0 ||
522 (r = sshpkt_send(ssh)) != 0) {
523 fatal("%s: channel %i: %s", __func__,
524 c->self, ssh_err(r));
526 fwd_perm_clear(fp); /* unregister */
530 /* Free the channel and close its fd/socket. */
532 channel_free(struct ssh *ssh, Channel *c)
534 struct ssh_channels *sc = ssh->chanctxt;
538 struct channel_confirm *cc;
540 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
541 if ((other = sc->channels[i]) == NULL)
544 /* detach from mux client and prepare for closing */
545 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
546 other->type == SSH_CHANNEL_MUX_PROXY &&
547 other->mux_ctx == c) {
548 other->mux_ctx = NULL;
549 other->type = SSH_CHANNEL_OPEN;
550 other->istate = CHAN_INPUT_CLOSED;
551 other->ostate = CHAN_OUTPUT_CLOSED;
554 debug("channel %d: free: %s, nchannels %u", c->self,
555 c->remote_name ? c->remote_name : "???", n);
557 if (c->type == SSH_CHANNEL_MUX_CLIENT)
558 mux_remove_remote_forwardings(ssh, c);
560 s = channel_open_message(ssh);
561 debug3("channel %d: status: %s", c->self, s);
564 channel_close_fds(ssh, c);
565 sshbuf_free(c->input);
566 sshbuf_free(c->output);
567 sshbuf_free(c->extended);
568 c->input = c->output = c->extended = NULL;
569 free(c->remote_name);
570 c->remote_name = NULL;
573 free(c->listening_addr);
574 c->listening_addr = NULL;
575 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
576 if (cc->abandon_cb != NULL)
577 cc->abandon_cb(ssh, c, cc->ctx);
578 TAILQ_REMOVE(&c->status_confirms, cc, entry);
579 explicit_bzero(cc, sizeof(*cc));
582 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
583 c->filter_cleanup(ssh, c->self, c->filter_ctx);
584 sc->channels[c->self] = NULL;
585 explicit_bzero(c, sizeof(*c));
590 channel_free_all(struct ssh *ssh)
594 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
595 if (ssh->chanctxt->channels[i] != NULL)
596 channel_free(ssh, ssh->chanctxt->channels[i]);
600 * Closes the sockets/fds of all channels. This is used to close extra file
601 * descriptors after a fork.
604 channel_close_all(struct ssh *ssh)
608 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
609 if (ssh->chanctxt->channels[i] != NULL)
610 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
614 * Stop listening to channels.
617 channel_stop_listening(struct ssh *ssh)
622 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
623 c = ssh->chanctxt->channels[i];
626 case SSH_CHANNEL_AUTH_SOCKET:
627 case SSH_CHANNEL_PORT_LISTENER:
628 case SSH_CHANNEL_RPORT_LISTENER:
629 case SSH_CHANNEL_X11_LISTENER:
630 case SSH_CHANNEL_UNIX_LISTENER:
631 case SSH_CHANNEL_RUNIX_LISTENER:
632 channel_close_fd(ssh, &c->sock);
633 channel_free(ssh, c);
641 * Returns true if no channel has too much buffered data, and false if one or
642 * more channel is overfull.
645 channel_not_very_much_buffered_data(struct ssh *ssh)
648 u_int maxsize = ssh_packet_get_maxsize(ssh);
651 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
652 c = ssh->chanctxt->channels[i];
653 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
655 if (sshbuf_len(c->output) > maxsize) {
656 debug2("channel %d: big output buffer %zu > %u",
657 c->self, sshbuf_len(c->output), maxsize);
664 /* Returns true if any channel is still open. */
666 channel_still_open(struct ssh *ssh)
671 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
672 c = ssh->chanctxt->channels[i];
676 case SSH_CHANNEL_X11_LISTENER:
677 case SSH_CHANNEL_PORT_LISTENER:
678 case SSH_CHANNEL_RPORT_LISTENER:
679 case SSH_CHANNEL_MUX_LISTENER:
680 case SSH_CHANNEL_CLOSED:
681 case SSH_CHANNEL_AUTH_SOCKET:
682 case SSH_CHANNEL_DYNAMIC:
683 case SSH_CHANNEL_RDYNAMIC_OPEN:
684 case SSH_CHANNEL_CONNECTING:
685 case SSH_CHANNEL_ZOMBIE:
686 case SSH_CHANNEL_ABANDONED:
687 case SSH_CHANNEL_UNIX_LISTENER:
688 case SSH_CHANNEL_RUNIX_LISTENER:
690 case SSH_CHANNEL_LARVAL:
692 case SSH_CHANNEL_OPENING:
693 case SSH_CHANNEL_OPEN:
694 case SSH_CHANNEL_RDYNAMIC_FINISH:
695 case SSH_CHANNEL_X11_OPEN:
696 case SSH_CHANNEL_MUX_CLIENT:
697 case SSH_CHANNEL_MUX_PROXY:
700 fatal("%s: bad channel type %d", __func__, c->type);
707 /* Returns the id of an open channel suitable for keepaliving */
709 channel_find_open(struct ssh *ssh)
714 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
715 c = ssh->chanctxt->channels[i];
716 if (c == NULL || !c->have_remote_id)
719 case SSH_CHANNEL_CLOSED:
720 case SSH_CHANNEL_DYNAMIC:
721 case SSH_CHANNEL_RDYNAMIC_OPEN:
722 case SSH_CHANNEL_RDYNAMIC_FINISH:
723 case SSH_CHANNEL_X11_LISTENER:
724 case SSH_CHANNEL_PORT_LISTENER:
725 case SSH_CHANNEL_RPORT_LISTENER:
726 case SSH_CHANNEL_MUX_LISTENER:
727 case SSH_CHANNEL_MUX_CLIENT:
728 case SSH_CHANNEL_MUX_PROXY:
729 case SSH_CHANNEL_OPENING:
730 case SSH_CHANNEL_CONNECTING:
731 case SSH_CHANNEL_ZOMBIE:
732 case SSH_CHANNEL_ABANDONED:
733 case SSH_CHANNEL_UNIX_LISTENER:
734 case SSH_CHANNEL_RUNIX_LISTENER:
736 case SSH_CHANNEL_LARVAL:
737 case SSH_CHANNEL_AUTH_SOCKET:
738 case SSH_CHANNEL_OPEN:
739 case SSH_CHANNEL_X11_OPEN:
742 fatal("%s: bad channel type %d", __func__, c->type);
750 * Returns a message describing the currently open forwarded connections,
751 * suitable for sending to the client. The message contains crlf pairs for
755 channel_open_message(struct ssh *ssh)
763 if ((buf = sshbuf_new()) == NULL)
764 fatal("%s: sshbuf_new", __func__);
765 if ((r = sshbuf_putf(buf,
766 "The following connections are open:\r\n")) != 0)
767 fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
768 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
769 c = ssh->chanctxt->channels[i];
773 case SSH_CHANNEL_X11_LISTENER:
774 case SSH_CHANNEL_PORT_LISTENER:
775 case SSH_CHANNEL_RPORT_LISTENER:
776 case SSH_CHANNEL_CLOSED:
777 case SSH_CHANNEL_AUTH_SOCKET:
778 case SSH_CHANNEL_ZOMBIE:
779 case SSH_CHANNEL_ABANDONED:
780 case SSH_CHANNEL_MUX_LISTENER:
781 case SSH_CHANNEL_UNIX_LISTENER:
782 case SSH_CHANNEL_RUNIX_LISTENER:
784 case SSH_CHANNEL_LARVAL:
785 case SSH_CHANNEL_OPENING:
786 case SSH_CHANNEL_CONNECTING:
787 case SSH_CHANNEL_DYNAMIC:
788 case SSH_CHANNEL_RDYNAMIC_OPEN:
789 case SSH_CHANNEL_RDYNAMIC_FINISH:
790 case SSH_CHANNEL_OPEN:
791 case SSH_CHANNEL_X11_OPEN:
792 case SSH_CHANNEL_MUX_PROXY:
793 case SSH_CHANNEL_MUX_CLIENT:
794 if ((r = sshbuf_putf(buf, " #%d %.300s "
795 "(t%d %s%u i%u/%zu o%u/%zu fd %d/%d cc %d)\r\n",
796 c->self, c->remote_name,
798 c->have_remote_id ? "r" : "nr", c->remote_id,
799 c->istate, sshbuf_len(c->input),
800 c->ostate, sshbuf_len(c->output),
801 c->rfd, c->wfd, c->ctl_chan)) != 0)
802 fatal("%s: sshbuf_putf: %s",
803 __func__, ssh_err(r));
806 fatal("%s: bad channel type %d", __func__, c->type);
810 if ((ret = sshbuf_dup_string(buf)) == NULL)
811 fatal("%s: sshbuf_dup_string", __func__);
817 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
821 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
822 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
823 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
824 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
825 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
826 fatal("%s: channel %i: open: %s", where, c->self, ssh_err(r));
831 channel_send_open(struct ssh *ssh, int id)
833 Channel *c = channel_lookup(ssh, id);
837 logit("channel_send_open: %d: bad id", id);
840 debug2("channel %d: send open", id);
841 open_preamble(ssh, __func__, c, c->ctype);
842 if ((r = sshpkt_send(ssh)) != 0)
843 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
847 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
849 Channel *c = channel_lookup(ssh, id);
853 logit("%s: %d: unknown channel id", __func__, id);
856 if (!c->have_remote_id)
857 fatal(":%s: channel %d: no remote id", __func__, c->self);
859 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
860 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
861 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
862 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
863 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
864 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
869 channel_register_status_confirm(struct ssh *ssh, int id,
870 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
872 struct channel_confirm *cc;
875 if ((c = channel_lookup(ssh, id)) == NULL)
876 fatal("%s: %d: bad id", __func__, id);
878 cc = xcalloc(1, sizeof(*cc));
880 cc->abandon_cb = abandon_cb;
882 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
886 channel_register_open_confirm(struct ssh *ssh, int id,
887 channel_open_fn *fn, void *ctx)
889 Channel *c = channel_lookup(ssh, id);
892 logit("%s: %d: bad id", __func__, id);
895 c->open_confirm = fn;
896 c->open_confirm_ctx = ctx;
900 channel_register_cleanup(struct ssh *ssh, int id,
901 channel_callback_fn *fn, int do_close)
903 Channel *c = channel_by_id(ssh, id);
906 logit("%s: %d: bad id", __func__, id);
910 c->detach_close = do_close;
914 channel_cancel_cleanup(struct ssh *ssh, int id)
916 Channel *c = channel_by_id(ssh, id);
919 logit("%s: %d: bad id", __func__, id);
922 c->detach_user = NULL;
927 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
928 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
930 Channel *c = channel_lookup(ssh, id);
933 logit("%s: %d: bad id", __func__, id);
936 c->input_filter = ifn;
937 c->output_filter = ofn;
939 c->filter_cleanup = cfn;
943 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
944 int extusage, int nonblock, int is_tty, u_int window_max)
946 Channel *c = channel_lookup(ssh, id);
949 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
950 fatal("channel_activate for non-larval channel %d.", id);
951 if (!c->have_remote_id)
952 fatal(":%s: channel %d: no remote id", __func__, c->self);
954 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
955 c->type = SSH_CHANNEL_OPEN;
956 c->local_window = c->local_window_max = window_max;
958 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
959 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
960 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
961 (r = sshpkt_send(ssh)) != 0)
962 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
966 channel_pre_listener(struct ssh *ssh, Channel *c,
967 fd_set *readset, fd_set *writeset)
969 FD_SET(c->sock, readset);
973 channel_pre_connecting(struct ssh *ssh, Channel *c,
974 fd_set *readset, fd_set *writeset)
976 debug3("channel %d: waiting for connection", c->self);
977 FD_SET(c->sock, writeset);
981 channel_pre_open(struct ssh *ssh, Channel *c,
982 fd_set *readset, fd_set *writeset)
984 if (c->istate == CHAN_INPUT_OPEN &&
985 c->remote_window > 0 &&
986 sshbuf_len(c->input) < c->remote_window &&
987 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
988 FD_SET(c->rfd, readset);
989 if (c->ostate == CHAN_OUTPUT_OPEN ||
990 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
991 if (sshbuf_len(c->output) > 0) {
992 FD_SET(c->wfd, writeset);
993 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
994 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
995 debug2("channel %d: "
996 "obuf_empty delayed efd %d/(%zu)", c->self,
997 c->efd, sshbuf_len(c->extended));
999 chan_obuf_empty(ssh, c);
1002 /** XXX check close conditions, too */
1003 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1004 c->ostate == CHAN_OUTPUT_CLOSED)) {
1005 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1006 sshbuf_len(c->extended) > 0)
1007 FD_SET(c->efd, writeset);
1008 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1009 (c->extended_usage == CHAN_EXTENDED_READ ||
1010 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1011 sshbuf_len(c->extended) < c->remote_window)
1012 FD_SET(c->efd, readset);
1014 /* XXX: What about efd? races? */
1018 * This is a special state for X11 authentication spoofing. An opened X11
1019 * connection (when authentication spoofing is being done) remains in this
1020 * state until the first packet has been completely read. The authentication
1021 * data in that packet is then substituted by the real data if it matches the
1022 * fake data, and the channel is put into normal mode.
1023 * XXX All this happens at the client side.
1024 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1027 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1029 struct ssh_channels *sc = ssh->chanctxt;
1031 u_int proto_len, data_len;
1033 /* Is this being called after the refusal deadline? */
1034 if (sc->x11_refuse_time != 0 &&
1035 (u_int)monotime() >= sc->x11_refuse_time) {
1036 verbose("Rejected X11 connection after ForwardX11Timeout "
1041 /* Check if the fixed size part of the packet is in buffer. */
1042 if (sshbuf_len(b) < 12)
1045 /* Parse the lengths of variable-length fields. */
1046 ucp = sshbuf_mutable_ptr(b);
1047 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1048 proto_len = 256 * ucp[6] + ucp[7];
1049 data_len = 256 * ucp[8] + ucp[9];
1050 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1051 proto_len = ucp[6] + 256 * ucp[7];
1052 data_len = ucp[8] + 256 * ucp[9];
1054 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1059 /* Check if the whole packet is in buffer. */
1061 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1064 /* Check if authentication protocol matches. */
1065 if (proto_len != strlen(sc->x11_saved_proto) ||
1066 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1067 debug2("X11 connection uses different authentication protocol.");
1070 /* Check if authentication data matches our fake data. */
1071 if (data_len != sc->x11_fake_data_len ||
1072 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1073 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1074 debug2("X11 auth data does not match fake data.");
1077 /* Check fake data length */
1078 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1079 error("X11 fake_data_len %d != saved_data_len %d",
1080 sc->x11_fake_data_len, sc->x11_saved_data_len);
1084 * Received authentication protocol and data match
1085 * our fake data. Substitute the fake data with real
1088 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1089 sc->x11_saved_data, sc->x11_saved_data_len);
1094 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1095 fd_set *readset, fd_set *writeset)
1097 int ret = x11_open_helper(ssh, c->output);
1099 /* c->force_drain = 1; */
1102 c->type = SSH_CHANNEL_OPEN;
1103 channel_pre_open(ssh, c, readset, writeset);
1104 } else if (ret == -1) {
1105 logit("X11 connection rejected because of wrong authentication.");
1106 debug2("X11 rejected %d i%d/o%d",
1107 c->self, c->istate, c->ostate);
1108 chan_read_failed(ssh, c);
1109 sshbuf_reset(c->input);
1110 chan_ibuf_empty(ssh, c);
1111 sshbuf_reset(c->output);
1112 chan_write_failed(ssh, c);
1113 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1118 channel_pre_mux_client(struct ssh *ssh,
1119 Channel *c, fd_set *readset, fd_set *writeset)
1121 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1122 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1123 FD_SET(c->rfd, readset);
1124 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1125 /* clear buffer immediately (discard any partial packet) */
1126 sshbuf_reset(c->input);
1127 chan_ibuf_empty(ssh, c);
1128 /* Start output drain. XXX just kill chan? */
1129 chan_rcvd_oclose(ssh, c);
1131 if (c->ostate == CHAN_OUTPUT_OPEN ||
1132 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1133 if (sshbuf_len(c->output) > 0)
1134 FD_SET(c->wfd, writeset);
1135 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1136 chan_obuf_empty(ssh, c);
1140 /* try to decode a socks4 header */
1142 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1146 u_int len, have, i, found, need;
1151 u_int16_t dest_port;
1152 struct in_addr dest_addr;
1156 debug2("channel %d: decode socks4", c->self);
1158 have = sshbuf_len(input);
1159 len = sizeof(s4_req);
1162 p = sshbuf_ptr(input);
1165 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1166 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1167 debug2("channel %d: socks4a request", c->self);
1168 /* ... and needs an extra string (the hostname) */
1171 /* Check for terminating NUL on the string(s) */
1172 for (found = 0, i = len; i < have; i++) {
1179 /* the peer is probably sending garbage */
1180 debug("channel %d: decode socks4: too long",
1187 if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1188 (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1189 (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1190 (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1191 debug("channels %d: decode socks4: %s", c->self, ssh_err(r));
1194 have = sshbuf_len(input);
1195 p = sshbuf_ptr(input);
1196 if (memchr(p, '\0', have) == NULL) {
1197 error("channel %d: decode socks4: user not nul terminated",
1202 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1203 len++; /* trailing '\0' */
1204 strlcpy(username, p, sizeof(username));
1205 if ((r = sshbuf_consume(input, len)) != 0) {
1206 fatal("%s: channel %d: consume: %s", __func__,
1207 c->self, ssh_err(r));
1211 if (need == 1) { /* SOCKS4: one string */
1212 host = inet_ntoa(s4_req.dest_addr);
1213 c->path = xstrdup(host);
1214 } else { /* SOCKS4A: two strings */
1215 have = sshbuf_len(input);
1216 p = sshbuf_ptr(input);
1217 if (memchr(p, '\0', have) == NULL) {
1218 error("channel %d: decode socks4a: host not nul "
1219 "terminated", c->self);
1223 debug2("channel %d: decode socks4a: host %s/%d",
1225 len++; /* trailing '\0' */
1226 if (len > NI_MAXHOST) {
1227 error("channel %d: hostname \"%.100s\" too long",
1231 c->path = xstrdup(p);
1232 if ((r = sshbuf_consume(input, len)) != 0) {
1233 fatal("%s: channel %d: consume: %s", __func__,
1234 c->self, ssh_err(r));
1237 c->host_port = ntohs(s4_req.dest_port);
1239 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1240 c->self, c->path, c->host_port, s4_req.command);
1242 if (s4_req.command != 1) {
1243 debug("channel %d: cannot handle: %s cn %d",
1244 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1247 s4_rsp.version = 0; /* vn: 0 for reply */
1248 s4_rsp.command = 90; /* cd: req granted */
1249 s4_rsp.dest_port = 0; /* ignored */
1250 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1251 if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0) {
1252 fatal("%s: channel %d: append reply: %s", __func__,
1253 c->self, ssh_err(r));
1258 /* try to decode a socks5 header */
1259 #define SSH_SOCKS5_AUTHDONE 0x1000
1260 #define SSH_SOCKS5_NOAUTH 0x00
1261 #define SSH_SOCKS5_IPV4 0x01
1262 #define SSH_SOCKS5_DOMAIN 0x03
1263 #define SSH_SOCKS5_IPV6 0x04
1264 #define SSH_SOCKS5_CONNECT 0x01
1265 #define SSH_SOCKS5_SUCCESS 0x00
1268 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1270 /* XXX use get/put_u8 instead of trusting struct padding */
1277 u_int16_t dest_port;
1278 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1280 u_int have, need, i, found, nmethods, addrlen, af;
1283 debug2("channel %d: decode socks5", c->self);
1284 p = sshbuf_ptr(input);
1287 have = sshbuf_len(input);
1288 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1289 /* format: ver | nmethods | methods */
1293 if (have < nmethods + 2)
1295 /* look for method: "NO AUTHENTICATION REQUIRED" */
1296 for (found = 0, i = 2; i < nmethods + 2; i++) {
1297 if (p[i] == SSH_SOCKS5_NOAUTH) {
1303 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1307 if ((r = sshbuf_consume(input, nmethods + 2)) != 0) {
1308 fatal("%s: channel %d: consume: %s", __func__,
1309 c->self, ssh_err(r));
1311 /* version, method */
1312 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1313 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0) {
1314 fatal("%s: channel %d: append reply: %s", __func__,
1315 c->self, ssh_err(r));
1317 c->flags |= SSH_SOCKS5_AUTHDONE;
1318 debug2("channel %d: socks5 auth done", c->self);
1319 return 0; /* need more */
1321 debug2("channel %d: socks5 post auth", c->self);
1322 if (have < sizeof(s5_req)+1)
1323 return 0; /* need more */
1324 memcpy(&s5_req, p, sizeof(s5_req));
1325 if (s5_req.version != 0x05 ||
1326 s5_req.command != SSH_SOCKS5_CONNECT ||
1327 s5_req.reserved != 0x00) {
1328 debug2("channel %d: only socks5 connect supported", c->self);
1331 switch (s5_req.atyp){
1332 case SSH_SOCKS5_IPV4:
1336 case SSH_SOCKS5_DOMAIN:
1337 addrlen = p[sizeof(s5_req)];
1340 case SSH_SOCKS5_IPV6:
1345 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1348 need = sizeof(s5_req) + addrlen + 2;
1349 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1353 if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0) {
1354 fatal("%s: channel %d: consume: %s", __func__,
1355 c->self, ssh_err(r));
1357 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1358 /* host string length */
1359 if ((r = sshbuf_consume(input, 1)) != 0) {
1360 fatal("%s: channel %d: consume: %s", __func__,
1361 c->self, ssh_err(r));
1364 if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1365 (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1366 debug("channel %d: parse addr/port: %s", c->self, ssh_err(r));
1369 dest_addr[addrlen] = '\0';
1372 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1373 if (addrlen >= NI_MAXHOST) {
1374 error("channel %d: dynamic request: socks5 hostname "
1375 "\"%.100s\" too long", c->self, dest_addr);
1378 c->path = xstrdup(dest_addr);
1380 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1382 c->path = xstrdup(ntop);
1384 c->host_port = ntohs(dest_port);
1386 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1387 c->self, c->path, c->host_port, s5_req.command);
1389 s5_rsp.version = 0x05;
1390 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1391 s5_rsp.reserved = 0; /* ignored */
1392 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1393 dest_port = 0; /* ignored */
1395 if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1396 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1397 (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1398 fatal("%s: channel %d: append reply: %s", __func__,
1399 c->self, ssh_err(r));
1404 channel_connect_stdio_fwd(struct ssh *ssh,
1405 const char *host_to_connect, u_short port_to_connect, int in, int out)
1409 debug("%s %s:%d", __func__, host_to_connect, port_to_connect);
1411 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1412 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1413 0, "stdio-forward", /*nonblock*/0);
1415 c->path = xstrdup(host_to_connect);
1416 c->host_port = port_to_connect;
1417 c->listening_port = 0;
1420 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1421 port_open_helper(ssh, c, "direct-tcpip");
1426 /* dynamic port forwarding */
1428 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1429 fd_set *readset, fd_set *writeset)
1435 have = sshbuf_len(c->input);
1436 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1437 /* sshbuf_dump(c->input, stderr); */
1438 /* check if the fixed size part of the packet is in buffer. */
1441 FD_SET(c->sock, readset);
1444 /* try to guess the protocol */
1445 p = sshbuf_ptr(c->input);
1446 /* XXX sshbuf_peek_u8? */
1449 ret = channel_decode_socks4(c, c->input, c->output);
1452 ret = channel_decode_socks5(c, c->input, c->output);
1459 chan_mark_dead(ssh, c);
1460 } else if (ret == 0) {
1461 debug2("channel %d: pre_dynamic: need more", c->self);
1463 FD_SET(c->sock, readset);
1464 if (sshbuf_len(c->output))
1465 FD_SET(c->sock, writeset);
1467 /* switch to the next state */
1468 c->type = SSH_CHANNEL_OPENING;
1469 port_open_helper(ssh, c, "direct-tcpip");
1473 /* simulate read-error */
1475 rdynamic_close(struct ssh *ssh, Channel *c)
1477 c->type = SSH_CHANNEL_OPEN;
1478 chan_read_failed(ssh, c);
1479 sshbuf_reset(c->input);
1480 chan_ibuf_empty(ssh, c);
1481 sshbuf_reset(c->output);
1482 chan_write_failed(ssh, c);
1485 /* reverse dynamic port forwarding */
1487 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1493 have = sshbuf_len(c->output);
1494 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1495 /* sshbuf_dump(c->output, stderr); */
1497 if (c->flags & CHAN_EOF_RCVD) {
1498 if ((r = sshbuf_consume(c->output, have)) != 0) {
1499 fatal("%s: channel %d: consume: %s",
1500 __func__, c->self, ssh_err(r));
1502 rdynamic_close(ssh, c);
1505 /* check if the fixed size part of the packet is in buffer. */
1508 /* try to guess the protocol */
1509 p = sshbuf_ptr(c->output);
1512 /* switch input/output for reverse forwarding */
1513 ret = channel_decode_socks4(c, c->output, c->input);
1516 ret = channel_decode_socks5(c, c->output, c->input);
1523 rdynamic_close(ssh, c);
1524 } else if (ret == 0) {
1525 debug2("channel %d: pre_rdynamic: need more", c->self);
1526 /* send socks request to peer */
1527 len = sshbuf_len(c->input);
1528 if (len > 0 && len < c->remote_window) {
1529 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1530 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1531 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1532 (r = sshpkt_send(ssh)) != 0) {
1533 fatal("%s: channel %i: rdynamic: %s", __func__,
1534 c->self, ssh_err(r));
1536 if ((r = sshbuf_consume(c->input, len)) != 0) {
1537 fatal("%s: channel %d: consume: %s",
1538 __func__, c->self, ssh_err(r));
1540 c->remote_window -= len;
1542 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1543 /* the connect failed */
1544 rdynamic_close(ssh, c);
1548 /* This is our fake X11 server socket. */
1550 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1551 fd_set *readset, fd_set *writeset)
1554 struct sockaddr_storage addr;
1555 int r, newsock, oerrno, remote_port;
1557 char buf[16384], *remote_ipaddr;
1559 if (!FD_ISSET(c->sock, readset))
1562 debug("X11 connection requested.");
1563 addrlen = sizeof(addr);
1564 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1565 if (c->single_connection) {
1567 debug2("single_connection: closing X11 listener.");
1568 channel_close_fd(ssh, &c->sock);
1569 chan_mark_dead(ssh, c);
1573 if (errno != EINTR && errno != EWOULDBLOCK &&
1574 errno != ECONNABORTED)
1575 error("accept: %.100s", strerror(errno));
1576 if (errno == EMFILE || errno == ENFILE)
1577 c->notbefore = monotime() + 1;
1580 set_nodelay(newsock);
1581 remote_ipaddr = get_peer_ipaddr(newsock);
1582 remote_port = get_peer_port(newsock);
1583 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1584 remote_ipaddr, remote_port);
1586 nc = channel_new(ssh, "accepted x11 socket",
1587 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1588 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1589 open_preamble(ssh, __func__, nc, "x11");
1590 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1591 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1592 fatal("%s: channel %i: reply %s", __func__,
1593 c->self, ssh_err(r));
1595 if ((r = sshpkt_send(ssh)) != 0)
1596 fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1597 free(remote_ipaddr);
1601 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1603 char *local_ipaddr = get_local_ipaddr(c->sock);
1604 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1605 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1606 int remote_port = get_peer_port(c->sock);
1609 if (remote_port == -1) {
1610 /* Fake addr/port to appease peers that validate it (Tectia) */
1611 free(remote_ipaddr);
1612 remote_ipaddr = xstrdup("127.0.0.1");
1613 remote_port = 65535;
1616 free(c->remote_name);
1617 xasprintf(&c->remote_name,
1618 "%s: listening port %d for %.100s port %d, "
1619 "connect from %.200s port %d to %.100s port %d",
1620 rtype, c->listening_port, c->path, c->host_port,
1621 remote_ipaddr, remote_port, local_ipaddr, local_port);
1623 open_preamble(ssh, __func__, c, rtype);
1624 if (strcmp(rtype, "direct-tcpip") == 0) {
1625 /* target host, port */
1626 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1627 (r = sshpkt_put_u32(ssh, c->host_port)) != 0) {
1628 fatal("%s: channel %i: reply %s", __func__,
1629 c->self, ssh_err(r));
1631 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1633 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1634 fatal("%s: channel %i: reply %s", __func__,
1635 c->self, ssh_err(r));
1637 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1639 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1640 fatal("%s: channel %i: reply %s", __func__,
1641 c->self, ssh_err(r));
1644 /* listen address, port */
1645 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1646 (r = sshpkt_put_u32(ssh, local_port)) != 0) {
1647 fatal("%s: channel %i: reply %s", __func__,
1648 c->self, ssh_err(r));
1651 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1652 /* reserved for future owner/mode info */
1653 if ((r = sshpkt_put_cstring(ssh, "")) != 0) {
1654 fatal("%s: channel %i: reply %s", __func__,
1655 c->self, ssh_err(r));
1658 /* originator host and port */
1659 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1660 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0) {
1661 fatal("%s: channel %i: reply %s", __func__,
1662 c->self, ssh_err(r));
1665 if ((r = sshpkt_send(ssh)) != 0)
1666 fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1667 free(remote_ipaddr);
1672 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1674 ssh->chanctxt->x11_refuse_time = refuse_time;
1678 * This socket is listening for connections to a forwarded TCP/IP port.
1681 channel_post_port_listener(struct ssh *ssh, Channel *c,
1682 fd_set *readset, fd_set *writeset)
1685 struct sockaddr_storage addr;
1686 int newsock, nextstate;
1690 if (!FD_ISSET(c->sock, readset))
1693 debug("Connection to port %d forwarding to %.100s port %d requested.",
1694 c->listening_port, c->path, c->host_port);
1696 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1697 nextstate = SSH_CHANNEL_OPENING;
1698 rtype = "forwarded-tcpip";
1699 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1700 nextstate = SSH_CHANNEL_OPENING;
1701 rtype = "forwarded-streamlocal@openssh.com";
1702 } else if (c->host_port == PORT_STREAMLOCAL) {
1703 nextstate = SSH_CHANNEL_OPENING;
1704 rtype = "direct-streamlocal@openssh.com";
1705 } else if (c->host_port == 0) {
1706 nextstate = SSH_CHANNEL_DYNAMIC;
1707 rtype = "dynamic-tcpip";
1709 nextstate = SSH_CHANNEL_OPENING;
1710 rtype = "direct-tcpip";
1713 addrlen = sizeof(addr);
1714 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1716 if (errno != EINTR && errno != EWOULDBLOCK &&
1717 errno != ECONNABORTED)
1718 error("accept: %.100s", strerror(errno));
1719 if (errno == EMFILE || errno == ENFILE)
1720 c->notbefore = monotime() + 1;
1723 if (c->host_port != PORT_STREAMLOCAL)
1724 set_nodelay(newsock);
1725 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1726 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1727 nc->listening_port = c->listening_port;
1728 nc->host_port = c->host_port;
1729 if (c->path != NULL)
1730 nc->path = xstrdup(c->path);
1732 if (nextstate != SSH_CHANNEL_DYNAMIC)
1733 port_open_helper(ssh, nc, rtype);
1737 * This is the authentication agent socket listening for connections from
1741 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1742 fd_set *readset, fd_set *writeset)
1746 struct sockaddr_storage addr;
1749 if (!FD_ISSET(c->sock, readset))
1752 addrlen = sizeof(addr);
1753 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1755 error("accept from auth socket: %.100s", strerror(errno));
1756 if (errno == EMFILE || errno == ENFILE)
1757 c->notbefore = monotime() + 1;
1760 nc = channel_new(ssh, "accepted auth socket",
1761 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1762 c->local_window_max, c->local_maxpacket,
1763 0, "accepted auth socket", 1);
1764 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1765 if ((r = sshpkt_send(ssh)) != 0)
1766 fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
1770 channel_post_connecting(struct ssh *ssh, Channel *c,
1771 fd_set *readset, fd_set *writeset)
1773 int err = 0, sock, isopen, r;
1774 socklen_t sz = sizeof(err);
1776 if (!FD_ISSET(c->sock, writeset))
1778 if (!c->have_remote_id)
1779 fatal(":%s: channel %d: no remote id", __func__, c->self);
1780 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
1781 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1782 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1784 error("getsockopt SO_ERROR failed");
1787 debug("channel %d: connected to %s port %d",
1788 c->self, c->connect_ctx.host, c->connect_ctx.port);
1789 channel_connect_ctx_free(&c->connect_ctx);
1790 c->type = SSH_CHANNEL_OPEN;
1792 /* no message necessary */
1794 if ((r = sshpkt_start(ssh,
1795 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1796 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1797 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1798 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1799 (r = sshpkt_put_u32(ssh, c->local_maxpacket))
1801 fatal("%s: channel %i: confirm: %s", __func__,
1802 c->self, ssh_err(r));
1803 if ((r = sshpkt_send(ssh)) != 0)
1804 fatal("%s: channel %i: %s", __func__, c->self,
1808 debug("channel %d: connection failed: %s",
1809 c->self, strerror(err));
1810 /* Try next address, if any */
1811 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1813 c->sock = c->rfd = c->wfd = sock;
1814 channel_find_maxfd(ssh->chanctxt);
1817 /* Exhausted all addresses */
1818 error("connect_to %.100s port %d: failed.",
1819 c->connect_ctx.host, c->connect_ctx.port);
1820 channel_connect_ctx_free(&c->connect_ctx);
1822 rdynamic_close(ssh, c);
1824 if ((r = sshpkt_start(ssh,
1825 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1826 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1827 (r = sshpkt_put_u32(ssh,
1828 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1829 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1830 (r = sshpkt_put_cstring(ssh, "")) != 0) {
1831 fatal("%s: channel %i: failure: %s", __func__,
1832 c->self, ssh_err(r));
1834 if ((r = sshpkt_send(ssh)) != 0)
1835 fatal("%s: channel %i: %s", __func__, c->self,
1837 chan_mark_dead(ssh, c);
1843 channel_handle_rfd(struct ssh *ssh, Channel *c,
1844 fd_set *readset, fd_set *writeset)
1846 char buf[CHAN_RBUF];
1850 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1852 if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1856 len = read(c->rfd, buf, sizeof(buf));
1857 if (len < 0 && (errno == EINTR ||
1858 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1860 #ifndef PTY_ZEROREAD
1863 if ((!c->isatty && len <= 0) ||
1864 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1866 debug2("channel %d: read<=0 rfd %d len %zd",
1867 c->self, c->rfd, len);
1868 if (c->type != SSH_CHANNEL_OPEN) {
1869 debug2("channel %d: not open", c->self);
1870 chan_mark_dead(ssh, c);
1873 chan_read_failed(ssh, c);
1877 if (c->input_filter != NULL) {
1878 if (c->input_filter(ssh, c, buf, len) == -1) {
1879 debug2("channel %d: filter stops", c->self);
1880 chan_read_failed(ssh, c);
1882 } else if (c->datagram) {
1883 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1884 fatal("%s: channel %d: put datagram: %s", __func__,
1885 c->self, ssh_err(r));
1886 } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
1887 fatal("%s: channel %d: put data: %s", __func__,
1888 c->self, ssh_err(r));
1894 channel_handle_wfd(struct ssh *ssh, Channel *c,
1895 fd_set *readset, fd_set *writeset)
1898 u_char *data = NULL, *buf; /* XXX const; need filter API change */
1899 size_t dlen, olen = 0;
1902 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1903 sshbuf_len(c->output) == 0)
1906 /* Send buffered output data to the socket. */
1907 olen = sshbuf_len(c->output);
1908 if (c->output_filter != NULL) {
1909 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1910 debug2("channel %d: filter stops", c->self);
1911 if (c->type != SSH_CHANNEL_OPEN)
1912 chan_mark_dead(ssh, c);
1914 chan_write_failed(ssh, c);
1917 } else if (c->datagram) {
1918 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
1919 fatal("%s: channel %d: get datagram: %s", __func__,
1920 c->self, ssh_err(r));
1923 buf = data = sshbuf_mutable_ptr(c->output);
1924 dlen = sshbuf_len(c->output);
1928 /* ignore truncated writes, datagrams might get lost */
1929 len = write(c->wfd, buf, dlen);
1931 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1932 errno == EWOULDBLOCK))
1940 /* XXX: Later AIX versions can't push as much data to tty */
1942 dlen = MIN(dlen, 8*1024);
1945 len = write(c->wfd, buf, dlen);
1947 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1951 if (c->type != SSH_CHANNEL_OPEN) {
1952 debug2("channel %d: not open", c->self);
1953 chan_mark_dead(ssh, c);
1956 chan_write_failed(ssh, c);
1960 #ifndef BROKEN_TCGETATTR_ICANON
1961 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
1962 if (tcgetattr(c->wfd, &tio) == 0 &&
1963 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1965 * Simulate echo to reduce the impact of
1966 * traffic analysis. We need to match the
1967 * size of a SSH2_MSG_CHANNEL_DATA message
1968 * (4 byte channel id + buf)
1970 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
1971 (r = sshpkt_send(ssh)) != 0)
1972 fatal("%s: channel %d: ignore: %s",
1973 __func__, c->self, ssh_err(r));
1976 #endif /* BROKEN_TCGETATTR_ICANON */
1977 if ((r = sshbuf_consume(c->output, len)) != 0) {
1978 fatal("%s: channel %d: consume: %s",
1979 __func__, c->self, ssh_err(r));
1982 c->local_consumed += olen - sshbuf_len(c->output);
1988 channel_handle_efd_write(struct ssh *ssh, Channel *c,
1989 fd_set *readset, fd_set *writeset)
1994 if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
1997 len = write(c->efd, sshbuf_ptr(c->extended),
1998 sshbuf_len(c->extended));
1999 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2000 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
2001 errno == EWOULDBLOCK))
2004 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2005 channel_close_fd(ssh, &c->efd);
2007 if ((r = sshbuf_consume(c->extended, len)) != 0) {
2008 fatal("%s: channel %d: consume: %s",
2009 __func__, c->self, ssh_err(r));
2011 c->local_consumed += len;
2017 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2018 fd_set *readset, fd_set *writeset)
2020 char buf[CHAN_RBUF];
2024 if (!c->detach_close && !FD_ISSET(c->efd, readset))
2027 len = read(c->efd, buf, sizeof(buf));
2028 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2029 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
2030 errno == EWOULDBLOCK) && !c->detach_close)))
2033 debug2("channel %d: closing read-efd %d",
2035 channel_close_fd(ssh, &c->efd);
2037 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
2038 debug3("channel %d: discard efd",
2040 } else if ((r = sshbuf_put(c->extended, buf, len)) != 0) {
2041 fatal("%s: channel %d: append: %s",
2042 __func__, c->self, ssh_err(r));
2049 channel_handle_efd(struct ssh *ssh, Channel *c,
2050 fd_set *readset, fd_set *writeset)
2055 /** XXX handle drain efd, too */
2057 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2058 return channel_handle_efd_write(ssh, c, readset, writeset);
2059 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2060 c->extended_usage == CHAN_EXTENDED_IGNORE)
2061 return channel_handle_efd_read(ssh, c, readset, writeset);
2067 channel_check_window(struct ssh *ssh, Channel *c)
2071 if (c->type == SSH_CHANNEL_OPEN &&
2072 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2073 ((c->local_window_max - c->local_window >
2074 c->local_maxpacket*3) ||
2075 c->local_window < c->local_window_max/2) &&
2076 c->local_consumed > 0) {
2077 if (!c->have_remote_id)
2078 fatal(":%s: channel %d: no remote id",
2080 if ((r = sshpkt_start(ssh,
2081 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2082 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2083 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2084 (r = sshpkt_send(ssh)) != 0) {
2085 fatal("%s: channel %i: %s", __func__,
2086 c->self, ssh_err(r));
2088 debug2("channel %d: window %d sent adjust %d",
2089 c->self, c->local_window,
2091 c->local_window += c->local_consumed;
2092 c->local_consumed = 0;
2098 channel_post_open(struct ssh *ssh, Channel *c,
2099 fd_set *readset, fd_set *writeset)
2101 channel_handle_rfd(ssh, c, readset, writeset);
2102 channel_handle_wfd(ssh, c, readset, writeset);
2103 channel_handle_efd(ssh, c, readset, writeset);
2104 channel_check_window(ssh, c);
2108 read_mux(struct ssh *ssh, Channel *c, u_int need)
2110 char buf[CHAN_RBUF];
2115 if (sshbuf_len(c->input) < need) {
2116 rlen = need - sshbuf_len(c->input);
2117 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2118 if (len < 0 && (errno == EINTR || errno == EAGAIN))
2119 return sshbuf_len(c->input);
2121 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2122 c->self, c->rfd, len);
2123 chan_read_failed(ssh, c);
2125 } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
2126 fatal("%s: channel %d: append: %s",
2127 __func__, c->self, ssh_err(r));
2130 return sshbuf_len(c->input);
2134 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2135 fd_set *readset, fd_set *writeset)
2139 if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2141 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2147 * Don't not read past the precise end of packets to
2148 * avoid disrupting fd passing.
2150 if (read_mux(ssh, c, 4) < 4) /* read header */
2152 /* XXX sshbuf_peek_u32 */
2153 need = PEEK_U32(sshbuf_ptr(c->input));
2154 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2155 if (need > CHANNEL_MUX_MAX_PACKET) {
2156 debug2("channel %d: packet too big %u > %u",
2157 c->self, CHANNEL_MUX_MAX_PACKET, need);
2158 chan_rcvd_oclose(ssh, c);
2161 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2163 if (c->mux_rcb(ssh, c) != 0) {
2164 debug("channel %d: mux_rcb failed", c->self);
2165 chan_mark_dead(ssh, c);
2171 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2172 fd_set *readset, fd_set *writeset)
2177 if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2178 sshbuf_len(c->output) == 0)
2181 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2182 if (len < 0 && (errno == EINTR || errno == EAGAIN))
2185 chan_mark_dead(ssh, c);
2188 if ((r = sshbuf_consume(c->output, len)) != 0)
2189 fatal("%s: channel %d: consume: %s", __func__,
2190 c->self, ssh_err(r));
2194 channel_post_mux_client(struct ssh *ssh, Channel *c,
2195 fd_set *readset, fd_set *writeset)
2197 channel_post_mux_client_read(ssh, c, readset, writeset);
2198 channel_post_mux_client_write(ssh, c, readset, writeset);
2202 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2203 fd_set *readset, fd_set *writeset)
2206 struct sockaddr_storage addr;
2212 if (!FD_ISSET(c->sock, readset))
2215 debug("multiplexing control connection");
2218 * Accept connection on control socket
2220 memset(&addr, 0, sizeof(addr));
2221 addrlen = sizeof(addr);
2222 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2224 error("%s accept: %s", __func__, strerror(errno));
2225 if (errno == EMFILE || errno == ENFILE)
2226 c->notbefore = monotime() + 1;
2230 if (getpeereid(newsock, &euid, &egid) < 0) {
2231 error("%s getpeereid failed: %s", __func__,
2236 if ((euid != 0) && (getuid() != euid)) {
2237 error("multiplex uid mismatch: peer euid %u != uid %u",
2238 (u_int)euid, (u_int)getuid());
2242 nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2243 newsock, newsock, -1, c->local_window_max,
2244 c->local_maxpacket, 0, "mux-control", 1);
2245 nc->mux_rcb = c->mux_rcb;
2246 debug3("%s: new mux channel %d fd %d", __func__, nc->self, nc->sock);
2247 /* establish state */
2248 nc->mux_rcb(ssh, nc);
2249 /* mux state transitions must not elicit protocol messages */
2250 nc->flags |= CHAN_LOCAL;
2254 channel_handler_init(struct ssh_channels *sc)
2256 chan_fn **pre, **post;
2258 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2259 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2260 fatal("%s: allocation failed", __func__);
2262 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2263 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2264 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2265 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2266 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2267 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2268 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2269 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2270 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2271 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2272 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2273 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2274 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2276 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2277 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2278 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2279 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2280 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2281 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2282 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2283 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2284 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2285 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2286 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2287 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2289 sc->channel_pre = pre;
2290 sc->channel_post = post;
2293 /* gc dead channels */
2295 channel_garbage_collect(struct ssh *ssh, Channel *c)
2299 if (c->detach_user != NULL) {
2300 if (!chan_is_dead(ssh, c, c->detach_close))
2302 debug2("channel %d: gc: notify user", c->self);
2303 c->detach_user(ssh, c->self, NULL);
2304 /* if we still have a callback */
2305 if (c->detach_user != NULL)
2307 debug2("channel %d: gc: user detached", c->self);
2309 if (!chan_is_dead(ssh, c, 1))
2311 debug2("channel %d: garbage collecting", c->self);
2312 channel_free(ssh, c);
2315 enum channel_table { CHAN_PRE, CHAN_POST };
2318 channel_handler(struct ssh *ssh, int table,
2319 fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2321 struct ssh_channels *sc = ssh->chanctxt;
2322 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2328 if (unpause_secs != NULL)
2330 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2331 c = sc->channels[i];
2335 if (table == CHAN_PRE)
2340 if (ftab[c->type] != NULL) {
2342 * Run handlers that are not paused.
2344 if (c->notbefore <= now)
2345 (*ftab[c->type])(ssh, c, readset, writeset);
2346 else if (unpause_secs != NULL) {
2348 * Collect the time that the earliest
2349 * channel comes off pause.
2351 debug3("%s: chan %d: skip for %d more seconds",
2353 (int)(c->notbefore - now));
2354 if (*unpause_secs == 0 ||
2355 (c->notbefore - now) < *unpause_secs)
2356 *unpause_secs = c->notbefore - now;
2359 channel_garbage_collect(ssh, c);
2361 if (unpause_secs != NULL && *unpause_secs != 0)
2362 debug3("%s: first channel unpauses in %d seconds",
2363 __func__, (int)*unpause_secs);
2367 * Create sockets before allocating the select bitmasks.
2368 * This is necessary for things that need to happen after reading
2369 * the network-input but before channel_prepare_select().
2372 channel_before_prepare_select(struct ssh *ssh)
2374 struct ssh_channels *sc = ssh->chanctxt;
2378 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2379 c = sc->channels[i];
2382 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2383 channel_before_prepare_select_rdynamic(ssh, c);
2388 * Allocate/update select bitmasks and add any bits relevant to channels in
2392 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2393 int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2395 u_int n, sz, nfdset;
2397 channel_before_prepare_select(ssh); /* might update channel_max_fd */
2399 n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2401 nfdset = howmany(n+1, NFDBITS);
2402 /* Explicitly test here, because xrealloc isn't always called */
2403 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2404 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2405 sz = nfdset * sizeof(fd_mask);
2407 /* perhaps check sz < nalloc/2 and shrink? */
2408 if (*readsetp == NULL || sz > *nallocp) {
2409 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2410 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2414 memset(*readsetp, 0, sz);
2415 memset(*writesetp, 0, sz);
2417 if (!ssh_packet_is_rekeying(ssh))
2418 channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2423 * After select, perform any appropriate operations for channels which have
2427 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2429 channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2433 * Enqueue data for channels with open or draining c->input.
2436 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2442 if ((len = sshbuf_len(c->input)) == 0) {
2443 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2445 * input-buffer is empty and read-socket shutdown:
2446 * tell peer, that we will not send more data:
2448 * hack for extended data: delay EOF if EFD still
2451 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2452 debug2("channel %d: "
2453 "ibuf_empty delayed efd %d/(%zu)",
2454 c->self, c->efd, sshbuf_len(c->extended));
2456 chan_ibuf_empty(ssh, c);
2461 if (!c->have_remote_id)
2462 fatal(":%s: channel %d: no remote id", __func__, c->self);
2465 /* Check datagram will fit; drop if not */
2466 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2467 fatal("%s: channel %d: get datagram: %s", __func__,
2468 c->self, ssh_err(r));
2470 * XXX this does tail-drop on the datagram queue which is
2471 * usually suboptimal compared to head-drop. Better to have
2472 * backpressure at read time? (i.e. read + discard)
2474 if (plen > c->remote_window || plen > c->remote_maxpacket) {
2475 debug("channel %d: datagram too big", c->self);
2479 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2480 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2481 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2482 (r = sshpkt_send(ssh)) != 0) {
2483 fatal("%s: channel %i: datagram: %s", __func__,
2484 c->self, ssh_err(r));
2486 c->remote_window -= plen;
2490 /* Enqueue packet for buffered data. */
2491 if (len > c->remote_window)
2492 len = c->remote_window;
2493 if (len > c->remote_maxpacket)
2494 len = c->remote_maxpacket;
2497 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2498 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2499 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2500 (r = sshpkt_send(ssh)) != 0) {
2501 fatal("%s: channel %i: data: %s", __func__,
2502 c->self, ssh_err(r));
2504 if ((r = sshbuf_consume(c->input, len)) != 0)
2505 fatal("%s: channel %i: consume: %s", __func__,
2506 c->self, ssh_err(r));
2507 c->remote_window -= len;
2511 * Enqueue data for channels with open c->extended in read mode.
2514 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2519 if ((len = sshbuf_len(c->extended)) == 0)
2522 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2523 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2524 if (len > c->remote_window)
2525 len = c->remote_window;
2526 if (len > c->remote_maxpacket)
2527 len = c->remote_maxpacket;
2530 if (!c->have_remote_id)
2531 fatal(":%s: channel %d: no remote id", __func__, c->self);
2532 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2533 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2534 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2535 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2536 (r = sshpkt_send(ssh)) != 0) {
2537 fatal("%s: channel %i: data: %s", __func__,
2538 c->self, ssh_err(r));
2540 if ((r = sshbuf_consume(c->extended, len)) != 0)
2541 fatal("%s: channel %i: consume: %s", __func__,
2542 c->self, ssh_err(r));
2543 c->remote_window -= len;
2544 debug2("channel %d: sent ext data %zu", c->self, len);
2547 /* If there is data to send to the connection, enqueue some of it now. */
2549 channel_output_poll(struct ssh *ssh)
2551 struct ssh_channels *sc = ssh->chanctxt;
2555 for (i = 0; i < sc->channels_alloc; i++) {
2556 c = sc->channels[i];
2561 * We are only interested in channels that can have buffered
2564 if (c->type != SSH_CHANNEL_OPEN)
2566 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2567 /* XXX is this true? */
2568 debug3("channel %d: will not send data after close",
2573 /* Get the amount of buffered data for this channel. */
2574 if (c->istate == CHAN_INPUT_OPEN ||
2575 c->istate == CHAN_INPUT_WAIT_DRAIN)
2576 channel_output_poll_input_open(ssh, c);
2577 /* Send extended data, i.e. stderr */
2578 if (!(c->flags & CHAN_EOF_SENT) &&
2579 c->extended_usage == CHAN_EXTENDED_READ)
2580 channel_output_poll_extended_read(ssh, c);
2584 /* -- mux proxy support */
2587 * When multiplexing channel messages for mux clients we have to deal
2588 * with downstream messages from the mux client and upstream messages
2589 * from the ssh server:
2590 * 1) Handling downstream messages is straightforward and happens
2591 * in channel_proxy_downstream():
2592 * - We forward all messages (mostly) unmodified to the server.
2593 * - However, in order to route messages from upstream to the correct
2594 * downstream client, we have to replace the channel IDs used by the
2595 * mux clients with a unique channel ID because the mux clients might
2596 * use conflicting channel IDs.
2597 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2598 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2599 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2600 * with the newly allocated channel ID.
2601 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2602 * channels and procesed by channel_proxy_upstream(). The local channel ID
2603 * is then translated back to the original mux client ID.
2604 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2605 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2606 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2607 * downstream mux client are removed.
2608 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2609 * requires more work, because they are not addressed to a specific
2610 * channel. E.g. client_request_forwarded_tcpip() needs to figure
2611 * out whether the request is addressed to the local client or a
2612 * specific downstream client based on the listen-address/port.
2613 * 6) Agent and X11-Forwarding have a similar problem and are currenly
2614 * not supported as the matching session/channel cannot be identified
2619 * receive packets from downstream mux clients:
2620 * channel callback fired on read from mux client, creates
2621 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2622 * on channel creation.
2625 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2628 struct sshbuf *original = NULL, *modified = NULL;
2630 char *ctype = NULL, *listen_host = NULL;
2634 u_int id, remote_id, listen_port;
2636 /* sshbuf_dump(downstream->input, stderr); */
2637 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2639 error("%s: malformed message: %s", __func__, ssh_err(r));
2643 error("%s: short message", __func__);
2647 /* skip padlen + type */
2650 if (ssh_packet_log_type(type))
2651 debug3("%s: channel %u: down->up: type %u", __func__,
2652 downstream->self, type);
2655 case SSH2_MSG_CHANNEL_OPEN:
2656 if ((original = sshbuf_from(cp, have)) == NULL ||
2657 (modified = sshbuf_new()) == NULL) {
2658 error("%s: alloc", __func__);
2661 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2662 (r = sshbuf_get_u32(original, &id)) != 0) {
2663 error("%s: parse error %s", __func__, ssh_err(r));
2666 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2667 -1, -1, -1, 0, 0, 0, ctype, 1);
2668 c->mux_ctx = downstream; /* point to mux client */
2669 c->mux_downstream_id = id; /* original downstream id */
2670 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2671 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2672 (r = sshbuf_putb(modified, original)) != 0) {
2673 error("%s: compose error %s", __func__, ssh_err(r));
2674 channel_free(ssh, c);
2678 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2680 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2681 * need to parse 'remote_id' instead of 'ctype'.
2683 if ((original = sshbuf_from(cp, have)) == NULL ||
2684 (modified = sshbuf_new()) == NULL) {
2685 error("%s: alloc", __func__);
2688 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2689 (r = sshbuf_get_u32(original, &id)) != 0) {
2690 error("%s: parse error %s", __func__, ssh_err(r));
2693 c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2694 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2695 c->mux_ctx = downstream; /* point to mux client */
2696 c->mux_downstream_id = id;
2697 c->remote_id = remote_id;
2698 c->have_remote_id = 1;
2699 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2700 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2701 (r = sshbuf_putb(modified, original)) != 0) {
2702 error("%s: compose error %s", __func__, ssh_err(r));
2703 channel_free(ssh, c);
2707 case SSH2_MSG_GLOBAL_REQUEST:
2708 if ((original = sshbuf_from(cp, have)) == NULL) {
2709 error("%s: alloc", __func__);
2712 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2713 error("%s: parse error %s", __func__, ssh_err(r));
2716 if (strcmp(ctype, "tcpip-forward") != 0) {
2717 error("%s: unsupported request %s", __func__, ctype);
2720 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2721 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2722 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2723 error("%s: parse error %s", __func__, ssh_err(r));
2726 if (listen_port > 65535) {
2727 error("%s: tcpip-forward for %s: bad port %u",
2728 __func__, listen_host, listen_port);
2731 /* Record that connection to this host/port is permitted. */
2732 fwd_perm_list_add(ssh, FWDPERM_USER, "<mux>", -1,
2733 listen_host, NULL, (int)listen_port, downstream);
2736 case SSH2_MSG_CHANNEL_CLOSE:
2739 remote_id = PEEK_U32(cp);
2740 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2741 if (c->flags & CHAN_CLOSE_RCVD)
2742 channel_free(ssh, c);
2744 c->flags |= CHAN_CLOSE_SENT;
2749 if ((r = sshpkt_start(ssh, type)) != 0 ||
2750 (r = sshpkt_putb(ssh, modified)) != 0 ||
2751 (r = sshpkt_send(ssh)) != 0) {
2752 error("%s: send %s", __func__, ssh_err(r));
2756 if ((r = sshpkt_start(ssh, type)) != 0 ||
2757 (r = sshpkt_put(ssh, cp, have)) != 0 ||
2758 (r = sshpkt_send(ssh)) != 0) {
2759 error("%s: send %s", __func__, ssh_err(r));
2767 sshbuf_free(original);
2768 sshbuf_free(modified);
2773 * receive packets from upstream server and de-multiplex packets
2774 * to correct downstream:
2775 * implemented as a helper for channel input handlers,
2776 * replaces local (proxy) channel ID with downstream channel ID.
2779 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2781 struct sshbuf *b = NULL;
2782 Channel *downstream;
2783 const u_char *cp = NULL;
2788 * When receiving packets from the peer we need to check whether we
2789 * need to forward the packets to the mux client. In this case we
2790 * restore the orignal channel id and keep track of CLOSE messages,
2791 * so we can cleanup the channel.
2793 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2795 if ((downstream = c->mux_ctx) == NULL)
2798 case SSH2_MSG_CHANNEL_CLOSE:
2799 case SSH2_MSG_CHANNEL_DATA:
2800 case SSH2_MSG_CHANNEL_EOF:
2801 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
2802 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2803 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
2804 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
2805 case SSH2_MSG_CHANNEL_SUCCESS:
2806 case SSH2_MSG_CHANNEL_FAILURE:
2807 case SSH2_MSG_CHANNEL_REQUEST:
2810 debug2("%s: channel %u: unsupported type %u", __func__,
2814 if ((b = sshbuf_new()) == NULL) {
2815 error("%s: alloc reply", __func__);
2818 /* get remaining payload (after id) */
2819 cp = sshpkt_ptr(ssh, &len);
2821 error("%s: no packet", __func__);
2824 /* translate id and send to muxclient */
2825 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
2826 (r = sshbuf_put_u8(b, type)) != 0 ||
2827 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
2828 (r = sshbuf_put(b, cp, len)) != 0 ||
2829 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
2830 error("%s: compose for muxclient %s", __func__, ssh_err(r));
2833 /* sshbuf_dump(b, stderr); */
2834 if (ssh_packet_log_type(type))
2835 debug3("%s: channel %u: up->down: type %u", __func__, c->self,
2840 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2841 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
2842 if (cp && len > 4) {
2843 c->remote_id = PEEK_U32(cp);
2844 c->have_remote_id = 1;
2847 case SSH2_MSG_CHANNEL_CLOSE:
2848 if (c->flags & CHAN_CLOSE_SENT)
2849 channel_free(ssh, c);
2851 c->flags |= CHAN_CLOSE_RCVD;
2858 /* -- protocol input */
2860 /* Parse a channel ID from the current packet */
2862 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
2867 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
2868 error("%s: parse id: %s", where, ssh_err(r));
2869 ssh_packet_disconnect(ssh, "Invalid %s message", what);
2872 error("%s: bad channel id %u: %s", where, id, ssh_err(r));
2873 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
2878 /* Lookup a channel from an ID in the current packet */
2880 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
2882 int id = channel_parse_id(ssh, where, what);
2885 if ((c = channel_lookup(ssh, id)) == NULL) {
2886 ssh_packet_disconnect(ssh,
2887 "%s packet referred to nonexistent channel %d", what, id);
2893 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
2896 size_t data_len, win_len;
2897 Channel *c = channel_from_packet_id(ssh, __func__, "data");
2900 if (channel_proxy_upstream(c, type, seq, ssh))
2903 /* Ignore any data for non-open channels (might happen on close) */
2904 if (c->type != SSH_CHANNEL_OPEN &&
2905 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
2906 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
2907 c->type != SSH_CHANNEL_X11_OPEN)
2911 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0)
2912 fatal("%s: channel %d: get data: %s", __func__,
2913 c->self, ssh_err(r));
2914 ssh_packet_check_eom(ssh);
2918 win_len += 4; /* string length header */
2921 * The sending side reduces its window as it sends data, so we
2922 * must 'fake' consumption of the data in order to ensure that window
2923 * updates are sent back. Otherwise the connection might deadlock.
2925 if (c->ostate != CHAN_OUTPUT_OPEN) {
2926 c->local_window -= win_len;
2927 c->local_consumed += win_len;
2931 if (win_len > c->local_maxpacket) {
2932 logit("channel %d: rcvd big packet %zu, maxpack %u",
2933 c->self, win_len, c->local_maxpacket);
2936 if (win_len > c->local_window) {
2937 logit("channel %d: rcvd too much data %zu, win %u",
2938 c->self, win_len, c->local_window);
2941 c->local_window -= win_len;
2944 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
2945 fatal("%s: channel %d: append datagram: %s",
2946 __func__, c->self, ssh_err(r));
2947 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
2948 fatal("%s: channel %d: append data: %s",
2949 __func__, c->self, ssh_err(r));
2955 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
2960 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
2963 if (channel_proxy_upstream(c, type, seq, ssh))
2965 if (c->type != SSH_CHANNEL_OPEN) {
2966 logit("channel %d: ext data for non open", c->self);
2969 if (c->flags & CHAN_EOF_RCVD) {
2970 if (datafellows & SSH_BUG_EXTEOF)
2971 debug("channel %d: accepting ext data after eof",
2974 ssh_packet_disconnect(ssh, "Received extended_data "
2975 "after EOF on channel %d.", c->self);
2978 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
2979 error("%s: parse tcode: %s", __func__, ssh_err(r));
2980 ssh_packet_disconnect(ssh, "Invalid extended_data message");
2983 c->extended_usage != CHAN_EXTENDED_WRITE ||
2984 tcode != SSH2_EXTENDED_DATA_STDERR) {
2985 logit("channel %d: bad ext data", c->self);
2988 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0) {
2989 error("%s: parse data: %s", __func__, ssh_err(r));
2990 ssh_packet_disconnect(ssh, "Invalid extended_data message");
2992 ssh_packet_check_eom(ssh);
2994 if (data_len > c->local_window) {
2995 logit("channel %d: rcvd too much extended_data %zu, win %u",
2996 c->self, data_len, c->local_window);
2999 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3000 /* XXX sshpkt_getb? */
3001 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3002 error("%s: append: %s", __func__, ssh_err(r));
3003 c->local_window -= data_len;
3008 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3010 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3012 ssh_packet_check_eom(ssh);
3014 if (channel_proxy_upstream(c, type, seq, ssh))
3016 chan_rcvd_ieof(ssh, c);
3018 /* XXX force input close */
3019 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3020 debug("channel %d: FORCE input drain", c->self);
3021 c->istate = CHAN_INPUT_WAIT_DRAIN;
3022 if (sshbuf_len(c->input) == 0)
3023 chan_ibuf_empty(ssh, c);
3029 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3031 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3033 if (channel_proxy_upstream(c, type, seq, ssh))
3035 ssh_packet_check_eom(ssh);
3036 chan_rcvd_oclose(ssh, c);
3041 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3043 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3044 u_int32_t remote_window, remote_maxpacket;
3047 if (channel_proxy_upstream(c, type, seq, ssh))
3049 if (c->type != SSH_CHANNEL_OPENING)
3050 packet_disconnect("Received open confirmation for "
3051 "non-opening channel %d.", c->self);
3053 * Record the remote channel number and mark that the channel
3056 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3057 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3058 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0) {
3059 error("%s: window/maxpacket: %s", __func__, ssh_err(r));
3060 packet_disconnect("Invalid open confirmation message");
3062 ssh_packet_check_eom(ssh);
3064 c->have_remote_id = 1;
3065 c->remote_window = remote_window;
3066 c->remote_maxpacket = remote_maxpacket;
3067 c->type = SSH_CHANNEL_OPEN;
3068 if (c->open_confirm) {
3069 debug2("%s: channel %d: callback start", __func__, c->self);
3070 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3071 debug2("%s: channel %d: callback done", __func__, c->self);
3073 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3074 c->remote_window, c->remote_maxpacket);
3079 reason2txt(int reason)
3082 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3083 return "administratively prohibited";
3084 case SSH2_OPEN_CONNECT_FAILED:
3085 return "connect failed";
3086 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3087 return "unknown channel type";
3088 case SSH2_OPEN_RESOURCE_SHORTAGE:
3089 return "resource shortage";
3091 return "unknown reason";
3095 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3097 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3102 if (channel_proxy_upstream(c, type, seq, ssh))
3104 if (c->type != SSH_CHANNEL_OPENING)
3105 packet_disconnect("Received open failure for "
3106 "non-opening channel %d.", c->self);
3107 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3108 error("%s: reason: %s", __func__, ssh_err(r));
3109 packet_disconnect("Invalid open failure message");
3112 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3113 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0) {
3114 error("%s: message/lang: %s", __func__, ssh_err(r));
3115 packet_disconnect("Invalid open failure message");
3117 ssh_packet_check_eom(ssh);
3118 logit("channel %d: open failed: %s%s%s", c->self,
3119 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3121 if (c->open_confirm) {
3122 debug2("%s: channel %d: callback start", __func__, c->self);
3123 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3124 debug2("%s: channel %d: callback done", __func__, c->self);
3126 /* Schedule the channel for cleanup/deletion. */
3127 chan_mark_dead(ssh, c);
3132 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3134 int id = channel_parse_id(ssh, __func__, "window adjust");
3140 if ((c = channel_lookup(ssh, id)) == NULL) {
3141 logit("Received window adjust for non-open channel %d.", id);
3145 if (channel_proxy_upstream(c, type, seq, ssh))
3147 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0) {
3148 error("%s: adjust: %s", __func__, ssh_err(r));
3149 packet_disconnect("Invalid window adjust message");
3151 ssh_packet_check_eom(ssh);
3152 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3153 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3154 fatal("channel %d: adjust %u overflows remote window %u",
3155 c->self, adjust, c->remote_window);
3157 c->remote_window = new_rwin;
3162 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3164 int id = channel_parse_id(ssh, __func__, "status confirm");
3166 struct channel_confirm *cc;
3168 /* Reset keepalive timeout */
3169 packet_set_alive_timeouts(0);
3171 debug2("%s: type %d id %d", __func__, type, id);
3173 if ((c = channel_lookup(ssh, id)) == NULL) {
3174 logit("%s: %d: unknown", __func__, id);
3177 if (channel_proxy_upstream(c, type, seq, ssh))
3179 ssh_packet_check_eom(ssh);
3180 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3182 cc->cb(ssh, type, c, cc->ctx);
3183 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3184 explicit_bzero(cc, sizeof(*cc));
3189 /* -- tcp forwarding */
3192 channel_set_af(struct ssh *ssh, int af)
3194 ssh->chanctxt->IPv4or6 = af;
3199 * Determine whether or not a port forward listens to loopback, the
3200 * specified address or wildcard. On the client, a specified bind
3201 * address will always override gateway_ports. On the server, a
3202 * gateway_ports of 1 (``yes'') will override the client's specification
3203 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3204 * will bind to whatever address the client asked for.
3206 * Special-case listen_addrs are:
3208 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3209 * "" (empty string), "*" -> wildcard v4/v6
3210 * "localhost" -> loopback v4/v6
3211 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3214 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
3215 int is_client, struct ForwardOptions *fwd_opts)
3217 const char *addr = NULL;
3220 if (listen_addr == NULL) {
3221 /* No address specified: default to gateway_ports setting */
3222 if (fwd_opts->gateway_ports)
3224 } else if (fwd_opts->gateway_ports || is_client) {
3225 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
3226 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3227 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3228 (!is_client && fwd_opts->gateway_ports == 1)) {
3231 * Notify client if they requested a specific listen
3232 * address and it was overridden.
3234 if (*listen_addr != '\0' &&
3235 strcmp(listen_addr, "0.0.0.0") != 0 &&
3236 strcmp(listen_addr, "*") != 0) {
3237 packet_send_debug("Forwarding listen address "
3238 "\"%s\" overridden by server "
3239 "GatewayPorts", listen_addr);
3241 } else if (strcmp(listen_addr, "localhost") != 0 ||
3242 strcmp(listen_addr, "127.0.0.1") == 0 ||
3243 strcmp(listen_addr, "::1") == 0) {
3244 /* Accept localhost address when GatewayPorts=yes */
3247 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3248 strcmp(listen_addr, "::1") == 0) {
3250 * If a specific IPv4/IPv6 localhost address has been
3251 * requested then accept it even if gateway_ports is in
3252 * effect. This allows the client to prefer IPv4 or IPv6.
3256 if (wildcardp != NULL)
3257 *wildcardp = wildcard;
3262 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3263 struct Forward *fwd, int *allocated_listen_port,
3264 struct ForwardOptions *fwd_opts)
3267 int sock, r, success = 0, wildcard = 0, is_client;
3268 struct addrinfo hints, *ai, *aitop;
3269 const char *host, *addr;
3270 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3273 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3275 if (is_client && fwd->connect_path != NULL) {
3276 host = fwd->connect_path;
3278 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3279 fwd->listen_host : fwd->connect_host;
3281 error("No forward host name.");
3284 if (strlen(host) >= NI_MAXHOST) {
3285 error("Forward host name too long.");
3290 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3291 addr = channel_fwd_bind_addr(fwd->listen_host, &wildcard,
3292 is_client, fwd_opts);
3293 debug3("%s: type %d wildcard %d addr %s", __func__,
3294 type, wildcard, (addr == NULL) ? "NULL" : addr);
3297 * getaddrinfo returns a loopback address if the hostname is
3298 * set to NULL and hints.ai_flags is not AI_PASSIVE
3300 memset(&hints, 0, sizeof(hints));
3301 hints.ai_family = ssh->chanctxt->IPv4or6;
3302 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3303 hints.ai_socktype = SOCK_STREAM;
3304 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3305 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3307 /* This really shouldn't happen */
3308 packet_disconnect("getaddrinfo: fatal error: %s",
3309 ssh_gai_strerror(r));
3311 error("%s: getaddrinfo(%.64s): %s", __func__, addr,
3312 ssh_gai_strerror(r));
3316 if (allocated_listen_port != NULL)
3317 *allocated_listen_port = 0;
3318 for (ai = aitop; ai; ai = ai->ai_next) {
3319 switch (ai->ai_family) {
3321 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3325 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3332 * If allocating a port for -R forwards, then use the
3333 * same port for all address families.
3335 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3336 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3337 *allocated_listen_port > 0)
3338 *lport_p = htons(*allocated_listen_port);
3340 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3341 strport, sizeof(strport),
3342 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3343 error("%s: getnameinfo failed", __func__);
3346 /* Create a port to listen for the host. */
3347 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3349 /* this is no error since kernel may not support ipv6 */
3350 verbose("socket [%s]:%s: %.100s", ntop, strport,
3355 set_reuseaddr(sock);
3356 if (ai->ai_family == AF_INET6)
3357 sock_set_v6only(sock);
3359 debug("Local forwarding listening on %s port %s.",
3362 /* Bind the socket to the address. */
3363 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3365 * address can be in if use ipv6 address is
3369 error("bind [%s]:%s: %.100s",
3370 ntop, strport, strerror(errno));
3372 verbose("bind [%s]:%s: %.100s",
3373 ntop, strport, strerror(errno));
3378 /* Start listening for connections on the socket. */
3379 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3380 error("listen: %.100s", strerror(errno));
3381 error("listen [%s]:%s: %.100s", ntop, strport,
3388 * fwd->listen_port == 0 requests a dynamically allocated port -
3389 * record what we got.
3391 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3392 fwd->listen_port == 0 &&
3393 allocated_listen_port != NULL &&
3394 *allocated_listen_port == 0) {
3395 *allocated_listen_port = get_local_port(sock);
3396 debug("Allocated listen port %d",
3397 *allocated_listen_port);
3400 /* Allocate a channel number for the socket. */
3401 c = channel_new(ssh, "port listener", type, sock, sock, -1,
3402 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3403 0, "port listener", 1);
3404 c->path = xstrdup(host);
3405 c->host_port = fwd->connect_port;
3406 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3407 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3408 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
3409 c->listening_port = *allocated_listen_port;
3411 c->listening_port = fwd->listen_port;
3415 error("%s: cannot listen to port: %d", __func__,
3417 freeaddrinfo(aitop);
3422 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3423 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3425 struct sockaddr_un sunaddr;
3432 case SSH_CHANNEL_UNIX_LISTENER:
3433 if (fwd->connect_path != NULL) {
3434 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3435 error("Local connecting path too long: %s",
3439 path = fwd->connect_path;
3440 port = PORT_STREAMLOCAL;
3442 if (fwd->connect_host == NULL) {
3443 error("No forward host name.");
3446 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3447 error("Forward host name too long.");
3450 path = fwd->connect_host;
3451 port = fwd->connect_port;
3454 case SSH_CHANNEL_RUNIX_LISTENER:
3455 path = fwd->listen_path;
3456 port = PORT_STREAMLOCAL;
3459 error("%s: unexpected channel type %d", __func__, type);
3463 if (fwd->listen_path == NULL) {
3464 error("No forward path name.");
3467 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3468 error("Local listening path too long: %s", fwd->listen_path);
3472 debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
3474 /* Start a Unix domain listener. */
3475 omask = umask(fwd_opts->streamlocal_bind_mask);
3476 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3477 fwd_opts->streamlocal_bind_unlink);
3482 debug("Local forwarding listening on path %s.", fwd->listen_path);
3484 /* Allocate a channel number for the socket. */
3485 c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3486 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3487 0, "unix listener", 1);
3488 c->path = xstrdup(path);
3489 c->host_port = port;
3490 c->listening_port = PORT_STREAMLOCAL;
3491 c->listening_addr = xstrdup(fwd->listen_path);
3496 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3497 const char *host, u_short port)
3502 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3503 Channel *c = ssh->chanctxt->channels[i];
3504 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3506 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3507 debug2("%s: close channel %d", __func__, i);
3508 channel_free(ssh, c);
3517 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3522 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3523 Channel *c = ssh->chanctxt->channels[i];
3524 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3526 if (c->path == NULL)
3528 if (strcmp(c->path, path) == 0) {
3529 debug2("%s: close channel %d", __func__, i);
3530 channel_free(ssh, c);
3539 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3541 if (fwd->listen_path != NULL) {
3542 return channel_cancel_rport_listener_streamlocal(ssh,
3545 return channel_cancel_rport_listener_tcpip(ssh,
3546 fwd->listen_host, fwd->listen_port);
3551 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3552 const char *lhost, u_short lport, int cport,
3553 struct ForwardOptions *fwd_opts)
3557 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, fwd_opts);
3559 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3560 Channel *c = ssh->chanctxt->channels[i];
3561 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3563 if (c->listening_port != lport)
3565 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3566 /* skip dynamic forwardings */
3567 if (c->host_port == 0)
3570 if (c->host_port != cport)
3573 if ((c->listening_addr == NULL && addr != NULL) ||
3574 (c->listening_addr != NULL && addr == NULL))
3576 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3577 debug2("%s: close channel %d", __func__, i);
3578 channel_free(ssh, c);
3587 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3593 error("%s: no path specified.", __func__);
3597 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3598 Channel *c = ssh->chanctxt->channels[i];
3599 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3601 if (c->listening_addr == NULL)
3603 if (strcmp(c->listening_addr, path) == 0) {
3604 debug2("%s: close channel %d", __func__, i);
3605 channel_free(ssh, c);
3614 channel_cancel_lport_listener(struct ssh *ssh,
3615 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3617 if (fwd->listen_path != NULL) {
3618 return channel_cancel_lport_listener_streamlocal(ssh,
3621 return channel_cancel_lport_listener_tcpip(ssh,
3622 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3626 /* protocol local port fwd, used by ssh */
3628 channel_setup_local_fwd_listener(struct ssh *ssh,
3629 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3631 if (fwd->listen_path != NULL) {
3632 return channel_setup_fwd_listener_streamlocal(ssh,
3633 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3635 return channel_setup_fwd_listener_tcpip(ssh,
3636 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3640 /* protocol v2 remote port fwd, used by sshd */
3642 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
3643 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3645 if (fwd->listen_path != NULL) {
3646 return channel_setup_fwd_listener_streamlocal(ssh,
3647 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3649 return channel_setup_fwd_listener_tcpip(ssh,
3650 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3656 * Translate the requested rfwd listen host to something usable for
3660 channel_rfwd_bind_host(const char *listen_host)
3662 if (listen_host == NULL) {
3664 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3671 * Initiate forwarding of connections to port "port" on remote host through
3672 * the secure channel to host:port from local side.
3673 * Returns handle (index) for updating the dynamic listen port with
3674 * channel_update_permitted_opens().
3677 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
3679 int r, success = 0, idx = -1;
3680 char *host_to_connect, *listen_host, *listen_path;
3681 int port_to_connect, listen_port;
3683 /* Send the forward request to the remote side. */
3684 if (fwd->listen_path != NULL) {
3685 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3686 (r = sshpkt_put_cstring(ssh,
3687 "streamlocal-forward@openssh.com")) != 0 ||
3688 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3689 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
3690 (r = sshpkt_send(ssh)) != 0 ||
3691 (r = ssh_packet_write_wait(ssh)) != 0)
3692 fatal("%s: request streamlocal: %s",
3693 __func__, ssh_err(r));
3695 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3696 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
3697 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
3698 (r = sshpkt_put_cstring(ssh,
3699 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
3700 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
3701 (r = sshpkt_send(ssh)) != 0 ||
3702 (r = ssh_packet_write_wait(ssh)) != 0)
3703 fatal("%s: request tcpip-forward: %s",
3704 __func__, ssh_err(r));
3706 /* Assume that server accepts the request */
3709 /* Record that connection to this host/port is permitted. */
3710 host_to_connect = listen_host = listen_path = NULL;
3711 port_to_connect = listen_port = 0;
3712 if (fwd->connect_path != NULL) {
3713 host_to_connect = xstrdup(fwd->connect_path);
3714 port_to_connect = PORT_STREAMLOCAL;
3716 host_to_connect = xstrdup(fwd->connect_host);
3717 port_to_connect = fwd->connect_port;
3719 if (fwd->listen_path != NULL) {
3720 listen_path = xstrdup(fwd->listen_path);
3721 listen_port = PORT_STREAMLOCAL;
3723 if (fwd->listen_host != NULL)
3724 listen_host = xstrdup(fwd->listen_host);
3725 listen_port = fwd->listen_port;
3727 idx = fwd_perm_list_add(ssh, FWDPERM_USER,
3728 host_to_connect, port_to_connect,
3729 listen_host, listen_path, listen_port, NULL);
3735 open_match(ForwardPermission *allowed_open, const char *requestedhost,
3738 if (allowed_open->host_to_connect == NULL)
3740 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3741 allowed_open->port_to_connect != requestedport)
3743 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3744 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3750 * Note that in the listen host/port case
3751 * we don't support FWD_PERMIT_ANY_PORT and
3752 * need to translate between the configured-host (listen_host)
3753 * and what we've sent to the remote server (channel_rfwd_bind_host)
3756 open_listen_match_tcpip(ForwardPermission *allowed_open,
3757 const char *requestedhost, u_short requestedport, int translate)
3759 const char *allowed_host;
3761 if (allowed_open->host_to_connect == NULL)
3763 if (allowed_open->listen_port != requestedport)
3765 if (!translate && allowed_open->listen_host == NULL &&
3766 requestedhost == NULL)
3768 allowed_host = translate ?
3769 channel_rfwd_bind_host(allowed_open->listen_host) :
3770 allowed_open->listen_host;
3771 if (allowed_host == NULL ||
3772 strcmp(allowed_host, requestedhost) != 0)
3778 open_listen_match_streamlocal(ForwardPermission *allowed_open,
3779 const char *requestedpath)
3781 if (allowed_open->host_to_connect == NULL)
3783 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3785 if (allowed_open->listen_path == NULL ||
3786 strcmp(allowed_open->listen_path, requestedpath) != 0)
3792 * Request cancellation of remote forwarding of connection host:port from
3796 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
3797 const char *host, u_short port)
3799 struct ssh_channels *sc = ssh->chanctxt;
3802 ForwardPermission *fp;
3804 for (i = 0; i < sc->num_permitted_opens; i++) {
3805 fp = &sc->permitted_opens[i];
3806 if (open_listen_match_tcpip(fp, host, port, 0))
3811 debug("%s: requested forward not found", __func__);
3814 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3815 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
3816 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3817 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
3818 (r = sshpkt_put_u32(ssh, port)) != 0 ||
3819 (r = sshpkt_send(ssh)) != 0)
3820 fatal("%s: send cancel: %s", __func__, ssh_err(r));
3822 fwd_perm_clear(fp); /* unregister */
3828 * Request cancellation of remote forwarding of Unix domain socket
3829 * path from local side.
3832 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
3834 struct ssh_channels *sc = ssh->chanctxt;
3837 ForwardPermission *fp;
3839 for (i = 0; i < sc->num_permitted_opens; i++) {
3840 fp = &sc->permitted_opens[i];
3841 if (open_listen_match_streamlocal(fp, path))
3846 debug("%s: requested forward not found", __func__);
3849 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
3850 (r = sshpkt_put_cstring(ssh,
3851 "cancel-streamlocal-forward@openssh.com")) != 0 ||
3852 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
3853 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
3854 (r = sshpkt_send(ssh)) != 0)
3855 fatal("%s: send cancel: %s", __func__, ssh_err(r));
3857 fwd_perm_clear(fp); /* unregister */
3863 * Request cancellation of remote forwarding of a connection from local side.
3866 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
3868 if (fwd->listen_path != NULL) {
3869 return channel_request_rforward_cancel_streamlocal(ssh,
3872 return channel_request_rforward_cancel_tcpip(ssh,
3874 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
3879 * Permits opening to any host/port if permitted_opens[] is empty. This is
3880 * usually called by the server, because the user could connect to any port
3881 * anyway, and the server has no way to know but to trust the client anyway.
3884 channel_permit_all_opens(struct ssh *ssh)
3886 if (ssh->chanctxt->num_permitted_opens == 0)
3887 ssh->chanctxt->all_opens_permitted = 1;
3891 channel_add_permitted_opens(struct ssh *ssh, char *host, int port)
3893 struct ssh_channels *sc = ssh->chanctxt;
3895 debug("allow port forwarding to host %s port %d", host, port);
3896 fwd_perm_list_add(ssh, FWDPERM_USER, host, port, NULL, NULL, 0, NULL);
3897 sc->all_opens_permitted = 0;
3901 * Update the listen port for a dynamic remote forward, after
3902 * the actual 'newport' has been allocated. If 'newport' < 0 is
3903 * passed then they entry will be invalidated.
3906 channel_update_permitted_opens(struct ssh *ssh, int idx, int newport)
3908 struct ssh_channels *sc = ssh->chanctxt;
3910 if (idx < 0 || (u_int)idx >= sc->num_permitted_opens) {
3911 debug("%s: index out of range: %d num_permitted_opens %d",
3912 __func__, idx, sc->num_permitted_opens);
3915 debug("%s allowed port %d for forwarding to host %s port %d",
3916 newport > 0 ? "Updating" : "Removing",
3918 sc->permitted_opens[idx].host_to_connect,
3919 sc->permitted_opens[idx].port_to_connect);
3921 fwd_perm_clear(&sc->permitted_opens[idx]);
3923 sc->permitted_opens[idx].listen_port =
3924 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3929 channel_add_adm_permitted_opens(struct ssh *ssh, char *host, int port)
3931 debug("config allows port forwarding to host %s port %d", host, port);
3932 return fwd_perm_list_add(ssh, FWDPERM_ADMIN, host, port,
3933 NULL, NULL, 0, NULL);
3937 channel_disable_adm_local_opens(struct ssh *ssh)
3939 channel_clear_adm_permitted_opens(ssh);
3940 fwd_perm_list_add(ssh, FWDPERM_ADMIN, NULL, 0, NULL, NULL, 0, NULL);
3944 channel_clear_permitted_opens(struct ssh *ssh)
3946 struct ssh_channels *sc = ssh->chanctxt;
3948 sc->permitted_opens = xrecallocarray(sc->permitted_opens,
3949 sc->num_permitted_opens, 0, sizeof(*sc->permitted_opens));
3950 sc->num_permitted_opens = 0;
3954 channel_clear_adm_permitted_opens(struct ssh *ssh)
3956 struct ssh_channels *sc = ssh->chanctxt;
3958 sc->permitted_adm_opens = xrecallocarray(sc->permitted_adm_opens,
3959 sc->num_adm_permitted_opens, 0, sizeof(*sc->permitted_adm_opens));
3960 sc->num_adm_permitted_opens = 0;
3963 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3965 permitopen_port(const char *p)
3969 if (strcmp(p, "*") == 0)
3970 return FWD_PERMIT_ANY_PORT;
3971 if ((port = a2port(p)) > 0)
3976 /* Try to start non-blocking connect to next host in cctx list */
3978 connect_next(struct channel_connect *cctx)
3980 int sock, saved_errno;
3981 struct sockaddr_un *sunaddr;
3982 char ntop[NI_MAXHOST];
3983 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
3985 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3986 switch (cctx->ai->ai_family) {
3988 /* unix:pathname instead of host:port */
3989 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
3990 strlcpy(ntop, "unix", sizeof(ntop));
3991 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
3995 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3996 ntop, sizeof(ntop), strport, sizeof(strport),
3997 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3998 error("connect_next: getnameinfo failed");
4005 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4006 cctx->ai->ai_protocol)) == -1) {
4007 if (cctx->ai->ai_next == NULL)
4008 error("socket: %.100s", strerror(errno));
4010 verbose("socket: %.100s", strerror(errno));
4013 if (set_nonblock(sock) == -1)
4014 fatal("%s: set_nonblock(%d)", __func__, sock);
4015 if (connect(sock, cctx->ai->ai_addr,
4016 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4017 debug("connect_next: host %.100s ([%.100s]:%s): "
4018 "%.100s", cctx->host, ntop, strport,
4020 saved_errno = errno;
4022 errno = saved_errno;
4023 continue; /* fail -- try next */
4025 if (cctx->ai->ai_family != AF_UNIX)
4027 debug("connect_next: host %.100s ([%.100s]:%s) "
4028 "in progress, fd=%d", cctx->host, ntop, strport, sock);
4029 cctx->ai = cctx->ai->ai_next;
4036 channel_connect_ctx_free(struct channel_connect *cctx)
4040 if (cctx->aitop->ai_family == AF_UNIX)
4043 freeaddrinfo(cctx->aitop);
4045 memset(cctx, 0, sizeof(*cctx));
4049 * Return connecting socket to remote host:port or local socket path,
4050 * passing back the failure reason if appropriate.
4053 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4054 char *ctype, char *rname, struct channel_connect *cctx,
4055 int *reason, const char **errmsg)
4057 struct addrinfo hints;
4060 char strport[NI_MAXSERV];
4062 if (port == PORT_STREAMLOCAL) {
4063 struct sockaddr_un *sunaddr;
4064 struct addrinfo *ai;
4066 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4067 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4072 * Fake up a struct addrinfo for AF_UNIX connections.
4073 * channel_connect_ctx_free() must check ai_family
4074 * and use free() not freeaddirinfo() for AF_UNIX.
4076 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4077 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4078 ai->ai_addr = (struct sockaddr *)(ai + 1);
4079 ai->ai_addrlen = sizeof(*sunaddr);
4080 ai->ai_family = AF_UNIX;
4081 ai->ai_socktype = socktype;
4082 ai->ai_protocol = PF_UNSPEC;
4083 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4084 sunaddr->sun_family = AF_UNIX;
4085 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4088 memset(&hints, 0, sizeof(hints));
4089 hints.ai_family = ssh->chanctxt->IPv4or6;
4090 hints.ai_socktype = socktype;
4091 snprintf(strport, sizeof strport, "%d", port);
4092 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4095 *errmsg = ssh_gai_strerror(gaierr);
4097 *reason = SSH2_OPEN_CONNECT_FAILED;
4098 error("connect_to %.100s: unknown host (%s)", name,
4099 ssh_gai_strerror(gaierr));
4104 cctx->host = xstrdup(name);
4106 cctx->ai = cctx->aitop;
4108 if ((sock = connect_next(cctx)) == -1) {
4109 error("connect to %.100s port %d failed: %s",
4110 name, port, strerror(errno));
4117 /* Return CONNECTING channel to remote host:port or local socket path */
4119 connect_to(struct ssh *ssh, const char *host, int port,
4120 char *ctype, char *rname)
4122 struct channel_connect cctx;
4126 memset(&cctx, 0, sizeof(cctx));
4127 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4130 channel_connect_ctx_free(&cctx);
4133 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4134 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4135 c->host_port = port;
4136 c->path = xstrdup(host);
4137 c->connect_ctx = cctx;
4143 * returns either the newly connected channel or the downstream channel
4144 * that needs to deal with this connection.
4147 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4148 u_short listen_port, char *ctype, char *rname)
4150 struct ssh_channels *sc = ssh->chanctxt;
4152 ForwardPermission *fp;
4154 for (i = 0; i < sc->num_permitted_opens; i++) {
4155 fp = &sc->permitted_opens[i];
4156 if (open_listen_match_tcpip(fp, listen_host, listen_port, 1)) {
4158 return fp->downstream;
4159 if (fp->port_to_connect == 0)
4160 return rdynamic_connect_prepare(ssh,
4162 return connect_to(ssh,
4163 fp->host_to_connect, fp->port_to_connect,
4167 error("WARNING: Server requests forwarding for unknown listen_port %d",
4173 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4174 char *ctype, char *rname)
4176 struct ssh_channels *sc = ssh->chanctxt;
4178 ForwardPermission *fp;
4180 for (i = 0; i < sc->num_permitted_opens; i++) {
4181 fp = &sc->permitted_opens[i];
4182 if (open_listen_match_streamlocal(fp, path)) {
4183 return connect_to(ssh,
4184 fp->host_to_connect, fp->port_to_connect,
4188 error("WARNING: Server requests forwarding for unknown path %.100s",
4193 /* Check if connecting to that port is permitted and connect. */
4195 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4196 char *ctype, char *rname, int *reason, const char **errmsg)
4198 struct ssh_channels *sc = ssh->chanctxt;
4199 struct channel_connect cctx;
4201 u_int i, permit, permit_adm = 1;
4203 ForwardPermission *fp;
4205 permit = sc->all_opens_permitted;
4207 for (i = 0; i < sc->num_permitted_opens; i++) {
4208 fp = &sc->permitted_opens[i];
4209 if (open_match(fp, host, port)) {
4216 if (sc->num_adm_permitted_opens > 0) {
4218 for (i = 0; i < sc->num_adm_permitted_opens; i++) {
4219 fp = &sc->permitted_adm_opens[i];
4220 if (open_match(fp, host, port)) {
4227 if (!permit || !permit_adm) {
4228 logit("Received request to connect to host %.100s port %d, "
4229 "but the request was denied.", host, port);
4231 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4235 memset(&cctx, 0, sizeof(cctx));
4236 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4237 &cctx, reason, errmsg);
4239 channel_connect_ctx_free(&cctx);
4243 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4244 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4245 c->host_port = port;
4246 c->path = xstrdup(host);
4247 c->connect_ctx = cctx;
4252 /* Check if connecting to that path is permitted and connect. */
4254 channel_connect_to_path(struct ssh *ssh, const char *path,
4255 char *ctype, char *rname)
4257 struct ssh_channels *sc = ssh->chanctxt;
4258 u_int i, permit, permit_adm = 1;
4259 ForwardPermission *fp;
4261 permit = sc->all_opens_permitted;
4263 for (i = 0; i < sc->num_permitted_opens; i++) {
4264 fp = &sc->permitted_opens[i];
4265 if (open_match(fp, path, PORT_STREAMLOCAL)) {
4272 if (sc->num_adm_permitted_opens > 0) {
4274 for (i = 0; i < sc->num_adm_permitted_opens; i++) {
4275 fp = &sc->permitted_adm_opens[i];
4276 if (open_match(fp, path, PORT_STREAMLOCAL)) {
4283 if (!permit || !permit_adm) {
4284 logit("Received request to connect to path %.100s, "
4285 "but the request was denied.", path);
4288 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4292 channel_send_window_changes(struct ssh *ssh)
4294 struct ssh_channels *sc = ssh->chanctxt;
4299 for (i = 0; i < sc->channels_alloc; i++) {
4300 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4301 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4303 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
4305 channel_request_start(ssh, i, "window-change", 0);
4306 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4307 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4308 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4309 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4310 (r = sshpkt_send(ssh)) != 0)
4311 fatal("%s: channel %u: send window-change: %s",
4312 __func__, i, ssh_err(r));
4316 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4318 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4323 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4324 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4329 * We need to open the channel before we have a FD,
4330 * so that we can get SOCKS header from peer.
4332 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4333 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4334 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4335 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4336 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
4337 fatal("%s: channel %i: confirm: %s", __func__,
4338 c->self, ssh_err(r));
4343 /* Return CONNECTING socket to remote host:port or local socket path */
4345 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4347 struct channel_connect cctx;
4350 memset(&cctx, 0, sizeof(cctx));
4351 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4352 NULL, &cctx, NULL, NULL);
4354 channel_connect_ctx_free(&cctx);
4356 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4357 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4358 c->connect_ctx = cctx;
4359 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4364 /* -- X11 forwarding */
4367 * Creates an internet domain socket for listening for X11 connections.
4368 * Returns 0 and a suitable display number for the DISPLAY variable
4369 * stored in display_numberp , or -1 if an error occurs.
4372 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4373 int x11_use_localhost, int single_connection,
4374 u_int *display_numberp, int **chanids)
4377 int display_number, sock;
4379 struct addrinfo hints, *ai, *aitop;
4380 char strport[NI_MAXSERV];
4381 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4383 if (chanids == NULL)
4386 for (display_number = x11_display_offset;
4387 display_number < MAX_DISPLAYS;
4389 port = 6000 + display_number;
4390 memset(&hints, 0, sizeof(hints));
4391 hints.ai_family = ssh->chanctxt->IPv4or6;
4392 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4393 hints.ai_socktype = SOCK_STREAM;
4394 snprintf(strport, sizeof strport, "%d", port);
4395 if ((gaierr = getaddrinfo(NULL, strport,
4396 &hints, &aitop)) != 0) {
4397 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4400 for (ai = aitop; ai; ai = ai->ai_next) {
4401 if (ai->ai_family != AF_INET &&
4402 ai->ai_family != AF_INET6)
4404 sock = socket(ai->ai_family, ai->ai_socktype,
4407 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4409 && (errno != EPFNOSUPPORT)
4412 error("socket: %.100s", strerror(errno));
4413 freeaddrinfo(aitop);
4416 debug("x11_create_display_inet: Socket family %d not supported",
4421 if (ai->ai_family == AF_INET6)
4422 sock_set_v6only(sock);
4423 if (x11_use_localhost)
4424 set_reuseaddr(sock);
4425 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4426 debug2("%s: bind port %d: %.100s", __func__,
4427 port, strerror(errno));
4429 for (n = 0; n < num_socks; n++)
4434 socks[num_socks++] = sock;
4435 if (num_socks == NUM_SOCKS)
4438 freeaddrinfo(aitop);
4442 if (display_number >= MAX_DISPLAYS) {
4443 error("Failed to allocate internet-domain X11 display socket.");
4446 /* Start listening for connections on the socket. */
4447 for (n = 0; n < num_socks; n++) {
4449 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
4450 error("listen: %.100s", strerror(errno));
4456 /* Allocate a channel for each socket. */
4457 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4458 for (n = 0; n < num_socks; n++) {
4460 nc = channel_new(ssh, "x11 listener",
4461 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4462 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4463 0, "X11 inet listener", 1);
4464 nc->single_connection = single_connection;
4465 (*chanids)[n] = nc->self;
4469 /* Return the display number for the DISPLAY environment variable. */
4470 *display_numberp = display_number;
4475 connect_local_xsocket_path(const char *pathname)
4478 struct sockaddr_un addr;
4480 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4482 error("socket: %.100s", strerror(errno));
4483 memset(&addr, 0, sizeof(addr));
4484 addr.sun_family = AF_UNIX;
4485 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4486 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4489 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4494 connect_local_xsocket(u_int dnr)
4497 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4498 return connect_local_xsocket_path(buf);
4503 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4507 if (strlcpy(path, display, pathlen) >= pathlen) {
4508 error("%s: display path too long", __func__);
4511 if (display[0] != '/')
4513 if (stat(path, &sbuf) == 0) {
4516 char *dot = strrchr(path, '.');
4519 if (stat(path, &sbuf) == 0) {
4529 x11_connect_display(struct ssh *ssh)
4531 u_int display_number;
4532 const char *display;
4533 char buf[1024], *cp;
4534 struct addrinfo hints, *ai, *aitop;
4535 char strport[NI_MAXSERV];
4536 int gaierr, sock = 0;
4538 /* Try to open a socket for the local X server. */
4539 display = getenv("DISPLAY");
4541 error("DISPLAY not set.");
4545 * Now we decode the value of the DISPLAY variable and make a
4546 * connection to the real X server.
4550 /* Check if display is a path to a socket (as set by launchd). */
4552 char path[PATH_MAX];
4554 if (is_path_to_xsocket(display, path, sizeof(path))) {
4555 debug("x11_connect_display: $DISPLAY is launchd");
4557 /* Create a socket. */
4558 sock = connect_local_xsocket_path(path);
4562 /* OK, we now have a connection to the display. */
4568 * Check if it is a unix domain socket. Unix domain displays are in
4569 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4571 if (strncmp(display, "unix:", 5) == 0 ||
4572 display[0] == ':') {
4573 /* Connect to the unix domain socket. */
4574 if (sscanf(strrchr(display, ':') + 1, "%u",
4575 &display_number) != 1) {
4576 error("Could not parse display number from DISPLAY: "
4580 /* Create a socket. */
4581 sock = connect_local_xsocket(display_number);
4585 /* OK, we now have a connection to the display. */
4589 * Connect to an inet socket. The DISPLAY value is supposedly
4590 * hostname:d[.s], where hostname may also be numeric IP address.
4592 strlcpy(buf, display, sizeof(buf));
4593 cp = strchr(buf, ':');
4595 error("Could not find ':' in DISPLAY: %.100s", display);
4600 * buf now contains the host name. But first we parse the
4603 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4604 error("Could not parse display number from DISPLAY: %.100s",
4609 /* Look up the host address */
4610 memset(&hints, 0, sizeof(hints));
4611 hints.ai_family = ssh->chanctxt->IPv4or6;
4612 hints.ai_socktype = SOCK_STREAM;
4613 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4614 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4615 error("%.100s: unknown host. (%s)", buf,
4616 ssh_gai_strerror(gaierr));
4619 for (ai = aitop; ai; ai = ai->ai_next) {
4620 /* Create a socket. */
4621 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4623 debug2("socket: %.100s", strerror(errno));
4626 /* Connect it to the display. */
4627 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4628 debug2("connect %.100s port %u: %.100s", buf,
4629 6000 + display_number, strerror(errno));
4636 freeaddrinfo(aitop);
4638 error("connect %.100s port %u: %.100s", buf,
4639 6000 + display_number, strerror(errno));
4647 * Requests forwarding of X11 connections, generates fake authentication
4648 * data, and enables authentication spoofing.
4649 * This should be called in the client only.
4652 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
4653 const char *disp, const char *proto, const char *data, int want_reply)
4655 struct ssh_channels *sc = ssh->chanctxt;
4656 u_int data_len = (u_int) strlen(data) / 2;
4660 int r, screen_number;
4662 if (sc->x11_saved_display == NULL)
4663 sc->x11_saved_display = xstrdup(disp);
4664 else if (strcmp(disp, sc->x11_saved_display) != 0) {
4665 error("x11_request_forwarding_with_spoofing: different "
4666 "$DISPLAY already forwarded");
4670 cp = strchr(disp, ':');
4672 cp = strchr(cp, '.');
4674 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4678 if (sc->x11_saved_proto == NULL) {
4679 /* Save protocol name. */
4680 sc->x11_saved_proto = xstrdup(proto);
4682 /* Extract real authentication data. */
4683 sc->x11_saved_data = xmalloc(data_len);
4684 for (i = 0; i < data_len; i++) {
4685 if (sscanf(data + 2 * i, "%2x", &value) != 1)
4686 fatal("x11_request_forwarding: bad "
4687 "authentication data: %.100s", data);
4688 sc->x11_saved_data[i] = value;
4690 sc->x11_saved_data_len = data_len;
4692 /* Generate fake data of the same length. */
4693 sc->x11_fake_data = xmalloc(data_len);
4694 arc4random_buf(sc->x11_fake_data, data_len);
4695 sc->x11_fake_data_len = data_len;
4698 /* Convert the fake data into hex. */
4699 new_data = tohex(sc->x11_fake_data, data_len);
4701 /* Send the request packet. */
4702 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
4703 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
4704 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
4705 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
4706 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
4707 (r = sshpkt_send(ssh)) != 0 ||
4708 (r = ssh_packet_write_wait(ssh)) != 0)
4709 fatal("%s: send x11-req: %s", __func__, ssh_err(r));