Sync zoneinfo database with tzdata2016j from ftp://ftp.iana.org/tz/releases
[dragonfly.git] / crypto / openssh / channels.c
blob9f9e972f4291982427ec6e70774a519d038bf3ab
1 /* $OpenBSD: channels.c,v 1.351 2016/07/19 11:38:53 dtucker Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
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
23 * are met:
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.
42 #include "includes.h"
44 #include <sys/types.h>
45 #include <sys/param.h> /* MIN MAX */
46 #include <sys/stat.h>
47 #include <sys/ioctl.h>
48 #include <sys/un.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_TIME_H
51 # include <sys/time.h>
52 #endif
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <netdb.h>
60 #ifdef HAVE_STDINT_H
61 #include <stdint.h>
62 #endif
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <termios.h>
67 #include <unistd.h>
68 #include <stdarg.h>
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "ssh.h"
73 #include "ssh1.h"
74 #include "ssh2.h"
75 #include "packet.h"
76 #include "log.h"
77 #include "misc.h"
78 #include "buffer.h"
79 #include "channels.h"
80 #include "compat.h"
81 #include "canohost.h"
82 #include "key.h"
83 #include "authfd.h"
84 #include "pathnames.h"
86 /* -- channel core */
89 * Pointer to an array containing all allocated channels. The array is
90 * dynamically extended as needed.
92 static Channel **channels = NULL;
95 * Size of the channel array. All slots of the array must always be
96 * initialized (at least the type field); unused slots set to NULL
98 static u_int channels_alloc = 0;
101 * Maximum file descriptor value used in any of the channels. This is
102 * updated in channel_new.
104 static int channel_max_fd = 0;
107 /* -- tcp forwarding */
110 * Data structure for storing which hosts are permitted for forward requests.
111 * The local sides of any remote forwards are stored in this array to prevent
112 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
113 * network (which might be behind a firewall).
115 /* XXX: streamlocal wants a path instead of host:port */
116 /* Overload host_to_connect; we could just make this match Forward */
117 /* XXX - can we use listen_host instead of listen_path? */
118 typedef struct {
119 char *host_to_connect; /* Connect to 'host'. */
120 int port_to_connect; /* Connect to 'port'. */
121 char *listen_host; /* Remote side should listen address. */
122 char *listen_path; /* Remote side should listen path. */
123 int listen_port; /* Remote side should listen port. */
124 } ForwardPermission;
126 /* List of all permitted host/port pairs to connect by the user. */
127 static ForwardPermission *permitted_opens = NULL;
129 /* List of all permitted host/port pairs to connect by the admin. */
130 static ForwardPermission *permitted_adm_opens = NULL;
132 /* Number of permitted host/port pairs in the array permitted by the user. */
133 static int num_permitted_opens = 0;
135 /* Number of permitted host/port pair in the array permitted by the admin. */
136 static int num_adm_permitted_opens = 0;
138 /* special-case port number meaning allow any port */
139 #define FWD_PERMIT_ANY_PORT 0
141 /* special-case wildcard meaning allow any host */
142 #define FWD_PERMIT_ANY_HOST "*"
145 * If this is true, all opens are permitted. This is the case on the server
146 * on which we have to trust the client anyway, and the user could do
147 * anything after logging in anyway.
149 static int all_opens_permitted = 0;
152 /* -- X11 forwarding */
154 /* Maximum number of fake X11 displays to try. */
155 #define MAX_DISPLAYS 1000
157 /* Saved X11 local (client) display. */
158 static char *x11_saved_display = NULL;
160 /* Saved X11 authentication protocol name. */
161 static char *x11_saved_proto = NULL;
163 /* Saved X11 authentication data. This is the real data. */
164 static char *x11_saved_data = NULL;
165 static u_int x11_saved_data_len = 0;
167 /* Deadline after which all X11 connections are refused */
168 static u_int x11_refuse_time;
171 * Fake X11 authentication data. This is what the server will be sending us;
172 * we should replace any occurrences of this by the real data.
174 static u_char *x11_fake_data = NULL;
175 static u_int x11_fake_data_len;
178 /* -- agent forwarding */
180 #define NUM_SOCKS 10
182 /* AF_UNSPEC or AF_INET or AF_INET6 */
183 static int IPv4or6 = AF_UNSPEC;
185 /* helper */
186 static void port_open_helper(Channel *c, char *rtype);
188 /* non-blocking connect helpers */
189 static int connect_next(struct channel_connect *);
190 static void channel_connect_ctx_free(struct channel_connect *);
192 /* -- channel core */
194 Channel *
195 channel_by_id(int id)
197 Channel *c;
199 if (id < 0 || (u_int)id >= channels_alloc) {
200 logit("channel_by_id: %d: bad id", id);
201 return NULL;
203 c = channels[id];
204 if (c == NULL) {
205 logit("channel_by_id: %d: bad id: channel free", id);
206 return NULL;
208 return c;
212 * Returns the channel if it is allowed to receive protocol messages.
213 * Private channels, like listening sockets, may not receive messages.
215 Channel *
216 channel_lookup(int id)
218 Channel *c;
220 if ((c = channel_by_id(id)) == NULL)
221 return (NULL);
223 switch (c->type) {
224 case SSH_CHANNEL_X11_OPEN:
225 case SSH_CHANNEL_LARVAL:
226 case SSH_CHANNEL_CONNECTING:
227 case SSH_CHANNEL_DYNAMIC:
228 case SSH_CHANNEL_OPENING:
229 case SSH_CHANNEL_OPEN:
230 case SSH_CHANNEL_INPUT_DRAINING:
231 case SSH_CHANNEL_OUTPUT_DRAINING:
232 case SSH_CHANNEL_ABANDONED:
233 return (c);
235 logit("Non-public channel %d, type %d.", id, c->type);
236 return (NULL);
240 * Register filedescriptors for a channel, used when allocating a channel or
241 * when the channel consumer/producer is ready, e.g. shell exec'd
243 static void
244 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
245 int extusage, int nonblock, int is_tty)
247 /* Update the maximum file descriptor value. */
248 channel_max_fd = MAX(channel_max_fd, rfd);
249 channel_max_fd = MAX(channel_max_fd, wfd);
250 channel_max_fd = MAX(channel_max_fd, efd);
252 if (rfd != -1)
253 fcntl(rfd, F_SETFD, FD_CLOEXEC);
254 if (wfd != -1 && wfd != rfd)
255 fcntl(wfd, F_SETFD, FD_CLOEXEC);
256 if (efd != -1 && efd != rfd && efd != wfd)
257 fcntl(efd, F_SETFD, FD_CLOEXEC);
259 c->rfd = rfd;
260 c->wfd = wfd;
261 c->sock = (rfd == wfd) ? rfd : -1;
262 c->efd = efd;
263 c->extended_usage = extusage;
265 if ((c->isatty = is_tty) != 0)
266 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
267 #ifdef _AIX
268 /* XXX: Later AIX versions can't push as much data to tty */
269 c->wfd_isatty = is_tty || isatty(c->wfd);
270 #endif
272 /* enable nonblocking mode */
273 if (nonblock) {
274 if (rfd != -1)
275 set_nonblock(rfd);
276 if (wfd != -1)
277 set_nonblock(wfd);
278 if (efd != -1)
279 set_nonblock(efd);
284 * Allocate a new channel object and set its type and socket. This will cause
285 * remote_name to be freed.
287 Channel *
288 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
289 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
291 int found;
292 u_int i;
293 Channel *c;
295 /* Do initial allocation if this is the first call. */
296 if (channels_alloc == 0) {
297 channels_alloc = 10;
298 channels = xcalloc(channels_alloc, sizeof(Channel *));
299 for (i = 0; i < channels_alloc; i++)
300 channels[i] = NULL;
302 /* Try to find a free slot where to put the new channel. */
303 for (found = -1, i = 0; i < channels_alloc; i++)
304 if (channels[i] == NULL) {
305 /* Found a free slot. */
306 found = (int)i;
307 break;
309 if (found < 0) {
310 /* There are no free slots. Take last+1 slot and expand the array. */
311 found = channels_alloc;
312 if (channels_alloc > 10000)
313 fatal("channel_new: internal error: channels_alloc %d "
314 "too big.", channels_alloc);
315 channels = xreallocarray(channels, channels_alloc + 10,
316 sizeof(Channel *));
317 channels_alloc += 10;
318 debug2("channel: expanding %d", channels_alloc);
319 for (i = found; i < channels_alloc; i++)
320 channels[i] = NULL;
322 /* Initialize and return new channel. */
323 c = channels[found] = xcalloc(1, sizeof(Channel));
324 buffer_init(&c->input);
325 buffer_init(&c->output);
326 buffer_init(&c->extended);
327 c->path = NULL;
328 c->listening_addr = NULL;
329 c->listening_port = 0;
330 c->ostate = CHAN_OUTPUT_OPEN;
331 c->istate = CHAN_INPUT_OPEN;
332 c->flags = 0;
333 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
334 c->notbefore = 0;
335 c->self = found;
336 c->type = type;
337 c->ctype = ctype;
338 c->local_window = window;
339 c->local_window_max = window;
340 c->local_consumed = 0;
341 c->local_maxpacket = maxpack;
342 c->remote_id = -1;
343 c->remote_name = xstrdup(remote_name);
344 c->remote_window = 0;
345 c->remote_maxpacket = 0;
346 c->force_drain = 0;
347 c->single_connection = 0;
348 c->detach_user = NULL;
349 c->detach_close = 0;
350 c->open_confirm = NULL;
351 c->open_confirm_ctx = NULL;
352 c->input_filter = NULL;
353 c->output_filter = NULL;
354 c->filter_ctx = NULL;
355 c->filter_cleanup = NULL;
356 c->ctl_chan = -1;
357 c->mux_rcb = NULL;
358 c->mux_ctx = NULL;
359 c->mux_pause = 0;
360 c->delayed = 1; /* prevent call to channel_post handler */
361 TAILQ_INIT(&c->status_confirms);
362 debug("channel %d: new [%s]", found, remote_name);
363 return c;
366 static int
367 channel_find_maxfd(void)
369 u_int i;
370 int max = 0;
371 Channel *c;
373 for (i = 0; i < channels_alloc; i++) {
374 c = channels[i];
375 if (c != NULL) {
376 max = MAX(max, c->rfd);
377 max = MAX(max, c->wfd);
378 max = MAX(max, c->efd);
381 return max;
385 channel_close_fd(int *fdp)
387 int ret = 0, fd = *fdp;
389 if (fd != -1) {
390 ret = close(fd);
391 *fdp = -1;
392 if (fd == channel_max_fd)
393 channel_max_fd = channel_find_maxfd();
395 return ret;
398 /* Close all channel fd/socket. */
399 static void
400 channel_close_fds(Channel *c)
402 channel_close_fd(&c->sock);
403 channel_close_fd(&c->rfd);
404 channel_close_fd(&c->wfd);
405 channel_close_fd(&c->efd);
408 /* Free the channel and close its fd/socket. */
409 void
410 channel_free(Channel *c)
412 char *s;
413 u_int i, n;
414 struct channel_confirm *cc;
416 for (n = 0, i = 0; i < channels_alloc; i++)
417 if (channels[i])
418 n++;
419 debug("channel %d: free: %s, nchannels %u", c->self,
420 c->remote_name ? c->remote_name : "???", n);
422 s = channel_open_message();
423 debug3("channel %d: status: %s", c->self, s);
424 free(s);
426 if (c->sock != -1)
427 shutdown(c->sock, SHUT_RDWR);
428 channel_close_fds(c);
429 buffer_free(&c->input);
430 buffer_free(&c->output);
431 buffer_free(&c->extended);
432 free(c->remote_name);
433 c->remote_name = NULL;
434 free(c->path);
435 c->path = NULL;
436 free(c->listening_addr);
437 c->listening_addr = NULL;
438 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
439 if (cc->abandon_cb != NULL)
440 cc->abandon_cb(c, cc->ctx);
441 TAILQ_REMOVE(&c->status_confirms, cc, entry);
442 explicit_bzero(cc, sizeof(*cc));
443 free(cc);
445 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
446 c->filter_cleanup(c->self, c->filter_ctx);
447 channels[c->self] = NULL;
448 free(c);
451 void
452 channel_free_all(void)
454 u_int i;
456 for (i = 0; i < channels_alloc; i++)
457 if (channels[i] != NULL)
458 channel_free(channels[i]);
462 * Closes the sockets/fds of all channels. This is used to close extra file
463 * descriptors after a fork.
465 void
466 channel_close_all(void)
468 u_int i;
470 for (i = 0; i < channels_alloc; i++)
471 if (channels[i] != NULL)
472 channel_close_fds(channels[i]);
476 * Stop listening to channels.
478 void
479 channel_stop_listening(void)
481 u_int i;
482 Channel *c;
484 for (i = 0; i < channels_alloc; i++) {
485 c = channels[i];
486 if (c != NULL) {
487 switch (c->type) {
488 case SSH_CHANNEL_AUTH_SOCKET:
489 case SSH_CHANNEL_PORT_LISTENER:
490 case SSH_CHANNEL_RPORT_LISTENER:
491 case SSH_CHANNEL_X11_LISTENER:
492 case SSH_CHANNEL_UNIX_LISTENER:
493 case SSH_CHANNEL_RUNIX_LISTENER:
494 channel_close_fd(&c->sock);
495 channel_free(c);
496 break;
503 * Returns true if no channel has too much buffered data, and false if one or
504 * more channel is overfull.
507 channel_not_very_much_buffered_data(void)
509 u_int i;
510 Channel *c;
512 for (i = 0; i < channels_alloc; i++) {
513 c = channels[i];
514 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
515 #if 0
516 if (!compat20 &&
517 buffer_len(&c->input) > packet_get_maxsize()) {
518 debug2("channel %d: big input buffer %d",
519 c->self, buffer_len(&c->input));
520 return 0;
522 #endif
523 if (buffer_len(&c->output) > packet_get_maxsize()) {
524 debug2("channel %d: big output buffer %u > %u",
525 c->self, buffer_len(&c->output),
526 packet_get_maxsize());
527 return 0;
531 return 1;
534 /* Returns true if any channel is still open. */
536 channel_still_open(void)
538 u_int i;
539 Channel *c;
541 for (i = 0; i < channels_alloc; i++) {
542 c = channels[i];
543 if (c == NULL)
544 continue;
545 switch (c->type) {
546 case SSH_CHANNEL_X11_LISTENER:
547 case SSH_CHANNEL_PORT_LISTENER:
548 case SSH_CHANNEL_RPORT_LISTENER:
549 case SSH_CHANNEL_MUX_LISTENER:
550 case SSH_CHANNEL_CLOSED:
551 case SSH_CHANNEL_AUTH_SOCKET:
552 case SSH_CHANNEL_DYNAMIC:
553 case SSH_CHANNEL_CONNECTING:
554 case SSH_CHANNEL_ZOMBIE:
555 case SSH_CHANNEL_ABANDONED:
556 case SSH_CHANNEL_UNIX_LISTENER:
557 case SSH_CHANNEL_RUNIX_LISTENER:
558 continue;
559 case SSH_CHANNEL_LARVAL:
560 if (!compat20)
561 fatal("cannot happen: SSH_CHANNEL_LARVAL");
562 continue;
563 case SSH_CHANNEL_OPENING:
564 case SSH_CHANNEL_OPEN:
565 case SSH_CHANNEL_X11_OPEN:
566 case SSH_CHANNEL_MUX_CLIENT:
567 return 1;
568 case SSH_CHANNEL_INPUT_DRAINING:
569 case SSH_CHANNEL_OUTPUT_DRAINING:
570 if (!compat13)
571 fatal("cannot happen: OUT_DRAIN");
572 return 1;
573 default:
574 fatal("channel_still_open: bad channel type %d", c->type);
575 /* NOTREACHED */
578 return 0;
581 /* Returns the id of an open channel suitable for keepaliving */
583 channel_find_open(void)
585 u_int i;
586 Channel *c;
588 for (i = 0; i < channels_alloc; i++) {
589 c = channels[i];
590 if (c == NULL || c->remote_id < 0)
591 continue;
592 switch (c->type) {
593 case SSH_CHANNEL_CLOSED:
594 case SSH_CHANNEL_DYNAMIC:
595 case SSH_CHANNEL_X11_LISTENER:
596 case SSH_CHANNEL_PORT_LISTENER:
597 case SSH_CHANNEL_RPORT_LISTENER:
598 case SSH_CHANNEL_MUX_LISTENER:
599 case SSH_CHANNEL_MUX_CLIENT:
600 case SSH_CHANNEL_OPENING:
601 case SSH_CHANNEL_CONNECTING:
602 case SSH_CHANNEL_ZOMBIE:
603 case SSH_CHANNEL_ABANDONED:
604 case SSH_CHANNEL_UNIX_LISTENER:
605 case SSH_CHANNEL_RUNIX_LISTENER:
606 continue;
607 case SSH_CHANNEL_LARVAL:
608 case SSH_CHANNEL_AUTH_SOCKET:
609 case SSH_CHANNEL_OPEN:
610 case SSH_CHANNEL_X11_OPEN:
611 return i;
612 case SSH_CHANNEL_INPUT_DRAINING:
613 case SSH_CHANNEL_OUTPUT_DRAINING:
614 if (!compat13)
615 fatal("cannot happen: OUT_DRAIN");
616 return i;
617 default:
618 fatal("channel_find_open: bad channel type %d", c->type);
619 /* NOTREACHED */
622 return -1;
627 * Returns a message describing the currently open forwarded connections,
628 * suitable for sending to the client. The message contains crlf pairs for
629 * newlines.
631 char *
632 channel_open_message(void)
634 Buffer buffer;
635 Channel *c;
636 char buf[1024], *cp;
637 u_int i;
639 buffer_init(&buffer);
640 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
641 buffer_append(&buffer, buf, strlen(buf));
642 for (i = 0; i < channels_alloc; i++) {
643 c = channels[i];
644 if (c == NULL)
645 continue;
646 switch (c->type) {
647 case SSH_CHANNEL_X11_LISTENER:
648 case SSH_CHANNEL_PORT_LISTENER:
649 case SSH_CHANNEL_RPORT_LISTENER:
650 case SSH_CHANNEL_CLOSED:
651 case SSH_CHANNEL_AUTH_SOCKET:
652 case SSH_CHANNEL_ZOMBIE:
653 case SSH_CHANNEL_ABANDONED:
654 case SSH_CHANNEL_MUX_CLIENT:
655 case SSH_CHANNEL_MUX_LISTENER:
656 case SSH_CHANNEL_UNIX_LISTENER:
657 case SSH_CHANNEL_RUNIX_LISTENER:
658 continue;
659 case SSH_CHANNEL_LARVAL:
660 case SSH_CHANNEL_OPENING:
661 case SSH_CHANNEL_CONNECTING:
662 case SSH_CHANNEL_DYNAMIC:
663 case SSH_CHANNEL_OPEN:
664 case SSH_CHANNEL_X11_OPEN:
665 case SSH_CHANNEL_INPUT_DRAINING:
666 case SSH_CHANNEL_OUTPUT_DRAINING:
667 snprintf(buf, sizeof buf,
668 " #%d %.300s (t%d r%d i%u/%d o%u/%d fd %d/%d cc %d)\r\n",
669 c->self, c->remote_name,
670 c->type, c->remote_id,
671 c->istate, buffer_len(&c->input),
672 c->ostate, buffer_len(&c->output),
673 c->rfd, c->wfd, c->ctl_chan);
674 buffer_append(&buffer, buf, strlen(buf));
675 continue;
676 default:
677 fatal("channel_open_message: bad channel type %d", c->type);
678 /* NOTREACHED */
681 buffer_append(&buffer, "\0", 1);
682 cp = xstrdup((char *)buffer_ptr(&buffer));
683 buffer_free(&buffer);
684 return cp;
687 void
688 channel_send_open(int id)
690 Channel *c = channel_lookup(id);
692 if (c == NULL) {
693 logit("channel_send_open: %d: bad id", id);
694 return;
696 debug2("channel %d: send open", id);
697 packet_start(SSH2_MSG_CHANNEL_OPEN);
698 packet_put_cstring(c->ctype);
699 packet_put_int(c->self);
700 packet_put_int(c->local_window);
701 packet_put_int(c->local_maxpacket);
702 packet_send();
705 void
706 channel_request_start(int id, char *service, int wantconfirm)
708 Channel *c = channel_lookup(id);
710 if (c == NULL) {
711 logit("channel_request_start: %d: unknown channel id", id);
712 return;
714 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
715 packet_start(SSH2_MSG_CHANNEL_REQUEST);
716 packet_put_int(c->remote_id);
717 packet_put_cstring(service);
718 packet_put_char(wantconfirm);
721 void
722 channel_register_status_confirm(int id, channel_confirm_cb *cb,
723 channel_confirm_abandon_cb *abandon_cb, void *ctx)
725 struct channel_confirm *cc;
726 Channel *c;
728 if ((c = channel_lookup(id)) == NULL)
729 fatal("channel_register_expect: %d: bad id", id);
731 cc = xcalloc(1, sizeof(*cc));
732 cc->cb = cb;
733 cc->abandon_cb = abandon_cb;
734 cc->ctx = ctx;
735 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
738 void
739 channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
741 Channel *c = channel_lookup(id);
743 if (c == NULL) {
744 logit("channel_register_open_confirm: %d: bad id", id);
745 return;
747 c->open_confirm = fn;
748 c->open_confirm_ctx = ctx;
751 void
752 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
754 Channel *c = channel_by_id(id);
756 if (c == NULL) {
757 logit("channel_register_cleanup: %d: bad id", id);
758 return;
760 c->detach_user = fn;
761 c->detach_close = do_close;
764 void
765 channel_cancel_cleanup(int id)
767 Channel *c = channel_by_id(id);
769 if (c == NULL) {
770 logit("channel_cancel_cleanup: %d: bad id", id);
771 return;
773 c->detach_user = NULL;
774 c->detach_close = 0;
777 void
778 channel_register_filter(int id, channel_infilter_fn *ifn,
779 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
781 Channel *c = channel_lookup(id);
783 if (c == NULL) {
784 logit("channel_register_filter: %d: bad id", id);
785 return;
787 c->input_filter = ifn;
788 c->output_filter = ofn;
789 c->filter_ctx = ctx;
790 c->filter_cleanup = cfn;
793 void
794 channel_set_fds(int id, int rfd, int wfd, int efd,
795 int extusage, int nonblock, int is_tty, u_int window_max)
797 Channel *c = channel_lookup(id);
799 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
800 fatal("channel_activate for non-larval channel %d.", id);
801 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
802 c->type = SSH_CHANNEL_OPEN;
803 c->local_window = c->local_window_max = window_max;
804 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
805 packet_put_int(c->remote_id);
806 packet_put_int(c->local_window);
807 packet_send();
811 * 'channel_pre*' are called just before select() to add any bits relevant to
812 * channels in the select bitmasks.
815 * 'channel_post*': perform any appropriate operations for channels which
816 * have events pending.
818 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
819 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
820 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
822 /* ARGSUSED */
823 static void
824 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
826 FD_SET(c->sock, readset);
829 /* ARGSUSED */
830 static void
831 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
833 debug3("channel %d: waiting for connection", c->self);
834 FD_SET(c->sock, writeset);
837 static void
838 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
840 if (buffer_len(&c->input) < packet_get_maxsize())
841 FD_SET(c->sock, readset);
842 if (buffer_len(&c->output) > 0)
843 FD_SET(c->sock, writeset);
846 static void
847 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
849 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
851 if (c->istate == CHAN_INPUT_OPEN &&
852 limit > 0 &&
853 buffer_len(&c->input) < limit &&
854 buffer_check_alloc(&c->input, CHAN_RBUF))
855 FD_SET(c->rfd, readset);
856 if (c->ostate == CHAN_OUTPUT_OPEN ||
857 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
858 if (buffer_len(&c->output) > 0) {
859 FD_SET(c->wfd, writeset);
860 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
861 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
862 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
863 c->self, c->efd, buffer_len(&c->extended));
864 else
865 chan_obuf_empty(c);
868 /** XXX check close conditions, too */
869 if (compat20 && c->efd != -1 &&
870 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
871 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
872 buffer_len(&c->extended) > 0)
873 FD_SET(c->efd, writeset);
874 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
875 (c->extended_usage == CHAN_EXTENDED_READ ||
876 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
877 buffer_len(&c->extended) < c->remote_window)
878 FD_SET(c->efd, readset);
880 /* XXX: What about efd? races? */
883 /* ARGSUSED */
884 static void
885 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
887 if (buffer_len(&c->input) == 0) {
888 packet_start(SSH_MSG_CHANNEL_CLOSE);
889 packet_put_int(c->remote_id);
890 packet_send();
891 c->type = SSH_CHANNEL_CLOSED;
892 debug2("channel %d: closing after input drain.", c->self);
896 /* ARGSUSED */
897 static void
898 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
900 if (buffer_len(&c->output) == 0)
901 chan_mark_dead(c);
902 else
903 FD_SET(c->sock, writeset);
907 * This is a special state for X11 authentication spoofing. An opened X11
908 * connection (when authentication spoofing is being done) remains in this
909 * state until the first packet has been completely read. The authentication
910 * data in that packet is then substituted by the real data if it matches the
911 * fake data, and the channel is put into normal mode.
912 * XXX All this happens at the client side.
913 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
915 static int
916 x11_open_helper(Buffer *b)
918 u_char *ucp;
919 u_int proto_len, data_len;
921 /* Is this being called after the refusal deadline? */
922 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
923 verbose("Rejected X11 connection after ForwardX11Timeout "
924 "expired");
925 return -1;
928 /* Check if the fixed size part of the packet is in buffer. */
929 if (buffer_len(b) < 12)
930 return 0;
932 /* Parse the lengths of variable-length fields. */
933 ucp = buffer_ptr(b);
934 if (ucp[0] == 0x42) { /* Byte order MSB first. */
935 proto_len = 256 * ucp[6] + ucp[7];
936 data_len = 256 * ucp[8] + ucp[9];
937 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
938 proto_len = ucp[6] + 256 * ucp[7];
939 data_len = ucp[8] + 256 * ucp[9];
940 } else {
941 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
942 ucp[0]);
943 return -1;
946 /* Check if the whole packet is in buffer. */
947 if (buffer_len(b) <
948 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
949 return 0;
951 /* Check if authentication protocol matches. */
952 if (proto_len != strlen(x11_saved_proto) ||
953 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
954 debug2("X11 connection uses different authentication protocol.");
955 return -1;
957 /* Check if authentication data matches our fake data. */
958 if (data_len != x11_fake_data_len ||
959 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
960 x11_fake_data, x11_fake_data_len) != 0) {
961 debug2("X11 auth data does not match fake data.");
962 return -1;
964 /* Check fake data length */
965 if (x11_fake_data_len != x11_saved_data_len) {
966 error("X11 fake_data_len %d != saved_data_len %d",
967 x11_fake_data_len, x11_saved_data_len);
968 return -1;
971 * Received authentication protocol and data match
972 * our fake data. Substitute the fake data with real
973 * data.
975 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
976 x11_saved_data, x11_saved_data_len);
977 return 1;
980 static void
981 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
983 int ret = x11_open_helper(&c->output);
985 if (ret == 1) {
986 /* Start normal processing for the channel. */
987 c->type = SSH_CHANNEL_OPEN;
988 channel_pre_open_13(c, readset, writeset);
989 } else if (ret == -1) {
991 * We have received an X11 connection that has bad
992 * authentication information.
994 logit("X11 connection rejected because of wrong authentication.");
995 buffer_clear(&c->input);
996 buffer_clear(&c->output);
997 channel_close_fd(&c->sock);
998 c->sock = -1;
999 c->type = SSH_CHANNEL_CLOSED;
1000 packet_start(SSH_MSG_CHANNEL_CLOSE);
1001 packet_put_int(c->remote_id);
1002 packet_send();
1006 static void
1007 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1009 int ret = x11_open_helper(&c->output);
1011 /* c->force_drain = 1; */
1013 if (ret == 1) {
1014 c->type = SSH_CHANNEL_OPEN;
1015 channel_pre_open(c, readset, writeset);
1016 } else if (ret == -1) {
1017 logit("X11 connection rejected because of wrong authentication.");
1018 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1019 chan_read_failed(c);
1020 buffer_clear(&c->input);
1021 chan_ibuf_empty(c);
1022 buffer_clear(&c->output);
1023 /* for proto v1, the peer will send an IEOF */
1024 if (compat20)
1025 chan_write_failed(c);
1026 else
1027 c->type = SSH_CHANNEL_OPEN;
1028 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1032 static void
1033 channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1035 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1036 buffer_check_alloc(&c->input, CHAN_RBUF))
1037 FD_SET(c->rfd, readset);
1038 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1039 /* clear buffer immediately (discard any partial packet) */
1040 buffer_clear(&c->input);
1041 chan_ibuf_empty(c);
1042 /* Start output drain. XXX just kill chan? */
1043 chan_rcvd_oclose(c);
1045 if (c->ostate == CHAN_OUTPUT_OPEN ||
1046 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1047 if (buffer_len(&c->output) > 0)
1048 FD_SET(c->wfd, writeset);
1049 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1050 chan_obuf_empty(c);
1054 /* try to decode a socks4 header */
1055 /* ARGSUSED */
1056 static int
1057 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1059 char *p, *host;
1060 u_int len, have, i, found, need;
1061 char username[256];
1062 struct {
1063 u_int8_t version;
1064 u_int8_t command;
1065 u_int16_t dest_port;
1066 struct in_addr dest_addr;
1067 } s4_req, s4_rsp;
1069 debug2("channel %d: decode socks4", c->self);
1071 have = buffer_len(&c->input);
1072 len = sizeof(s4_req);
1073 if (have < len)
1074 return 0;
1075 p = (char *)buffer_ptr(&c->input);
1077 need = 1;
1078 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1079 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1080 debug2("channel %d: socks4a request", c->self);
1081 /* ... and needs an extra string (the hostname) */
1082 need = 2;
1084 /* Check for terminating NUL on the string(s) */
1085 for (found = 0, i = len; i < have; i++) {
1086 if (p[i] == '\0') {
1087 found++;
1088 if (found == need)
1089 break;
1091 if (i > 1024) {
1092 /* the peer is probably sending garbage */
1093 debug("channel %d: decode socks4: too long",
1094 c->self);
1095 return -1;
1098 if (found < need)
1099 return 0;
1100 buffer_get(&c->input, (char *)&s4_req.version, 1);
1101 buffer_get(&c->input, (char *)&s4_req.command, 1);
1102 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1103 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1104 have = buffer_len(&c->input);
1105 p = (char *)buffer_ptr(&c->input);
1106 if (memchr(p, '\0', have) == NULL)
1107 fatal("channel %d: decode socks4: user not nul terminated",
1108 c->self);
1109 len = strlen(p);
1110 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1111 len++; /* trailing '\0' */
1112 if (len > have)
1113 fatal("channel %d: decode socks4: len %d > have %d",
1114 c->self, len, have);
1115 strlcpy(username, p, sizeof(username));
1116 buffer_consume(&c->input, len);
1118 free(c->path);
1119 c->path = NULL;
1120 if (need == 1) { /* SOCKS4: one string */
1121 host = inet_ntoa(s4_req.dest_addr);
1122 c->path = xstrdup(host);
1123 } else { /* SOCKS4A: two strings */
1124 have = buffer_len(&c->input);
1125 p = (char *)buffer_ptr(&c->input);
1126 len = strlen(p);
1127 debug2("channel %d: decode socks4a: host %s/%d",
1128 c->self, p, len);
1129 len++; /* trailing '\0' */
1130 if (len > have)
1131 fatal("channel %d: decode socks4a: len %d > have %d",
1132 c->self, len, have);
1133 if (len > NI_MAXHOST) {
1134 error("channel %d: hostname \"%.100s\" too long",
1135 c->self, p);
1136 return -1;
1138 c->path = xstrdup(p);
1139 buffer_consume(&c->input, len);
1141 c->host_port = ntohs(s4_req.dest_port);
1143 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1144 c->self, c->path, c->host_port, s4_req.command);
1146 if (s4_req.command != 1) {
1147 debug("channel %d: cannot handle: %s cn %d",
1148 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1149 return -1;
1151 s4_rsp.version = 0; /* vn: 0 for reply */
1152 s4_rsp.command = 90; /* cd: req granted */
1153 s4_rsp.dest_port = 0; /* ignored */
1154 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1155 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1156 return 1;
1159 /* try to decode a socks5 header */
1160 #define SSH_SOCKS5_AUTHDONE 0x1000
1161 #define SSH_SOCKS5_NOAUTH 0x00
1162 #define SSH_SOCKS5_IPV4 0x01
1163 #define SSH_SOCKS5_DOMAIN 0x03
1164 #define SSH_SOCKS5_IPV6 0x04
1165 #define SSH_SOCKS5_CONNECT 0x01
1166 #define SSH_SOCKS5_SUCCESS 0x00
1168 /* ARGSUSED */
1169 static int
1170 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1172 struct {
1173 u_int8_t version;
1174 u_int8_t command;
1175 u_int8_t reserved;
1176 u_int8_t atyp;
1177 } s5_req, s5_rsp;
1178 u_int16_t dest_port;
1179 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1180 u_char *p;
1181 u_int have, need, i, found, nmethods, addrlen, af;
1183 debug2("channel %d: decode socks5", c->self);
1184 p = buffer_ptr(&c->input);
1185 if (p[0] != 0x05)
1186 return -1;
1187 have = buffer_len(&c->input);
1188 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1189 /* format: ver | nmethods | methods */
1190 if (have < 2)
1191 return 0;
1192 nmethods = p[1];
1193 if (have < nmethods + 2)
1194 return 0;
1195 /* look for method: "NO AUTHENTICATION REQUIRED" */
1196 for (found = 0, i = 2; i < nmethods + 2; i++) {
1197 if (p[i] == SSH_SOCKS5_NOAUTH) {
1198 found = 1;
1199 break;
1202 if (!found) {
1203 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1204 c->self);
1205 return -1;
1207 buffer_consume(&c->input, nmethods + 2);
1208 buffer_put_char(&c->output, 0x05); /* version */
1209 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1210 FD_SET(c->sock, writeset);
1211 c->flags |= SSH_SOCKS5_AUTHDONE;
1212 debug2("channel %d: socks5 auth done", c->self);
1213 return 0; /* need more */
1215 debug2("channel %d: socks5 post auth", c->self);
1216 if (have < sizeof(s5_req)+1)
1217 return 0; /* need more */
1218 memcpy(&s5_req, p, sizeof(s5_req));
1219 if (s5_req.version != 0x05 ||
1220 s5_req.command != SSH_SOCKS5_CONNECT ||
1221 s5_req.reserved != 0x00) {
1222 debug2("channel %d: only socks5 connect supported", c->self);
1223 return -1;
1225 switch (s5_req.atyp){
1226 case SSH_SOCKS5_IPV4:
1227 addrlen = 4;
1228 af = AF_INET;
1229 break;
1230 case SSH_SOCKS5_DOMAIN:
1231 addrlen = p[sizeof(s5_req)];
1232 af = -1;
1233 break;
1234 case SSH_SOCKS5_IPV6:
1235 addrlen = 16;
1236 af = AF_INET6;
1237 break;
1238 default:
1239 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1240 return -1;
1242 need = sizeof(s5_req) + addrlen + 2;
1243 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1244 need++;
1245 if (have < need)
1246 return 0;
1247 buffer_consume(&c->input, sizeof(s5_req));
1248 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1249 buffer_consume(&c->input, 1); /* host string length */
1250 buffer_get(&c->input, &dest_addr, addrlen);
1251 buffer_get(&c->input, (char *)&dest_port, 2);
1252 dest_addr[addrlen] = '\0';
1253 free(c->path);
1254 c->path = NULL;
1255 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1256 if (addrlen >= NI_MAXHOST) {
1257 error("channel %d: dynamic request: socks5 hostname "
1258 "\"%.100s\" too long", c->self, dest_addr);
1259 return -1;
1261 c->path = xstrdup(dest_addr);
1262 } else {
1263 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1264 return -1;
1265 c->path = xstrdup(ntop);
1267 c->host_port = ntohs(dest_port);
1269 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1270 c->self, c->path, c->host_port, s5_req.command);
1272 s5_rsp.version = 0x05;
1273 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1274 s5_rsp.reserved = 0; /* ignored */
1275 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1276 dest_port = 0; /* ignored */
1278 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1279 buffer_put_int(&c->output, ntohl(INADDR_ANY)); /* bind address */
1280 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1281 return 1;
1284 Channel *
1285 channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
1286 int in, int out)
1288 Channel *c;
1290 debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
1291 port_to_connect);
1293 c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
1294 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1295 0, "stdio-forward", /*nonblock*/0);
1297 c->path = xstrdup(host_to_connect);
1298 c->host_port = port_to_connect;
1299 c->listening_port = 0;
1300 c->force_drain = 1;
1302 channel_register_fds(c, in, out, -1, 0, 1, 0);
1303 port_open_helper(c, "direct-tcpip");
1305 return c;
1308 /* dynamic port forwarding */
1309 static void
1310 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1312 u_char *p;
1313 u_int have;
1314 int ret;
1316 have = buffer_len(&c->input);
1317 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1318 /* buffer_dump(&c->input); */
1319 /* check if the fixed size part of the packet is in buffer. */
1320 if (have < 3) {
1321 /* need more */
1322 FD_SET(c->sock, readset);
1323 return;
1325 /* try to guess the protocol */
1326 p = buffer_ptr(&c->input);
1327 switch (p[0]) {
1328 case 0x04:
1329 ret = channel_decode_socks4(c, readset, writeset);
1330 break;
1331 case 0x05:
1332 ret = channel_decode_socks5(c, readset, writeset);
1333 break;
1334 default:
1335 ret = -1;
1336 break;
1338 if (ret < 0) {
1339 chan_mark_dead(c);
1340 } else if (ret == 0) {
1341 debug2("channel %d: pre_dynamic: need more", c->self);
1342 /* need more */
1343 FD_SET(c->sock, readset);
1344 } else {
1345 /* switch to the next state */
1346 c->type = SSH_CHANNEL_OPENING;
1347 port_open_helper(c, "direct-tcpip");
1351 /* This is our fake X11 server socket. */
1352 /* ARGSUSED */
1353 static void
1354 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1356 Channel *nc;
1357 struct sockaddr_storage addr;
1358 int newsock, oerrno;
1359 socklen_t addrlen;
1360 char buf[16384], *remote_ipaddr;
1361 int remote_port;
1363 if (FD_ISSET(c->sock, readset)) {
1364 debug("X11 connection requested.");
1365 addrlen = sizeof(addr);
1366 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1367 if (c->single_connection) {
1368 oerrno = errno;
1369 debug2("single_connection: closing X11 listener.");
1370 channel_close_fd(&c->sock);
1371 chan_mark_dead(c);
1372 errno = oerrno;
1374 if (newsock < 0) {
1375 if (errno != EINTR && errno != EWOULDBLOCK &&
1376 errno != ECONNABORTED)
1377 error("accept: %.100s", strerror(errno));
1378 if (errno == EMFILE || errno == ENFILE)
1379 c->notbefore = monotime() + 1;
1380 return;
1382 set_nodelay(newsock);
1383 remote_ipaddr = get_peer_ipaddr(newsock);
1384 remote_port = get_peer_port(newsock);
1385 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1386 remote_ipaddr, remote_port);
1388 nc = channel_new("accepted x11 socket",
1389 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1390 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1391 if (compat20) {
1392 packet_start(SSH2_MSG_CHANNEL_OPEN);
1393 packet_put_cstring("x11");
1394 packet_put_int(nc->self);
1395 packet_put_int(nc->local_window_max);
1396 packet_put_int(nc->local_maxpacket);
1397 /* originator ipaddr and port */
1398 packet_put_cstring(remote_ipaddr);
1399 if (datafellows & SSH_BUG_X11FWD) {
1400 debug2("ssh2 x11 bug compat mode");
1401 } else {
1402 packet_put_int(remote_port);
1404 packet_send();
1405 } else {
1406 packet_start(SSH_SMSG_X11_OPEN);
1407 packet_put_int(nc->self);
1408 if (packet_get_protocol_flags() &
1409 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1410 packet_put_cstring(buf);
1411 packet_send();
1413 free(remote_ipaddr);
1417 static void
1418 port_open_helper(Channel *c, char *rtype)
1420 char buf[1024];
1421 char *local_ipaddr = get_local_ipaddr(c->sock);
1422 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1423 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1424 int remote_port = get_peer_port(c->sock);
1426 if (remote_port == -1) {
1427 /* Fake addr/port to appease peers that validate it (Tectia) */
1428 free(remote_ipaddr);
1429 remote_ipaddr = xstrdup("127.0.0.1");
1430 remote_port = 65535;
1433 snprintf(buf, sizeof buf,
1434 "%s: listening port %d for %.100s port %d, "
1435 "connect from %.200s port %d to %.100s port %d",
1436 rtype, c->listening_port, c->path, c->host_port,
1437 remote_ipaddr, remote_port, local_ipaddr, local_port);
1439 free(c->remote_name);
1440 c->remote_name = xstrdup(buf);
1442 if (compat20) {
1443 packet_start(SSH2_MSG_CHANNEL_OPEN);
1444 packet_put_cstring(rtype);
1445 packet_put_int(c->self);
1446 packet_put_int(c->local_window_max);
1447 packet_put_int(c->local_maxpacket);
1448 if (strcmp(rtype, "direct-tcpip") == 0) {
1449 /* target host, port */
1450 packet_put_cstring(c->path);
1451 packet_put_int(c->host_port);
1452 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1453 /* target path */
1454 packet_put_cstring(c->path);
1455 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1456 /* listen path */
1457 packet_put_cstring(c->path);
1458 } else {
1459 /* listen address, port */
1460 packet_put_cstring(c->path);
1461 packet_put_int(local_port);
1463 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1464 /* reserved for future owner/mode info */
1465 packet_put_cstring("");
1466 } else {
1467 /* originator host and port */
1468 packet_put_cstring(remote_ipaddr);
1469 packet_put_int((u_int)remote_port);
1471 packet_send();
1472 } else {
1473 packet_start(SSH_MSG_PORT_OPEN);
1474 packet_put_int(c->self);
1475 packet_put_cstring(c->path);
1476 packet_put_int(c->host_port);
1477 if (packet_get_protocol_flags() &
1478 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1479 packet_put_cstring(c->remote_name);
1480 packet_send();
1482 free(remote_ipaddr);
1483 free(local_ipaddr);
1486 static void
1487 channel_set_reuseaddr(int fd)
1489 int on = 1;
1492 * Set socket options.
1493 * Allow local port reuse in TIME_WAIT.
1495 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1496 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1499 void
1500 channel_set_x11_refuse_time(u_int refuse_time)
1502 x11_refuse_time = refuse_time;
1506 * This socket is listening for connections to a forwarded TCP/IP port.
1508 /* ARGSUSED */
1509 static void
1510 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1512 Channel *nc;
1513 struct sockaddr_storage addr;
1514 int newsock, nextstate;
1515 socklen_t addrlen;
1516 char *rtype;
1518 if (FD_ISSET(c->sock, readset)) {
1519 debug("Connection to port %d forwarding "
1520 "to %.100s port %d requested.",
1521 c->listening_port, c->path, c->host_port);
1523 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1524 nextstate = SSH_CHANNEL_OPENING;
1525 rtype = "forwarded-tcpip";
1526 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1527 nextstate = SSH_CHANNEL_OPENING;
1528 rtype = "forwarded-streamlocal@openssh.com";
1529 } else if (c->host_port == PORT_STREAMLOCAL) {
1530 nextstate = SSH_CHANNEL_OPENING;
1531 rtype = "direct-streamlocal@openssh.com";
1532 } else if (c->host_port == 0) {
1533 nextstate = SSH_CHANNEL_DYNAMIC;
1534 rtype = "dynamic-tcpip";
1535 } else {
1536 nextstate = SSH_CHANNEL_OPENING;
1537 rtype = "direct-tcpip";
1540 addrlen = sizeof(addr);
1541 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1542 if (newsock < 0) {
1543 if (errno != EINTR && errno != EWOULDBLOCK &&
1544 errno != ECONNABORTED)
1545 error("accept: %.100s", strerror(errno));
1546 if (errno == EMFILE || errno == ENFILE)
1547 c->notbefore = monotime() + 1;
1548 return;
1550 if (c->host_port != PORT_STREAMLOCAL)
1551 set_nodelay(newsock);
1552 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1553 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1554 nc->listening_port = c->listening_port;
1555 nc->host_port = c->host_port;
1556 if (c->path != NULL)
1557 nc->path = xstrdup(c->path);
1559 if (nextstate != SSH_CHANNEL_DYNAMIC)
1560 port_open_helper(nc, rtype);
1565 * This is the authentication agent socket listening for connections from
1566 * clients.
1568 /* ARGSUSED */
1569 static void
1570 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1572 Channel *nc;
1573 int newsock;
1574 struct sockaddr_storage addr;
1575 socklen_t addrlen;
1577 if (FD_ISSET(c->sock, readset)) {
1578 addrlen = sizeof(addr);
1579 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1580 if (newsock < 0) {
1581 error("accept from auth socket: %.100s",
1582 strerror(errno));
1583 if (errno == EMFILE || errno == ENFILE)
1584 c->notbefore = monotime() + 1;
1585 return;
1587 nc = channel_new("accepted auth socket",
1588 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1589 c->local_window_max, c->local_maxpacket,
1590 0, "accepted auth socket", 1);
1591 if (compat20) {
1592 packet_start(SSH2_MSG_CHANNEL_OPEN);
1593 packet_put_cstring("auth-agent@openssh.com");
1594 packet_put_int(nc->self);
1595 packet_put_int(c->local_window_max);
1596 packet_put_int(c->local_maxpacket);
1597 } else {
1598 packet_start(SSH_SMSG_AGENT_OPEN);
1599 packet_put_int(nc->self);
1601 packet_send();
1605 /* ARGSUSED */
1606 static void
1607 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1609 int err = 0, sock;
1610 socklen_t sz = sizeof(err);
1612 if (FD_ISSET(c->sock, writeset)) {
1613 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1614 err = errno;
1615 error("getsockopt SO_ERROR failed");
1617 if (err == 0) {
1618 debug("channel %d: connected to %s port %d",
1619 c->self, c->connect_ctx.host, c->connect_ctx.port);
1620 channel_connect_ctx_free(&c->connect_ctx);
1621 c->type = SSH_CHANNEL_OPEN;
1622 if (compat20) {
1623 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1624 packet_put_int(c->remote_id);
1625 packet_put_int(c->self);
1626 packet_put_int(c->local_window);
1627 packet_put_int(c->local_maxpacket);
1628 } else {
1629 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1630 packet_put_int(c->remote_id);
1631 packet_put_int(c->self);
1633 } else {
1634 debug("channel %d: connection failed: %s",
1635 c->self, strerror(err));
1636 /* Try next address, if any */
1637 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1638 close(c->sock);
1639 c->sock = c->rfd = c->wfd = sock;
1640 channel_max_fd = channel_find_maxfd();
1641 return;
1643 /* Exhausted all addresses */
1644 error("connect_to %.100s port %d: failed.",
1645 c->connect_ctx.host, c->connect_ctx.port);
1646 channel_connect_ctx_free(&c->connect_ctx);
1647 if (compat20) {
1648 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1649 packet_put_int(c->remote_id);
1650 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1651 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1652 packet_put_cstring(strerror(err));
1653 packet_put_cstring("");
1655 } else {
1656 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1657 packet_put_int(c->remote_id);
1659 chan_mark_dead(c);
1661 packet_send();
1665 /* ARGSUSED */
1666 static int
1667 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1669 char buf[CHAN_RBUF];
1670 int len, force;
1672 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1673 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1674 errno = 0;
1675 len = read(c->rfd, buf, sizeof(buf));
1676 if (len < 0 && (errno == EINTR ||
1677 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1678 return 1;
1679 #ifndef PTY_ZEROREAD
1680 if (len <= 0) {
1681 #else
1682 if ((!c->isatty && len <= 0) ||
1683 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1684 #endif
1685 debug2("channel %d: read<=0 rfd %d len %d",
1686 c->self, c->rfd, len);
1687 if (c->type != SSH_CHANNEL_OPEN) {
1688 debug2("channel %d: not open", c->self);
1689 chan_mark_dead(c);
1690 return -1;
1691 } else if (compat13) {
1692 buffer_clear(&c->output);
1693 c->type = SSH_CHANNEL_INPUT_DRAINING;
1694 debug2("channel %d: input draining.", c->self);
1695 } else {
1696 chan_read_failed(c);
1698 return -1;
1700 if (c->input_filter != NULL) {
1701 if (c->input_filter(c, buf, len) == -1) {
1702 debug2("channel %d: filter stops", c->self);
1703 chan_read_failed(c);
1705 } else if (c->datagram) {
1706 buffer_put_string(&c->input, buf, len);
1707 } else {
1708 buffer_append(&c->input, buf, len);
1711 return 1;
1714 /* ARGSUSED */
1715 static int
1716 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1718 struct termios tio;
1719 u_char *data = NULL, *buf;
1720 u_int dlen, olen = 0;
1721 int len;
1723 /* Send buffered output data to the socket. */
1724 if (c->wfd != -1 &&
1725 FD_ISSET(c->wfd, writeset) &&
1726 buffer_len(&c->output) > 0) {
1727 olen = buffer_len(&c->output);
1728 if (c->output_filter != NULL) {
1729 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1730 debug2("channel %d: filter stops", c->self);
1731 if (c->type != SSH_CHANNEL_OPEN)
1732 chan_mark_dead(c);
1733 else
1734 chan_write_failed(c);
1735 return -1;
1737 } else if (c->datagram) {
1738 buf = data = buffer_get_string(&c->output, &dlen);
1739 } else {
1740 buf = data = buffer_ptr(&c->output);
1741 dlen = buffer_len(&c->output);
1744 if (c->datagram) {
1745 /* ignore truncated writes, datagrams might get lost */
1746 len = write(c->wfd, buf, dlen);
1747 free(data);
1748 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1749 errno == EWOULDBLOCK))
1750 return 1;
1751 if (len <= 0) {
1752 if (c->type != SSH_CHANNEL_OPEN)
1753 chan_mark_dead(c);
1754 else
1755 chan_write_failed(c);
1756 return -1;
1758 goto out;
1760 #ifdef _AIX
1761 /* XXX: Later AIX versions can't push as much data to tty */
1762 if (compat20 && c->wfd_isatty)
1763 dlen = MIN(dlen, 8*1024);
1764 #endif
1766 len = write(c->wfd, buf, dlen);
1767 if (len < 0 &&
1768 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1769 return 1;
1770 if (len <= 0) {
1771 if (c->type != SSH_CHANNEL_OPEN) {
1772 debug2("channel %d: not open", c->self);
1773 chan_mark_dead(c);
1774 return -1;
1775 } else if (compat13) {
1776 buffer_clear(&c->output);
1777 debug2("channel %d: input draining.", c->self);
1778 c->type = SSH_CHANNEL_INPUT_DRAINING;
1779 } else {
1780 chan_write_failed(c);
1782 return -1;
1784 #ifndef BROKEN_TCGETATTR_ICANON
1785 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1786 if (tcgetattr(c->wfd, &tio) == 0 &&
1787 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1789 * Simulate echo to reduce the impact of
1790 * traffic analysis. We need to match the
1791 * size of a SSH2_MSG_CHANNEL_DATA message
1792 * (4 byte channel id + buf)
1794 packet_send_ignore(4 + len);
1795 packet_send();
1798 #endif
1799 buffer_consume(&c->output, len);
1801 out:
1802 if (compat20 && olen > 0)
1803 c->local_consumed += olen - buffer_len(&c->output);
1804 return 1;
1807 static int
1808 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1810 char buf[CHAN_RBUF];
1811 int len;
1813 /** XXX handle drain efd, too */
1814 if (c->efd != -1) {
1815 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1816 FD_ISSET(c->efd, writeset) &&
1817 buffer_len(&c->extended) > 0) {
1818 len = write(c->efd, buffer_ptr(&c->extended),
1819 buffer_len(&c->extended));
1820 debug2("channel %d: written %d to efd %d",
1821 c->self, len, c->efd);
1822 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1823 errno == EWOULDBLOCK))
1824 return 1;
1825 if (len <= 0) {
1826 debug2("channel %d: closing write-efd %d",
1827 c->self, c->efd);
1828 channel_close_fd(&c->efd);
1829 } else {
1830 buffer_consume(&c->extended, len);
1831 c->local_consumed += len;
1833 } else if (c->efd != -1 &&
1834 (c->extended_usage == CHAN_EXTENDED_READ ||
1835 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1836 (c->detach_close || FD_ISSET(c->efd, readset))) {
1837 len = read(c->efd, buf, sizeof(buf));
1838 debug2("channel %d: read %d from efd %d",
1839 c->self, len, c->efd);
1840 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1841 errno == EWOULDBLOCK) && !c->detach_close)))
1842 return 1;
1843 if (len <= 0) {
1844 debug2("channel %d: closing read-efd %d",
1845 c->self, c->efd);
1846 channel_close_fd(&c->efd);
1847 } else {
1848 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
1849 debug3("channel %d: discard efd",
1850 c->self);
1851 } else
1852 buffer_append(&c->extended, buf, len);
1856 return 1;
1859 static int
1860 channel_check_window(Channel *c)
1862 if (c->type == SSH_CHANNEL_OPEN &&
1863 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1864 ((c->local_window_max - c->local_window >
1865 c->local_maxpacket*3) ||
1866 c->local_window < c->local_window_max/2) &&
1867 c->local_consumed > 0) {
1868 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1869 packet_put_int(c->remote_id);
1870 packet_put_int(c->local_consumed);
1871 packet_send();
1872 debug2("channel %d: window %d sent adjust %d",
1873 c->self, c->local_window,
1874 c->local_consumed);
1875 c->local_window += c->local_consumed;
1876 c->local_consumed = 0;
1878 return 1;
1881 static void
1882 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1884 channel_handle_rfd(c, readset, writeset);
1885 channel_handle_wfd(c, readset, writeset);
1886 if (!compat20)
1887 return;
1888 channel_handle_efd(c, readset, writeset);
1889 channel_check_window(c);
1892 static u_int
1893 read_mux(Channel *c, u_int need)
1895 char buf[CHAN_RBUF];
1896 int len;
1897 u_int rlen;
1899 if (buffer_len(&c->input) < need) {
1900 rlen = need - buffer_len(&c->input);
1901 len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
1902 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1903 return buffer_len(&c->input);
1904 if (len <= 0) {
1905 debug2("channel %d: ctl read<=0 rfd %d len %d",
1906 c->self, c->rfd, len);
1907 chan_read_failed(c);
1908 return 0;
1909 } else
1910 buffer_append(&c->input, buf, len);
1912 return buffer_len(&c->input);
1915 static void
1916 channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1918 u_int need;
1919 ssize_t len;
1921 if (!compat20)
1922 fatal("%s: entered with !compat20", __func__);
1924 if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1925 (c->istate == CHAN_INPUT_OPEN ||
1926 c->istate == CHAN_INPUT_WAIT_DRAIN)) {
1928 * Don't not read past the precise end of packets to
1929 * avoid disrupting fd passing.
1931 if (read_mux(c, 4) < 4) /* read header */
1932 return;
1933 need = get_u32(buffer_ptr(&c->input));
1934 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1935 if (need > CHANNEL_MUX_MAX_PACKET) {
1936 debug2("channel %d: packet too big %u > %u",
1937 c->self, CHANNEL_MUX_MAX_PACKET, need);
1938 chan_rcvd_oclose(c);
1939 return;
1941 if (read_mux(c, need + 4) < need + 4) /* read body */
1942 return;
1943 if (c->mux_rcb(c) != 0) {
1944 debug("channel %d: mux_rcb failed", c->self);
1945 chan_mark_dead(c);
1946 return;
1950 if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
1951 buffer_len(&c->output) > 0) {
1952 len = write(c->wfd, buffer_ptr(&c->output),
1953 buffer_len(&c->output));
1954 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1955 return;
1956 if (len <= 0) {
1957 chan_mark_dead(c);
1958 return;
1960 buffer_consume(&c->output, len);
1964 static void
1965 channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
1967 Channel *nc;
1968 struct sockaddr_storage addr;
1969 socklen_t addrlen;
1970 int newsock;
1971 uid_t euid;
1972 gid_t egid;
1974 if (!FD_ISSET(c->sock, readset))
1975 return;
1977 debug("multiplexing control connection");
1980 * Accept connection on control socket
1982 memset(&addr, 0, sizeof(addr));
1983 addrlen = sizeof(addr);
1984 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
1985 &addrlen)) == -1) {
1986 error("%s accept: %s", __func__, strerror(errno));
1987 if (errno == EMFILE || errno == ENFILE)
1988 c->notbefore = monotime() + 1;
1989 return;
1992 if (getpeereid(newsock, &euid, &egid) < 0) {
1993 error("%s getpeereid failed: %s", __func__,
1994 strerror(errno));
1995 close(newsock);
1996 return;
1998 if ((euid != 0) && (getuid() != euid)) {
1999 error("multiplex uid mismatch: peer euid %u != uid %u",
2000 (u_int)euid, (u_int)getuid());
2001 close(newsock);
2002 return;
2004 nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
2005 newsock, newsock, -1, c->local_window_max,
2006 c->local_maxpacket, 0, "mux-control", 1);
2007 nc->mux_rcb = c->mux_rcb;
2008 debug3("%s: new mux channel %d fd %d", __func__,
2009 nc->self, nc->sock);
2010 /* establish state */
2011 nc->mux_rcb(nc);
2012 /* mux state transitions must not elicit protocol messages */
2013 nc->flags |= CHAN_LOCAL;
2016 /* ARGSUSED */
2017 static void
2018 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
2020 int len;
2022 /* Send buffered output data to the socket. */
2023 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
2024 len = write(c->sock, buffer_ptr(&c->output),
2025 buffer_len(&c->output));
2026 if (len <= 0)
2027 buffer_clear(&c->output);
2028 else
2029 buffer_consume(&c->output, len);
2033 static void
2034 channel_handler_init_20(void)
2036 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2037 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2038 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2039 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2040 channel_pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2041 channel_pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2042 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2043 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2044 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2045 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2046 channel_pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2047 channel_pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2049 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2050 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2051 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2052 channel_post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2053 channel_post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2054 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2055 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2056 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2057 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2058 channel_post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2059 channel_post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2062 static void
2063 channel_handler_init_13(void)
2065 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
2066 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
2067 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2068 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2069 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2070 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
2071 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
2072 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2073 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2075 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2076 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2077 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2078 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2079 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
2080 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2081 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2084 static void
2085 channel_handler_init_15(void)
2087 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2088 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2089 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2090 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2091 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2092 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2093 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2095 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2096 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2097 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2098 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2099 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2100 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2103 static void
2104 channel_handler_init(void)
2106 int i;
2108 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
2109 channel_pre[i] = NULL;
2110 channel_post[i] = NULL;
2112 if (compat20)
2113 channel_handler_init_20();
2114 else if (compat13)
2115 channel_handler_init_13();
2116 else
2117 channel_handler_init_15();
2120 /* gc dead channels */
2121 static void
2122 channel_garbage_collect(Channel *c)
2124 if (c == NULL)
2125 return;
2126 if (c->detach_user != NULL) {
2127 if (!chan_is_dead(c, c->detach_close))
2128 return;
2129 debug2("channel %d: gc: notify user", c->self);
2130 c->detach_user(c->self, NULL);
2131 /* if we still have a callback */
2132 if (c->detach_user != NULL)
2133 return;
2134 debug2("channel %d: gc: user detached", c->self);
2136 if (!chan_is_dead(c, 1))
2137 return;
2138 debug2("channel %d: garbage collecting", c->self);
2139 channel_free(c);
2142 static void
2143 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
2144 time_t *unpause_secs)
2146 static int did_init = 0;
2147 u_int i, oalloc;
2148 Channel *c;
2149 time_t now;
2151 if (!did_init) {
2152 channel_handler_init();
2153 did_init = 1;
2155 now = monotime();
2156 if (unpause_secs != NULL)
2157 *unpause_secs = 0;
2158 for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
2159 c = channels[i];
2160 if (c == NULL)
2161 continue;
2162 if (c->delayed) {
2163 if (ftab == channel_pre)
2164 c->delayed = 0;
2165 else
2166 continue;
2168 if (ftab[c->type] != NULL) {
2170 * Run handlers that are not paused.
2172 if (c->notbefore <= now)
2173 (*ftab[c->type])(c, readset, writeset);
2174 else if (unpause_secs != NULL) {
2176 * Collect the time that the earliest
2177 * channel comes off pause.
2179 debug3("%s: chan %d: skip for %d more seconds",
2180 __func__, c->self,
2181 (int)(c->notbefore - now));
2182 if (*unpause_secs == 0 ||
2183 (c->notbefore - now) < *unpause_secs)
2184 *unpause_secs = c->notbefore - now;
2187 channel_garbage_collect(c);
2189 if (unpause_secs != NULL && *unpause_secs != 0)
2190 debug3("%s: first channel unpauses in %d seconds",
2191 __func__, (int)*unpause_secs);
2195 * Allocate/update select bitmasks and add any bits relevant to channels in
2196 * select bitmasks.
2198 void
2199 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
2200 u_int *nallocp, time_t *minwait_secs, int rekeying)
2202 u_int n, sz, nfdset;
2204 n = MAX(*maxfdp, channel_max_fd);
2206 nfdset = howmany(n+1, NFDBITS);
2207 /* Explicitly test here, because xrealloc isn't always called */
2208 if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2209 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2210 sz = nfdset * sizeof(fd_mask);
2212 /* perhaps check sz < nalloc/2 and shrink? */
2213 if (*readsetp == NULL || sz > *nallocp) {
2214 *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2215 *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2216 *nallocp = sz;
2218 *maxfdp = n;
2219 memset(*readsetp, 0, sz);
2220 memset(*writesetp, 0, sz);
2222 if (!rekeying)
2223 channel_handler(channel_pre, *readsetp, *writesetp,
2224 minwait_secs);
2228 * After select, perform any appropriate operations for channels which have
2229 * events pending.
2231 void
2232 channel_after_select(fd_set *readset, fd_set *writeset)
2234 channel_handler(channel_post, readset, writeset, NULL);
2238 /* If there is data to send to the connection, enqueue some of it now. */
2239 void
2240 channel_output_poll(void)
2242 Channel *c;
2243 u_int i, len;
2245 for (i = 0; i < channels_alloc; i++) {
2246 c = channels[i];
2247 if (c == NULL)
2248 continue;
2251 * We are only interested in channels that can have buffered
2252 * incoming data.
2254 if (compat13) {
2255 if (c->type != SSH_CHANNEL_OPEN &&
2256 c->type != SSH_CHANNEL_INPUT_DRAINING)
2257 continue;
2258 } else {
2259 if (c->type != SSH_CHANNEL_OPEN)
2260 continue;
2262 if (compat20 &&
2263 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2264 /* XXX is this true? */
2265 debug3("channel %d: will not send data after close", c->self);
2266 continue;
2269 /* Get the amount of buffered data for this channel. */
2270 if ((c->istate == CHAN_INPUT_OPEN ||
2271 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
2272 (len = buffer_len(&c->input)) > 0) {
2273 if (c->datagram) {
2274 if (len > 0) {
2275 u_char *data;
2276 u_int dlen;
2278 data = buffer_get_string(&c->input,
2279 &dlen);
2280 if (dlen > c->remote_window ||
2281 dlen > c->remote_maxpacket) {
2282 debug("channel %d: datagram "
2283 "too big for channel",
2284 c->self);
2285 free(data);
2286 continue;
2288 packet_start(SSH2_MSG_CHANNEL_DATA);
2289 packet_put_int(c->remote_id);
2290 packet_put_string(data, dlen);
2291 packet_send();
2292 c->remote_window -= dlen;
2293 free(data);
2295 continue;
2298 * Send some data for the other side over the secure
2299 * connection.
2301 if (compat20) {
2302 if (len > c->remote_window)
2303 len = c->remote_window;
2304 if (len > c->remote_maxpacket)
2305 len = c->remote_maxpacket;
2306 } else {
2307 if (packet_is_interactive()) {
2308 if (len > 1024)
2309 len = 512;
2310 } else {
2311 /* Keep the packets at reasonable size. */
2312 if (len > packet_get_maxsize()/2)
2313 len = packet_get_maxsize()/2;
2316 if (len > 0) {
2317 packet_start(compat20 ?
2318 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2319 packet_put_int(c->remote_id);
2320 packet_put_string(buffer_ptr(&c->input), len);
2321 packet_send();
2322 buffer_consume(&c->input, len);
2323 c->remote_window -= len;
2325 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2326 if (compat13)
2327 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2329 * input-buffer is empty and read-socket shutdown:
2330 * tell peer, that we will not send more data: send IEOF.
2331 * hack for extended data: delay EOF if EFD still in use.
2333 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2334 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2335 c->self, c->efd, buffer_len(&c->extended));
2336 else
2337 chan_ibuf_empty(c);
2339 /* Send extended data, i.e. stderr */
2340 if (compat20 &&
2341 !(c->flags & CHAN_EOF_SENT) &&
2342 c->remote_window > 0 &&
2343 (len = buffer_len(&c->extended)) > 0 &&
2344 c->extended_usage == CHAN_EXTENDED_READ) {
2345 debug2("channel %d: rwin %u elen %u euse %d",
2346 c->self, c->remote_window, buffer_len(&c->extended),
2347 c->extended_usage);
2348 if (len > c->remote_window)
2349 len = c->remote_window;
2350 if (len > c->remote_maxpacket)
2351 len = c->remote_maxpacket;
2352 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2353 packet_put_int(c->remote_id);
2354 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2355 packet_put_string(buffer_ptr(&c->extended), len);
2356 packet_send();
2357 buffer_consume(&c->extended, len);
2358 c->remote_window -= len;
2359 debug2("channel %d: sent ext data %d", c->self, len);
2365 /* -- protocol input */
2367 /* ARGSUSED */
2369 channel_input_data(int type, u_int32_t seq, void *ctxt)
2371 int id;
2372 const u_char *data;
2373 u_int data_len, win_len;
2374 Channel *c;
2376 /* Get the channel number and verify it. */
2377 id = packet_get_int();
2378 c = channel_lookup(id);
2379 if (c == NULL)
2380 packet_disconnect("Received data for nonexistent channel %d.", id);
2382 /* Ignore any data for non-open channels (might happen on close) */
2383 if (c->type != SSH_CHANNEL_OPEN &&
2384 c->type != SSH_CHANNEL_X11_OPEN)
2385 return 0;
2387 /* Get the data. */
2388 data = packet_get_string_ptr(&data_len);
2389 win_len = data_len;
2390 if (c->datagram)
2391 win_len += 4; /* string length header */
2394 * Ignore data for protocol > 1.3 if output end is no longer open.
2395 * For protocol 2 the sending side is reducing its window as it sends
2396 * data, so we must 'fake' consumption of the data in order to ensure
2397 * that window updates are sent back. Otherwise the connection might
2398 * deadlock.
2400 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2401 if (compat20) {
2402 c->local_window -= win_len;
2403 c->local_consumed += win_len;
2405 return 0;
2408 if (compat20) {
2409 if (win_len > c->local_maxpacket) {
2410 logit("channel %d: rcvd big packet %d, maxpack %d",
2411 c->self, win_len, c->local_maxpacket);
2413 if (win_len > c->local_window) {
2414 logit("channel %d: rcvd too much data %d, win %d",
2415 c->self, win_len, c->local_window);
2416 return 0;
2418 c->local_window -= win_len;
2420 if (c->datagram)
2421 buffer_put_string(&c->output, data, data_len);
2422 else
2423 buffer_append(&c->output, data, data_len);
2424 packet_check_eom();
2425 return 0;
2428 /* ARGSUSED */
2430 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2432 int id;
2433 char *data;
2434 u_int data_len, tcode;
2435 Channel *c;
2437 /* Get the channel number and verify it. */
2438 id = packet_get_int();
2439 c = channel_lookup(id);
2441 if (c == NULL)
2442 packet_disconnect("Received extended_data for bad channel %d.", id);
2443 if (c->type != SSH_CHANNEL_OPEN) {
2444 logit("channel %d: ext data for non open", id);
2445 return 0;
2447 if (c->flags & CHAN_EOF_RCVD) {
2448 if (datafellows & SSH_BUG_EXTEOF)
2449 debug("channel %d: accepting ext data after eof", id);
2450 else
2451 packet_disconnect("Received extended_data after EOF "
2452 "on channel %d.", id);
2454 tcode = packet_get_int();
2455 if (c->efd == -1 ||
2456 c->extended_usage != CHAN_EXTENDED_WRITE ||
2457 tcode != SSH2_EXTENDED_DATA_STDERR) {
2458 logit("channel %d: bad ext data", c->self);
2459 return 0;
2461 data = packet_get_string(&data_len);
2462 packet_check_eom();
2463 if (data_len > c->local_window) {
2464 logit("channel %d: rcvd too much extended_data %d, win %d",
2465 c->self, data_len, c->local_window);
2466 free(data);
2467 return 0;
2469 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2470 c->local_window -= data_len;
2471 buffer_append(&c->extended, data, data_len);
2472 free(data);
2473 return 0;
2476 /* ARGSUSED */
2478 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2480 int id;
2481 Channel *c;
2483 id = packet_get_int();
2484 packet_check_eom();
2485 c = channel_lookup(id);
2486 if (c == NULL)
2487 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2488 chan_rcvd_ieof(c);
2490 /* XXX force input close */
2491 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2492 debug("channel %d: FORCE input drain", c->self);
2493 c->istate = CHAN_INPUT_WAIT_DRAIN;
2494 if (buffer_len(&c->input) == 0)
2495 chan_ibuf_empty(c);
2497 return 0;
2500 /* ARGSUSED */
2502 channel_input_close(int type, u_int32_t seq, void *ctxt)
2504 int id;
2505 Channel *c;
2507 id = packet_get_int();
2508 packet_check_eom();
2509 c = channel_lookup(id);
2510 if (c == NULL)
2511 packet_disconnect("Received close for nonexistent channel %d.", id);
2514 * Send a confirmation that we have closed the channel and no more
2515 * data is coming for it.
2517 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2518 packet_put_int(c->remote_id);
2519 packet_send();
2522 * If the channel is in closed state, we have sent a close request,
2523 * and the other side will eventually respond with a confirmation.
2524 * Thus, we cannot free the channel here, because then there would be
2525 * no-one to receive the confirmation. The channel gets freed when
2526 * the confirmation arrives.
2528 if (c->type != SSH_CHANNEL_CLOSED) {
2530 * Not a closed channel - mark it as draining, which will
2531 * cause it to be freed later.
2533 buffer_clear(&c->input);
2534 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2536 return 0;
2539 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2540 /* ARGSUSED */
2542 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2544 int id = packet_get_int();
2545 Channel *c = channel_lookup(id);
2547 packet_check_eom();
2548 if (c == NULL)
2549 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2550 chan_rcvd_oclose(c);
2551 return 0;
2554 /* ARGSUSED */
2556 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2558 int id = packet_get_int();
2559 Channel *c = channel_lookup(id);
2561 packet_check_eom();
2562 if (c == NULL)
2563 packet_disconnect("Received close confirmation for "
2564 "out-of-range channel %d.", id);
2565 if (c->type != SSH_CHANNEL_CLOSED && c->type != SSH_CHANNEL_ABANDONED)
2566 packet_disconnect("Received close confirmation for "
2567 "non-closed channel %d (type %d).", id, c->type);
2568 channel_free(c);
2569 return 0;
2572 /* ARGSUSED */
2574 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2576 int id, remote_id;
2577 Channel *c;
2579 id = packet_get_int();
2580 c = channel_lookup(id);
2582 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2583 packet_disconnect("Received open confirmation for "
2584 "non-opening channel %d.", id);
2585 remote_id = packet_get_int();
2586 /* Record the remote channel number and mark that the channel is now open. */
2587 c->remote_id = remote_id;
2588 c->type = SSH_CHANNEL_OPEN;
2590 if (compat20) {
2591 c->remote_window = packet_get_int();
2592 c->remote_maxpacket = packet_get_int();
2593 if (c->open_confirm) {
2594 debug2("callback start");
2595 c->open_confirm(c->self, 1, c->open_confirm_ctx);
2596 debug2("callback done");
2598 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2599 c->remote_window, c->remote_maxpacket);
2601 packet_check_eom();
2602 return 0;
2605 static char *
2606 reason2txt(int reason)
2608 switch (reason) {
2609 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2610 return "administratively prohibited";
2611 case SSH2_OPEN_CONNECT_FAILED:
2612 return "connect failed";
2613 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2614 return "unknown channel type";
2615 case SSH2_OPEN_RESOURCE_SHORTAGE:
2616 return "resource shortage";
2618 return "unknown reason";
2621 /* ARGSUSED */
2623 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2625 int id, reason;
2626 char *msg = NULL, *lang = NULL;
2627 Channel *c;
2629 id = packet_get_int();
2630 c = channel_lookup(id);
2632 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2633 packet_disconnect("Received open failure for "
2634 "non-opening channel %d.", id);
2635 if (compat20) {
2636 reason = packet_get_int();
2637 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2638 msg = packet_get_string(NULL);
2639 lang = packet_get_string(NULL);
2641 logit("channel %d: open failed: %s%s%s", id,
2642 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2643 free(msg);
2644 free(lang);
2645 if (c->open_confirm) {
2646 debug2("callback start");
2647 c->open_confirm(c->self, 0, c->open_confirm_ctx);
2648 debug2("callback done");
2651 packet_check_eom();
2652 /* Schedule the channel for cleanup/deletion. */
2653 chan_mark_dead(c);
2654 return 0;
2657 /* ARGSUSED */
2659 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2661 Channel *c;
2662 int id;
2663 u_int adjust, tmp;
2665 if (!compat20)
2666 return 0;
2668 /* Get the channel number and verify it. */
2669 id = packet_get_int();
2670 c = channel_lookup(id);
2672 if (c == NULL) {
2673 logit("Received window adjust for non-open channel %d.", id);
2674 return 0;
2676 adjust = packet_get_int();
2677 packet_check_eom();
2678 debug2("channel %d: rcvd adjust %u", id, adjust);
2679 if ((tmp = c->remote_window + adjust) < c->remote_window)
2680 fatal("channel %d: adjust %u overflows remote window %u",
2681 id, adjust, c->remote_window);
2682 c->remote_window = tmp;
2683 return 0;
2686 /* ARGSUSED */
2688 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2690 Channel *c = NULL;
2691 u_short host_port;
2692 char *host, *originator_string;
2693 int remote_id;
2695 remote_id = packet_get_int();
2696 host = packet_get_string(NULL);
2697 host_port = packet_get_int();
2699 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2700 originator_string = packet_get_string(NULL);
2701 } else {
2702 originator_string = xstrdup("unknown (remote did not supply name)");
2704 packet_check_eom();
2705 c = channel_connect_to_port(host, host_port,
2706 "connected socket", originator_string);
2707 free(originator_string);
2708 free(host);
2709 if (c == NULL) {
2710 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2711 packet_put_int(remote_id);
2712 packet_send();
2713 } else
2714 c->remote_id = remote_id;
2715 return 0;
2718 /* ARGSUSED */
2720 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2722 Channel *c;
2723 struct channel_confirm *cc;
2724 int id;
2726 /* Reset keepalive timeout */
2727 packet_set_alive_timeouts(0);
2729 id = packet_get_int();
2730 packet_check_eom();
2732 debug2("channel_input_status_confirm: type %d id %d", type, id);
2734 if ((c = channel_lookup(id)) == NULL) {
2735 logit("channel_input_status_confirm: %d: unknown", id);
2736 return 0;
2738 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2739 return 0;
2740 cc->cb(type, c, cc->ctx);
2741 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2742 explicit_bzero(cc, sizeof(*cc));
2743 free(cc);
2744 return 0;
2747 /* -- tcp forwarding */
2749 void
2750 channel_set_af(int af)
2752 IPv4or6 = af;
2757 * Determine whether or not a port forward listens to loopback, the
2758 * specified address or wildcard. On the client, a specified bind
2759 * address will always override gateway_ports. On the server, a
2760 * gateway_ports of 1 (``yes'') will override the client's specification
2761 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2762 * will bind to whatever address the client asked for.
2764 * Special-case listen_addrs are:
2766 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2767 * "" (empty string), "*" -> wildcard v4/v6
2768 * "localhost" -> loopback v4/v6
2769 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
2771 static const char *
2772 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
2773 int is_client, struct ForwardOptions *fwd_opts)
2775 const char *addr = NULL;
2776 int wildcard = 0;
2778 if (listen_addr == NULL) {
2779 /* No address specified: default to gateway_ports setting */
2780 if (fwd_opts->gateway_ports)
2781 wildcard = 1;
2782 } else if (fwd_opts->gateway_ports || is_client) {
2783 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2784 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2785 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2786 (!is_client && fwd_opts->gateway_ports == 1)) {
2787 wildcard = 1;
2789 * Notify client if they requested a specific listen
2790 * address and it was overridden.
2792 if (*listen_addr != '\0' &&
2793 strcmp(listen_addr, "0.0.0.0") != 0 &&
2794 strcmp(listen_addr, "*") != 0) {
2795 packet_send_debug("Forwarding listen address "
2796 "\"%s\" overridden by server "
2797 "GatewayPorts", listen_addr);
2799 } else if (strcmp(listen_addr, "localhost") != 0 ||
2800 strcmp(listen_addr, "127.0.0.1") == 0 ||
2801 strcmp(listen_addr, "::1") == 0) {
2802 /* Accept localhost address when GatewayPorts=yes */
2803 addr = listen_addr;
2805 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
2806 strcmp(listen_addr, "::1") == 0) {
2808 * If a specific IPv4/IPv6 localhost address has been
2809 * requested then accept it even if gateway_ports is in
2810 * effect. This allows the client to prefer IPv4 or IPv6.
2812 addr = listen_addr;
2814 if (wildcardp != NULL)
2815 *wildcardp = wildcard;
2816 return addr;
2819 static int
2820 channel_setup_fwd_listener_tcpip(int type, struct Forward *fwd,
2821 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
2823 Channel *c;
2824 int sock, r, success = 0, wildcard = 0, is_client;
2825 struct addrinfo hints, *ai, *aitop;
2826 const char *host, *addr;
2827 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2828 in_port_t *lport_p;
2830 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2832 if (is_client && fwd->connect_path != NULL) {
2833 host = fwd->connect_path;
2834 } else {
2835 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2836 fwd->listen_host : fwd->connect_host;
2837 if (host == NULL) {
2838 error("No forward host name.");
2839 return 0;
2841 if (strlen(host) >= NI_MAXHOST) {
2842 error("Forward host name too long.");
2843 return 0;
2847 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2848 addr = channel_fwd_bind_addr(fwd->listen_host, &wildcard,
2849 is_client, fwd_opts);
2850 debug3("%s: type %d wildcard %d addr %s", __func__,
2851 type, wildcard, (addr == NULL) ? "NULL" : addr);
2854 * getaddrinfo returns a loopback address if the hostname is
2855 * set to NULL and hints.ai_flags is not AI_PASSIVE
2857 memset(&hints, 0, sizeof(hints));
2858 hints.ai_family = IPv4or6;
2859 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2860 hints.ai_socktype = SOCK_STREAM;
2861 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
2862 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2863 if (addr == NULL) {
2864 /* This really shouldn't happen */
2865 packet_disconnect("getaddrinfo: fatal error: %s",
2866 ssh_gai_strerror(r));
2867 } else {
2868 error("%s: getaddrinfo(%.64s): %s", __func__, addr,
2869 ssh_gai_strerror(r));
2871 return 0;
2873 if (allocated_listen_port != NULL)
2874 *allocated_listen_port = 0;
2875 for (ai = aitop; ai; ai = ai->ai_next) {
2876 switch (ai->ai_family) {
2877 case AF_INET:
2878 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
2879 sin_port;
2880 break;
2881 case AF_INET6:
2882 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
2883 sin6_port;
2884 break;
2885 default:
2886 continue;
2889 * If allocating a port for -R forwards, then use the
2890 * same port for all address families.
2892 if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
2893 allocated_listen_port != NULL && *allocated_listen_port > 0)
2894 *lport_p = htons(*allocated_listen_port);
2896 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2897 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2898 error("%s: getnameinfo failed", __func__);
2899 continue;
2901 /* Create a port to listen for the host. */
2902 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2903 if (sock < 0) {
2904 /* this is no error since kernel may not support ipv6 */
2905 verbose("socket: %.100s", strerror(errno));
2906 continue;
2909 channel_set_reuseaddr(sock);
2910 if (ai->ai_family == AF_INET6)
2911 sock_set_v6only(sock);
2913 debug("Local forwarding listening on %s port %s.",
2914 ntop, strport);
2916 /* Bind the socket to the address. */
2917 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2918 /* address can be in use ipv6 address is already bound */
2919 if (!ai->ai_next)
2920 error("bind: %.100s", strerror(errno));
2921 else
2922 verbose("bind: %.100s", strerror(errno));
2924 close(sock);
2925 continue;
2927 /* Start listening for connections on the socket. */
2928 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2929 error("listen: %.100s", strerror(errno));
2930 close(sock);
2931 continue;
2935 * fwd->listen_port == 0 requests a dynamically allocated port -
2936 * record what we got.
2938 if (type == SSH_CHANNEL_RPORT_LISTENER && fwd->listen_port == 0 &&
2939 allocated_listen_port != NULL &&
2940 *allocated_listen_port == 0) {
2941 *allocated_listen_port = get_local_port(sock);
2942 debug("Allocated listen port %d",
2943 *allocated_listen_port);
2946 /* Allocate a channel number for the socket. */
2947 c = channel_new("port listener", type, sock, sock, -1,
2948 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2949 0, "port listener", 1);
2950 c->path = xstrdup(host);
2951 c->host_port = fwd->connect_port;
2952 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
2953 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
2954 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
2955 c->listening_port = *allocated_listen_port;
2956 else
2957 c->listening_port = fwd->listen_port;
2958 success = 1;
2960 if (success == 0)
2961 error("%s: cannot listen to port: %d", __func__,
2962 fwd->listen_port);
2963 freeaddrinfo(aitop);
2964 return success;
2967 static int
2968 channel_setup_fwd_listener_streamlocal(int type, struct Forward *fwd,
2969 struct ForwardOptions *fwd_opts)
2971 struct sockaddr_un sunaddr;
2972 const char *path;
2973 Channel *c;
2974 int port, sock;
2975 mode_t omask;
2977 switch (type) {
2978 case SSH_CHANNEL_UNIX_LISTENER:
2979 if (fwd->connect_path != NULL) {
2980 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
2981 error("Local connecting path too long: %s",
2982 fwd->connect_path);
2983 return 0;
2985 path = fwd->connect_path;
2986 port = PORT_STREAMLOCAL;
2987 } else {
2988 if (fwd->connect_host == NULL) {
2989 error("No forward host name.");
2990 return 0;
2992 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
2993 error("Forward host name too long.");
2994 return 0;
2996 path = fwd->connect_host;
2997 port = fwd->connect_port;
2999 break;
3000 case SSH_CHANNEL_RUNIX_LISTENER:
3001 path = fwd->listen_path;
3002 port = PORT_STREAMLOCAL;
3003 break;
3004 default:
3005 error("%s: unexpected channel type %d", __func__, type);
3006 return 0;
3009 if (fwd->listen_path == NULL) {
3010 error("No forward path name.");
3011 return 0;
3013 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3014 error("Local listening path too long: %s", fwd->listen_path);
3015 return 0;
3018 debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
3020 /* Start a Unix domain listener. */
3021 omask = umask(fwd_opts->streamlocal_bind_mask);
3022 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3023 fwd_opts->streamlocal_bind_unlink);
3024 umask(omask);
3025 if (sock < 0)
3026 return 0;
3028 debug("Local forwarding listening on path %s.", fwd->listen_path);
3030 /* Allocate a channel number for the socket. */
3031 c = channel_new("unix listener", type, sock, sock, -1,
3032 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3033 0, "unix listener", 1);
3034 c->path = xstrdup(path);
3035 c->host_port = port;
3036 c->listening_port = PORT_STREAMLOCAL;
3037 c->listening_addr = xstrdup(fwd->listen_path);
3038 return 1;
3041 static int
3042 channel_cancel_rport_listener_tcpip(const char *host, u_short port)
3044 u_int i;
3045 int found = 0;
3047 for (i = 0; i < channels_alloc; i++) {
3048 Channel *c = channels[i];
3049 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3050 continue;
3051 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3052 debug2("%s: close channel %d", __func__, i);
3053 channel_free(c);
3054 found = 1;
3058 return (found);
3061 static int
3062 channel_cancel_rport_listener_streamlocal(const char *path)
3064 u_int i;
3065 int found = 0;
3067 for (i = 0; i < channels_alloc; i++) {
3068 Channel *c = channels[i];
3069 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3070 continue;
3071 if (c->path == NULL)
3072 continue;
3073 if (strcmp(c->path, path) == 0) {
3074 debug2("%s: close channel %d", __func__, i);
3075 channel_free(c);
3076 found = 1;
3080 return (found);
3084 channel_cancel_rport_listener(struct Forward *fwd)
3086 if (fwd->listen_path != NULL)
3087 return channel_cancel_rport_listener_streamlocal(fwd->listen_path);
3088 else
3089 return channel_cancel_rport_listener_tcpip(fwd->listen_host, fwd->listen_port);
3092 static int
3093 channel_cancel_lport_listener_tcpip(const char *lhost, u_short lport,
3094 int cport, struct ForwardOptions *fwd_opts)
3096 u_int i;
3097 int found = 0;
3098 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, fwd_opts);
3100 for (i = 0; i < channels_alloc; i++) {
3101 Channel *c = channels[i];
3102 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3103 continue;
3104 if (c->listening_port != lport)
3105 continue;
3106 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3107 /* skip dynamic forwardings */
3108 if (c->host_port == 0)
3109 continue;
3110 } else {
3111 if (c->host_port != cport)
3112 continue;
3114 if ((c->listening_addr == NULL && addr != NULL) ||
3115 (c->listening_addr != NULL && addr == NULL))
3116 continue;
3117 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3118 debug2("%s: close channel %d", __func__, i);
3119 channel_free(c);
3120 found = 1;
3124 return (found);
3127 static int
3128 channel_cancel_lport_listener_streamlocal(const char *path)
3130 u_int i;
3131 int found = 0;
3133 if (path == NULL) {
3134 error("%s: no path specified.", __func__);
3135 return 0;
3138 for (i = 0; i < channels_alloc; i++) {
3139 Channel *c = channels[i];
3140 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3141 continue;
3142 if (c->listening_addr == NULL)
3143 continue;
3144 if (strcmp(c->listening_addr, path) == 0) {
3145 debug2("%s: close channel %d", __func__, i);
3146 channel_free(c);
3147 found = 1;
3151 return (found);
3155 channel_cancel_lport_listener(struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3157 if (fwd->listen_path != NULL)
3158 return channel_cancel_lport_listener_streamlocal(fwd->listen_path);
3159 else
3160 return channel_cancel_lport_listener_tcpip(fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3163 /* protocol local port fwd, used by ssh (and sshd in v1) */
3165 channel_setup_local_fwd_listener(struct Forward *fwd, struct ForwardOptions *fwd_opts)
3167 if (fwd->listen_path != NULL) {
3168 return channel_setup_fwd_listener_streamlocal(
3169 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3170 } else {
3171 return channel_setup_fwd_listener_tcpip(SSH_CHANNEL_PORT_LISTENER,
3172 fwd, NULL, fwd_opts);
3176 /* protocol v2 remote port fwd, used by sshd */
3178 channel_setup_remote_fwd_listener(struct Forward *fwd,
3179 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
3181 if (fwd->listen_path != NULL) {
3182 return channel_setup_fwd_listener_streamlocal(
3183 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
3184 } else {
3185 return channel_setup_fwd_listener_tcpip(
3186 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
3187 fwd_opts);
3192 * Translate the requested rfwd listen host to something usable for
3193 * this server.
3195 static const char *
3196 channel_rfwd_bind_host(const char *listen_host)
3198 if (listen_host == NULL) {
3199 if (datafellows & SSH_BUG_RFWD_ADDR)
3200 return "127.0.0.1";
3201 else
3202 return "localhost";
3203 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3204 if (datafellows & SSH_BUG_RFWD_ADDR)
3205 return "0.0.0.0";
3206 else
3207 return "";
3208 } else
3209 return listen_host;
3213 * Initiate forwarding of connections to port "port" on remote host through
3214 * the secure channel to host:port from local side.
3215 * Returns handle (index) for updating the dynamic listen port with
3216 * channel_update_permitted_opens().
3219 channel_request_remote_forwarding(struct Forward *fwd)
3221 int type, success = 0, idx = -1;
3223 /* Send the forward request to the remote side. */
3224 if (compat20) {
3225 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3226 if (fwd->listen_path != NULL) {
3227 packet_put_cstring("streamlocal-forward@openssh.com");
3228 packet_put_char(1); /* boolean: want reply */
3229 packet_put_cstring(fwd->listen_path);
3230 } else {
3231 packet_put_cstring("tcpip-forward");
3232 packet_put_char(1); /* boolean: want reply */
3233 packet_put_cstring(channel_rfwd_bind_host(fwd->listen_host));
3234 packet_put_int(fwd->listen_port);
3236 packet_send();
3237 packet_write_wait();
3238 /* Assume that server accepts the request */
3239 success = 1;
3240 } else if (fwd->listen_path == NULL) {
3241 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
3242 packet_put_int(fwd->listen_port);
3243 packet_put_cstring(fwd->connect_host);
3244 packet_put_int(fwd->connect_port);
3245 packet_send();
3246 packet_write_wait();
3248 /* Wait for response from the remote side. */
3249 type = packet_read();
3250 switch (type) {
3251 case SSH_SMSG_SUCCESS:
3252 success = 1;
3253 break;
3254 case SSH_SMSG_FAILURE:
3255 break;
3256 default:
3257 /* Unknown packet */
3258 packet_disconnect("Protocol error for port forward request:"
3259 "received packet type %d.", type);
3261 } else {
3262 logit("Warning: Server does not support remote stream local forwarding.");
3264 if (success) {
3265 /* Record that connection to this host/port is permitted. */
3266 permitted_opens = xreallocarray(permitted_opens,
3267 num_permitted_opens + 1, sizeof(*permitted_opens));
3268 idx = num_permitted_opens++;
3269 if (fwd->connect_path != NULL) {
3270 permitted_opens[idx].host_to_connect =
3271 xstrdup(fwd->connect_path);
3272 permitted_opens[idx].port_to_connect =
3273 PORT_STREAMLOCAL;
3274 } else {
3275 permitted_opens[idx].host_to_connect =
3276 xstrdup(fwd->connect_host);
3277 permitted_opens[idx].port_to_connect =
3278 fwd->connect_port;
3280 if (fwd->listen_path != NULL) {
3281 permitted_opens[idx].listen_host = NULL;
3282 permitted_opens[idx].listen_path =
3283 xstrdup(fwd->listen_path);
3284 permitted_opens[idx].listen_port = PORT_STREAMLOCAL;
3285 } else {
3286 permitted_opens[idx].listen_host =
3287 fwd->listen_host ? xstrdup(fwd->listen_host) : NULL;
3288 permitted_opens[idx].listen_path = NULL;
3289 permitted_opens[idx].listen_port = fwd->listen_port;
3292 return (idx);
3295 static int
3296 open_match(ForwardPermission *allowed_open, const char *requestedhost,
3297 int requestedport)
3299 if (allowed_open->host_to_connect == NULL)
3300 return 0;
3301 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
3302 allowed_open->port_to_connect != requestedport)
3303 return 0;
3304 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
3305 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
3306 return 0;
3307 return 1;
3311 * Note that in the listen host/port case
3312 * we don't support FWD_PERMIT_ANY_PORT and
3313 * need to translate between the configured-host (listen_host)
3314 * and what we've sent to the remote server (channel_rfwd_bind_host)
3316 static int
3317 open_listen_match_tcpip(ForwardPermission *allowed_open,
3318 const char *requestedhost, u_short requestedport, int translate)
3320 const char *allowed_host;
3322 if (allowed_open->host_to_connect == NULL)
3323 return 0;
3324 if (allowed_open->listen_port != requestedport)
3325 return 0;
3326 if (!translate && allowed_open->listen_host == NULL &&
3327 requestedhost == NULL)
3328 return 1;
3329 allowed_host = translate ?
3330 channel_rfwd_bind_host(allowed_open->listen_host) :
3331 allowed_open->listen_host;
3332 if (allowed_host == NULL ||
3333 strcmp(allowed_host, requestedhost) != 0)
3334 return 0;
3335 return 1;
3338 static int
3339 open_listen_match_streamlocal(ForwardPermission *allowed_open,
3340 const char *requestedpath)
3342 if (allowed_open->host_to_connect == NULL)
3343 return 0;
3344 if (allowed_open->listen_port != PORT_STREAMLOCAL)
3345 return 0;
3346 if (allowed_open->listen_path == NULL ||
3347 strcmp(allowed_open->listen_path, requestedpath) != 0)
3348 return 0;
3349 return 1;
3353 * Request cancellation of remote forwarding of connection host:port from
3354 * local side.
3356 static int
3357 channel_request_rforward_cancel_tcpip(const char *host, u_short port)
3359 int i;
3361 if (!compat20)
3362 return -1;
3364 for (i = 0; i < num_permitted_opens; i++) {
3365 if (open_listen_match_tcpip(&permitted_opens[i], host, port, 0))
3366 break;
3368 if (i >= num_permitted_opens) {
3369 debug("%s: requested forward not found", __func__);
3370 return -1;
3372 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3373 packet_put_cstring("cancel-tcpip-forward");
3374 packet_put_char(0);
3375 packet_put_cstring(channel_rfwd_bind_host(host));
3376 packet_put_int(port);
3377 packet_send();
3379 permitted_opens[i].listen_port = 0;
3380 permitted_opens[i].port_to_connect = 0;
3381 free(permitted_opens[i].host_to_connect);
3382 permitted_opens[i].host_to_connect = NULL;
3383 free(permitted_opens[i].listen_host);
3384 permitted_opens[i].listen_host = NULL;
3385 permitted_opens[i].listen_path = NULL;
3387 return 0;
3391 * Request cancellation of remote forwarding of Unix domain socket
3392 * path from local side.
3394 static int
3395 channel_request_rforward_cancel_streamlocal(const char *path)
3397 int i;
3399 if (!compat20)
3400 return -1;
3402 for (i = 0; i < num_permitted_opens; i++) {
3403 if (open_listen_match_streamlocal(&permitted_opens[i], path))
3404 break;
3406 if (i >= num_permitted_opens) {
3407 debug("%s: requested forward not found", __func__);
3408 return -1;
3410 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3411 packet_put_cstring("cancel-streamlocal-forward@openssh.com");
3412 packet_put_char(0);
3413 packet_put_cstring(path);
3414 packet_send();
3416 permitted_opens[i].listen_port = 0;
3417 permitted_opens[i].port_to_connect = 0;
3418 free(permitted_opens[i].host_to_connect);
3419 permitted_opens[i].host_to_connect = NULL;
3420 permitted_opens[i].listen_host = NULL;
3421 free(permitted_opens[i].listen_path);
3422 permitted_opens[i].listen_path = NULL;
3424 return 0;
3428 * Request cancellation of remote forwarding of a connection from local side.
3431 channel_request_rforward_cancel(struct Forward *fwd)
3433 if (fwd->listen_path != NULL) {
3434 return (channel_request_rforward_cancel_streamlocal(
3435 fwd->listen_path));
3436 } else {
3437 return (channel_request_rforward_cancel_tcpip(fwd->listen_host,
3438 fwd->listen_port ? fwd->listen_port : fwd->allocated_port));
3443 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3444 * listening for the port, and sends back a success reply (or disconnect
3445 * message if there was an error).
3448 channel_input_port_forward_request(int is_root, struct ForwardOptions *fwd_opts)
3450 int success = 0;
3451 struct Forward fwd;
3453 /* Get arguments from the packet. */
3454 memset(&fwd, 0, sizeof(fwd));
3455 fwd.listen_port = packet_get_int();
3456 fwd.connect_host = packet_get_string(NULL);
3457 fwd.connect_port = packet_get_int();
3459 #ifndef HAVE_CYGWIN
3461 * Check that an unprivileged user is not trying to forward a
3462 * privileged port.
3464 if (fwd.listen_port < IPPORT_RESERVED && !is_root)
3465 packet_disconnect(
3466 "Requested forwarding of port %d but user is not root.",
3467 fwd.listen_port);
3468 if (fwd.connect_port == 0)
3469 packet_disconnect("Dynamic forwarding denied.");
3470 #endif
3472 /* Initiate forwarding */
3473 success = channel_setup_local_fwd_listener(&fwd, fwd_opts);
3475 /* Free the argument string. */
3476 free(fwd.connect_host);
3478 return (success ? 0 : -1);
3482 * Permits opening to any host/port if permitted_opens[] is empty. This is
3483 * usually called by the server, because the user could connect to any port
3484 * anyway, and the server has no way to know but to trust the client anyway.
3486 void
3487 channel_permit_all_opens(void)
3489 if (num_permitted_opens == 0)
3490 all_opens_permitted = 1;
3493 void
3494 channel_add_permitted_opens(char *host, int port)
3496 debug("allow port forwarding to host %s port %d", host, port);
3498 permitted_opens = xreallocarray(permitted_opens,
3499 num_permitted_opens + 1, sizeof(*permitted_opens));
3500 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
3501 permitted_opens[num_permitted_opens].port_to_connect = port;
3502 permitted_opens[num_permitted_opens].listen_host = NULL;
3503 permitted_opens[num_permitted_opens].listen_path = NULL;
3504 permitted_opens[num_permitted_opens].listen_port = 0;
3505 num_permitted_opens++;
3507 all_opens_permitted = 0;
3511 * Update the listen port for a dynamic remote forward, after
3512 * the actual 'newport' has been allocated. If 'newport' < 0 is
3513 * passed then they entry will be invalidated.
3515 void
3516 channel_update_permitted_opens(int idx, int newport)
3518 if (idx < 0 || idx >= num_permitted_opens) {
3519 debug("channel_update_permitted_opens: index out of range:"
3520 " %d num_permitted_opens %d", idx, num_permitted_opens);
3521 return;
3523 debug("%s allowed port %d for forwarding to host %s port %d",
3524 newport > 0 ? "Updating" : "Removing",
3525 newport,
3526 permitted_opens[idx].host_to_connect,
3527 permitted_opens[idx].port_to_connect);
3528 if (newport >= 0) {
3529 permitted_opens[idx].listen_port =
3530 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3531 } else {
3532 permitted_opens[idx].listen_port = 0;
3533 permitted_opens[idx].port_to_connect = 0;
3534 free(permitted_opens[idx].host_to_connect);
3535 permitted_opens[idx].host_to_connect = NULL;
3536 free(permitted_opens[idx].listen_host);
3537 permitted_opens[idx].listen_host = NULL;
3538 free(permitted_opens[idx].listen_path);
3539 permitted_opens[idx].listen_path = NULL;
3544 channel_add_adm_permitted_opens(char *host, int port)
3546 debug("config allows port forwarding to host %s port %d", host, port);
3548 permitted_adm_opens = xreallocarray(permitted_adm_opens,
3549 num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
3550 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3551 = xstrdup(host);
3552 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
3553 permitted_adm_opens[num_adm_permitted_opens].listen_host = NULL;
3554 permitted_adm_opens[num_adm_permitted_opens].listen_path = NULL;
3555 permitted_adm_opens[num_adm_permitted_opens].listen_port = 0;
3556 return ++num_adm_permitted_opens;
3559 void
3560 channel_disable_adm_local_opens(void)
3562 channel_clear_adm_permitted_opens();
3563 permitted_adm_opens = xcalloc(sizeof(*permitted_adm_opens), 1);
3564 permitted_adm_opens[num_adm_permitted_opens].host_to_connect = NULL;
3565 num_adm_permitted_opens = 1;
3568 void
3569 channel_clear_permitted_opens(void)
3571 int i;
3573 for (i = 0; i < num_permitted_opens; i++) {
3574 free(permitted_opens[i].host_to_connect);
3575 free(permitted_opens[i].listen_host);
3576 free(permitted_opens[i].listen_path);
3578 free(permitted_opens);
3579 permitted_opens = NULL;
3580 num_permitted_opens = 0;
3583 void
3584 channel_clear_adm_permitted_opens(void)
3586 int i;
3588 for (i = 0; i < num_adm_permitted_opens; i++) {
3589 free(permitted_adm_opens[i].host_to_connect);
3590 free(permitted_adm_opens[i].listen_host);
3591 free(permitted_adm_opens[i].listen_path);
3593 free(permitted_adm_opens);
3594 permitted_adm_opens = NULL;
3595 num_adm_permitted_opens = 0;
3598 void
3599 channel_print_adm_permitted_opens(void)
3601 int i;
3603 printf("permitopen");
3604 if (num_adm_permitted_opens == 0) {
3605 printf(" any\n");
3606 return;
3608 for (i = 0; i < num_adm_permitted_opens; i++)
3609 if (permitted_adm_opens[i].host_to_connect == NULL)
3610 printf(" none");
3611 else
3612 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
3613 permitted_adm_opens[i].port_to_connect);
3614 printf("\n");
3617 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3619 permitopen_port(const char *p)
3621 int port;
3623 if (strcmp(p, "*") == 0)
3624 return FWD_PERMIT_ANY_PORT;
3625 if ((port = a2port(p)) > 0)
3626 return port;
3627 return -1;
3630 /* Try to start non-blocking connect to next host in cctx list */
3631 static int
3632 connect_next(struct channel_connect *cctx)
3634 int sock, saved_errno;
3635 struct sockaddr_un *sunaddr;
3636 char ntop[NI_MAXHOST], strport[MAX(NI_MAXSERV,sizeof(sunaddr->sun_path))];
3638 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3639 switch (cctx->ai->ai_family) {
3640 case AF_UNIX:
3641 /* unix:pathname instead of host:port */
3642 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
3643 strlcpy(ntop, "unix", sizeof(ntop));
3644 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
3645 break;
3646 case AF_INET:
3647 case AF_INET6:
3648 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3649 ntop, sizeof(ntop), strport, sizeof(strport),
3650 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3651 error("connect_next: getnameinfo failed");
3652 continue;
3654 break;
3655 default:
3656 continue;
3658 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
3659 cctx->ai->ai_protocol)) == -1) {
3660 if (cctx->ai->ai_next == NULL)
3661 error("socket: %.100s", strerror(errno));
3662 else
3663 verbose("socket: %.100s", strerror(errno));
3664 continue;
3666 if (set_nonblock(sock) == -1)
3667 fatal("%s: set_nonblock(%d)", __func__, sock);
3668 if (connect(sock, cctx->ai->ai_addr,
3669 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
3670 debug("connect_next: host %.100s ([%.100s]:%s): "
3671 "%.100s", cctx->host, ntop, strport,
3672 strerror(errno));
3673 saved_errno = errno;
3674 close(sock);
3675 errno = saved_errno;
3676 continue; /* fail -- try next */
3678 if (cctx->ai->ai_family != AF_UNIX)
3679 set_nodelay(sock);
3680 debug("connect_next: host %.100s ([%.100s]:%s) "
3681 "in progress, fd=%d", cctx->host, ntop, strport, sock);
3682 cctx->ai = cctx->ai->ai_next;
3683 return sock;
3685 return -1;
3688 static void
3689 channel_connect_ctx_free(struct channel_connect *cctx)
3691 free(cctx->host);
3692 if (cctx->aitop) {
3693 if (cctx->aitop->ai_family == AF_UNIX)
3694 free(cctx->aitop);
3695 else
3696 freeaddrinfo(cctx->aitop);
3698 memset(cctx, 0, sizeof(*cctx));
3701 /* Return CONNECTING channel to remote host:port or local socket path */
3702 static Channel *
3703 connect_to(const char *name, int port, char *ctype, char *rname)
3705 struct addrinfo hints;
3706 int gaierr;
3707 int sock = -1;
3708 char strport[NI_MAXSERV];
3709 struct channel_connect cctx;
3710 Channel *c;
3712 memset(&cctx, 0, sizeof(cctx));
3714 if (port == PORT_STREAMLOCAL) {
3715 struct sockaddr_un *sunaddr;
3716 struct addrinfo *ai;
3718 if (strlen(name) > sizeof(sunaddr->sun_path)) {
3719 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
3720 return (NULL);
3724 * Fake up a struct addrinfo for AF_UNIX connections.
3725 * channel_connect_ctx_free() must check ai_family
3726 * and use free() not freeaddirinfo() for AF_UNIX.
3728 ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
3729 memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
3730 ai->ai_addr = (struct sockaddr *)(ai + 1);
3731 ai->ai_addrlen = sizeof(*sunaddr);
3732 ai->ai_family = AF_UNIX;
3733 ai->ai_socktype = SOCK_STREAM;
3734 ai->ai_protocol = PF_UNSPEC;
3735 sunaddr = (struct sockaddr_un *)ai->ai_addr;
3736 sunaddr->sun_family = AF_UNIX;
3737 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
3738 cctx.aitop = ai;
3739 } else {
3740 memset(&hints, 0, sizeof(hints));
3741 hints.ai_family = IPv4or6;
3742 hints.ai_socktype = SOCK_STREAM;
3743 snprintf(strport, sizeof strport, "%d", port);
3744 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx.aitop)) != 0) {
3745 error("connect_to %.100s: unknown host (%s)", name,
3746 ssh_gai_strerror(gaierr));
3747 return NULL;
3751 cctx.host = xstrdup(name);
3752 cctx.port = port;
3753 cctx.ai = cctx.aitop;
3755 if ((sock = connect_next(&cctx)) == -1) {
3756 error("connect to %.100s port %d failed: %s",
3757 name, port, strerror(errno));
3758 channel_connect_ctx_free(&cctx);
3759 return NULL;
3761 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
3762 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
3763 c->connect_ctx = cctx;
3764 return c;
3767 Channel *
3768 channel_connect_by_listen_address(const char *listen_host,
3769 u_short listen_port, char *ctype, char *rname)
3771 int i;
3773 for (i = 0; i < num_permitted_opens; i++) {
3774 if (open_listen_match_tcpip(&permitted_opens[i], listen_host,
3775 listen_port, 1)) {
3776 return connect_to(
3777 permitted_opens[i].host_to_connect,
3778 permitted_opens[i].port_to_connect, ctype, rname);
3781 error("WARNING: Server requests forwarding for unknown listen_port %d",
3782 listen_port);
3783 return NULL;
3786 Channel *
3787 channel_connect_by_listen_path(const char *path, char *ctype, char *rname)
3789 int i;
3791 for (i = 0; i < num_permitted_opens; i++) {
3792 if (open_listen_match_streamlocal(&permitted_opens[i], path)) {
3793 return connect_to(
3794 permitted_opens[i].host_to_connect,
3795 permitted_opens[i].port_to_connect, ctype, rname);
3798 error("WARNING: Server requests forwarding for unknown path %.100s",
3799 path);
3800 return NULL;
3803 /* Check if connecting to that port is permitted and connect. */
3804 Channel *
3805 channel_connect_to_port(const char *host, u_short port, char *ctype, char *rname)
3807 int i, permit, permit_adm = 1;
3809 permit = all_opens_permitted;
3810 if (!permit) {
3811 for (i = 0; i < num_permitted_opens; i++)
3812 if (open_match(&permitted_opens[i], host, port)) {
3813 permit = 1;
3814 break;
3818 if (num_adm_permitted_opens > 0) {
3819 permit_adm = 0;
3820 for (i = 0; i < num_adm_permitted_opens; i++)
3821 if (open_match(&permitted_adm_opens[i], host, port)) {
3822 permit_adm = 1;
3823 break;
3827 if (!permit || !permit_adm) {
3828 logit("Received request to connect to host %.100s port %d, "
3829 "but the request was denied.", host, port);
3830 return NULL;
3832 return connect_to(host, port, ctype, rname);
3835 /* Check if connecting to that path is permitted and connect. */
3836 Channel *
3837 channel_connect_to_path(const char *path, char *ctype, char *rname)
3839 int i, permit, permit_adm = 1;
3841 permit = all_opens_permitted;
3842 if (!permit) {
3843 for (i = 0; i < num_permitted_opens; i++)
3844 if (open_match(&permitted_opens[i], path, PORT_STREAMLOCAL)) {
3845 permit = 1;
3846 break;
3850 if (num_adm_permitted_opens > 0) {
3851 permit_adm = 0;
3852 for (i = 0; i < num_adm_permitted_opens; i++)
3853 if (open_match(&permitted_adm_opens[i], path, PORT_STREAMLOCAL)) {
3854 permit_adm = 1;
3855 break;
3859 if (!permit || !permit_adm) {
3860 logit("Received request to connect to path %.100s, "
3861 "but the request was denied.", path);
3862 return NULL;
3864 return connect_to(path, PORT_STREAMLOCAL, ctype, rname);
3867 void
3868 channel_send_window_changes(void)
3870 u_int i;
3871 struct winsize ws;
3873 for (i = 0; i < channels_alloc; i++) {
3874 if (channels[i] == NULL || !channels[i]->client_tty ||
3875 channels[i]->type != SSH_CHANNEL_OPEN)
3876 continue;
3877 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3878 continue;
3879 channel_request_start(i, "window-change", 0);
3880 packet_put_int((u_int)ws.ws_col);
3881 packet_put_int((u_int)ws.ws_row);
3882 packet_put_int((u_int)ws.ws_xpixel);
3883 packet_put_int((u_int)ws.ws_ypixel);
3884 packet_send();
3888 /* -- X11 forwarding */
3891 * Creates an internet domain socket for listening for X11 connections.
3892 * Returns 0 and a suitable display number for the DISPLAY variable
3893 * stored in display_numberp , or -1 if an error occurs.
3896 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
3897 int single_connection, u_int *display_numberp, int **chanids)
3899 Channel *nc = NULL;
3900 int display_number, sock;
3901 u_short port;
3902 struct addrinfo hints, *ai, *aitop;
3903 char strport[NI_MAXSERV];
3904 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3906 if (chanids == NULL)
3907 return -1;
3909 for (display_number = x11_display_offset;
3910 display_number < MAX_DISPLAYS;
3911 display_number++) {
3912 port = 6000 + display_number;
3913 memset(&hints, 0, sizeof(hints));
3914 hints.ai_family = IPv4or6;
3915 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3916 hints.ai_socktype = SOCK_STREAM;
3917 snprintf(strport, sizeof strport, "%d", port);
3918 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3919 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3920 return -1;
3922 for (ai = aitop; ai; ai = ai->ai_next) {
3923 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3924 continue;
3925 sock = socket(ai->ai_family, ai->ai_socktype,
3926 ai->ai_protocol);
3927 if (sock < 0) {
3928 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
3929 #ifdef EPFNOSUPPORT
3930 && (errno != EPFNOSUPPORT)
3931 #endif
3933 error("socket: %.100s", strerror(errno));
3934 freeaddrinfo(aitop);
3935 return -1;
3936 } else {
3937 debug("x11_create_display_inet: Socket family %d not supported",
3938 ai->ai_family);
3939 continue;
3942 if (ai->ai_family == AF_INET6)
3943 sock_set_v6only(sock);
3944 if (x11_use_localhost)
3945 channel_set_reuseaddr(sock);
3946 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3947 debug2("bind port %d: %.100s", port, strerror(errno));
3948 close(sock);
3950 for (n = 0; n < num_socks; n++) {
3951 close(socks[n]);
3953 num_socks = 0;
3954 break;
3956 socks[num_socks++] = sock;
3957 if (num_socks == NUM_SOCKS)
3958 break;
3960 freeaddrinfo(aitop);
3961 if (num_socks > 0)
3962 break;
3964 if (display_number >= MAX_DISPLAYS) {
3965 error("Failed to allocate internet-domain X11 display socket.");
3966 return -1;
3968 /* Start listening for connections on the socket. */
3969 for (n = 0; n < num_socks; n++) {
3970 sock = socks[n];
3971 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3972 error("listen: %.100s", strerror(errno));
3973 close(sock);
3974 return -1;
3978 /* Allocate a channel for each socket. */
3979 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3980 for (n = 0; n < num_socks; n++) {
3981 sock = socks[n];
3982 nc = channel_new("x11 listener",
3983 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3984 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3985 0, "X11 inet listener", 1);
3986 nc->single_connection = single_connection;
3987 (*chanids)[n] = nc->self;
3989 (*chanids)[n] = -1;
3991 /* Return the display number for the DISPLAY environment variable. */
3992 *display_numberp = display_number;
3993 return (0);
3996 static int
3997 connect_local_xsocket_path(const char *pathname)
3999 int sock;
4000 struct sockaddr_un addr;
4002 sock = socket(AF_UNIX, SOCK_STREAM, 0);
4003 if (sock < 0)
4004 error("socket: %.100s", strerror(errno));
4005 memset(&addr, 0, sizeof(addr));
4006 addr.sun_family = AF_UNIX;
4007 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4008 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4009 return sock;
4010 close(sock);
4011 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4012 return -1;
4015 static int
4016 connect_local_xsocket(u_int dnr)
4018 char buf[1024];
4019 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4020 return connect_local_xsocket_path(buf);
4024 x11_connect_display(void)
4026 u_int display_number;
4027 const char *display;
4028 char buf[1024], *cp;
4029 struct addrinfo hints, *ai, *aitop;
4030 char strport[NI_MAXSERV];
4031 int gaierr, sock = 0;
4033 /* Try to open a socket for the local X server. */
4034 display = getenv("DISPLAY");
4035 if (!display) {
4036 error("DISPLAY not set.");
4037 return -1;
4040 * Now we decode the value of the DISPLAY variable and make a
4041 * connection to the real X server.
4044 /* Check if the display is from launchd. */
4045 #ifdef __APPLE__
4046 if (strncmp(display, "/tmp/launch", 11) == 0) {
4047 sock = connect_local_xsocket_path(display);
4048 if (sock < 0)
4049 return -1;
4051 /* OK, we now have a connection to the display. */
4052 return sock;
4054 #endif
4056 * Check if it is a unix domain socket. Unix domain displays are in
4057 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4059 if (strncmp(display, "unix:", 5) == 0 ||
4060 display[0] == ':') {
4061 /* Connect to the unix domain socket. */
4062 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
4063 error("Could not parse display number from DISPLAY: %.100s",
4064 display);
4065 return -1;
4067 /* Create a socket. */
4068 sock = connect_local_xsocket(display_number);
4069 if (sock < 0)
4070 return -1;
4072 /* OK, we now have a connection to the display. */
4073 return sock;
4076 * Connect to an inet socket. The DISPLAY value is supposedly
4077 * hostname:d[.s], where hostname may also be numeric IP address.
4079 strlcpy(buf, display, sizeof(buf));
4080 cp = strchr(buf, ':');
4081 if (!cp) {
4082 error("Could not find ':' in DISPLAY: %.100s", display);
4083 return -1;
4085 *cp = 0;
4086 /* buf now contains the host name. But first we parse the display number. */
4087 if (sscanf(cp + 1, "%u", &display_number) != 1) {
4088 error("Could not parse display number from DISPLAY: %.100s",
4089 display);
4090 return -1;
4093 /* Look up the host address */
4094 memset(&hints, 0, sizeof(hints));
4095 hints.ai_family = IPv4or6;
4096 hints.ai_socktype = SOCK_STREAM;
4097 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
4098 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
4099 error("%.100s: unknown host. (%s)", buf,
4100 ssh_gai_strerror(gaierr));
4101 return -1;
4103 for (ai = aitop; ai; ai = ai->ai_next) {
4104 /* Create a socket. */
4105 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
4106 if (sock < 0) {
4107 debug2("socket: %.100s", strerror(errno));
4108 continue;
4110 /* Connect it to the display. */
4111 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
4112 debug2("connect %.100s port %u: %.100s", buf,
4113 6000 + display_number, strerror(errno));
4114 close(sock);
4115 continue;
4117 /* Success */
4118 break;
4120 freeaddrinfo(aitop);
4121 if (!ai) {
4122 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
4123 strerror(errno));
4124 return -1;
4126 set_nodelay(sock);
4127 return sock;
4131 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
4132 * the remote channel number. We should do whatever we want, and respond
4133 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
4136 /* ARGSUSED */
4138 x11_input_open(int type, u_int32_t seq, void *ctxt)
4140 Channel *c = NULL;
4141 int remote_id, sock = 0;
4142 char *remote_host;
4144 debug("Received X11 open request.");
4146 remote_id = packet_get_int();
4148 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
4149 remote_host = packet_get_string(NULL);
4150 } else {
4151 remote_host = xstrdup("unknown (remote did not supply name)");
4153 packet_check_eom();
4155 /* Obtain a connection to the real X display. */
4156 sock = x11_connect_display();
4157 if (sock != -1) {
4158 /* Allocate a channel for this connection. */
4159 c = channel_new("connected x11 socket",
4160 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
4161 remote_host, 1);
4162 c->remote_id = remote_id;
4163 c->force_drain = 1;
4165 free(remote_host);
4166 if (c == NULL) {
4167 /* Send refusal to the remote host. */
4168 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
4169 packet_put_int(remote_id);
4170 } else {
4171 /* Send a confirmation to the remote host. */
4172 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
4173 packet_put_int(remote_id);
4174 packet_put_int(c->self);
4176 packet_send();
4177 return 0;
4180 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
4181 /* ARGSUSED */
4183 deny_input_open(int type, u_int32_t seq, void *ctxt)
4185 int rchan = packet_get_int();
4187 switch (type) {
4188 case SSH_SMSG_AGENT_OPEN:
4189 error("Warning: ssh server tried agent forwarding.");
4190 break;
4191 case SSH_SMSG_X11_OPEN:
4192 error("Warning: ssh server tried X11 forwarding.");
4193 break;
4194 default:
4195 error("deny_input_open: type %d", type);
4196 break;
4198 error("Warning: this is probably a break-in attempt by a malicious server.");
4199 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
4200 packet_put_int(rchan);
4201 packet_send();
4202 return 0;
4206 * Requests forwarding of X11 connections, generates fake authentication
4207 * data, and enables authentication spoofing.
4208 * This should be called in the client only.
4210 void
4211 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
4212 const char *proto, const char *data, int want_reply)
4214 u_int data_len = (u_int) strlen(data) / 2;
4215 u_int i, value;
4216 char *new_data;
4217 int screen_number;
4218 const char *cp;
4219 u_int32_t rnd = 0;
4221 if (x11_saved_display == NULL)
4222 x11_saved_display = xstrdup(disp);
4223 else if (strcmp(disp, x11_saved_display) != 0) {
4224 error("x11_request_forwarding_with_spoofing: different "
4225 "$DISPLAY already forwarded");
4226 return;
4229 cp = strchr(disp, ':');
4230 if (cp)
4231 cp = strchr(cp, '.');
4232 if (cp)
4233 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
4234 else
4235 screen_number = 0;
4237 if (x11_saved_proto == NULL) {
4238 /* Save protocol name. */
4239 x11_saved_proto = xstrdup(proto);
4241 * Extract real authentication data and generate fake data
4242 * of the same length.
4244 x11_saved_data = xmalloc(data_len);
4245 x11_fake_data = xmalloc(data_len);
4246 for (i = 0; i < data_len; i++) {
4247 if (sscanf(data + 2 * i, "%2x", &value) != 1)
4248 fatal("x11_request_forwarding: bad "
4249 "authentication data: %.100s", data);
4250 if (i % 4 == 0)
4251 rnd = arc4random();
4252 x11_saved_data[i] = value;
4253 x11_fake_data[i] = rnd & 0xff;
4254 rnd >>= 8;
4256 x11_saved_data_len = data_len;
4257 x11_fake_data_len = data_len;
4260 /* Convert the fake data into hex. */
4261 new_data = tohex(x11_fake_data, data_len);
4263 /* Send the request packet. */
4264 if (compat20) {
4265 channel_request_start(client_session_id, "x11-req", want_reply);
4266 packet_put_char(0); /* XXX bool single connection */
4267 } else {
4268 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
4270 packet_put_cstring(proto);
4271 packet_put_cstring(new_data);
4272 packet_put_int(screen_number);
4273 packet_send();
4274 packet_write_wait();
4275 free(new_data);
4279 /* -- agent forwarding */
4281 /* Sends a message to the server to request authentication fd forwarding. */
4283 void
4284 auth_request_forwarding(void)
4286 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
4287 packet_send();
4288 packet_write_wait();