]> andersk Git - gssapi-openssh.git/blame - openssh/channels.c
Merged hpn13v5 to trunk.
[gssapi-openssh.git] / openssh / channels.c
CommitLineData
5156b1a1 1/* $OpenBSD: channels.c,v 1.286 2008/07/16 11:52:19 djm Exp $ */
3c0ef626 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.
9 *
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".
15 *
16 * SSH2 support added by Markus Friedl.
473db5ab 17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
3c0ef626 18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
20 *
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.
29 *
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.
40 */
41
42#include "includes.h"
3c0ef626 43
30460aeb 44#include <sys/types.h>
45#include <sys/ioctl.h>
46#include <sys/un.h>
47#include <sys/socket.h>
48#ifdef HAVE_SYS_TIME_H
49# include <sys/time.h>
50#endif
51
52#include <netinet/in.h>
53#include <arpa/inet.h>
54
55#include <errno.h>
56#include <netdb.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <termios.h>
61#include <unistd.h>
62#include <stdarg.h>
63
5156b1a1 64#include "openbsd-compat/sys-queue.h"
30460aeb 65#include "xmalloc.h"
3c0ef626 66#include "ssh.h"
67#include "ssh1.h"
68#include "ssh2.h"
69#include "packet.h"
3c0ef626 70#include "log.h"
71#include "misc.h"
30460aeb 72#include "buffer.h"
3c0ef626 73#include "channels.h"
74#include "compat.h"
75#include "canohost.h"
76#include "key.h"
77#include "authfd.h"
473db5ab 78#include "pathnames.h"
a7213e65 79
3c0ef626 80/* -- channel core */
81
82/*
83 * Pointer to an array containing all allocated channels. The array is
84 * dynamically extended as needed.
85 */
86static Channel **channels = NULL;
87
88/*
89 * Size of the channel array. All slots of the array must always be
90 * initialized (at least the type field); unused slots set to NULL
91 */
473db5ab 92static u_int channels_alloc = 0;
3c0ef626 93
94/*
95 * Maximum file descriptor value used in any of the channels. This is
96 * updated in channel_new.
97 */
98static int channel_max_fd = 0;
99
100
101/* -- tcp forwarding */
102
103/*
104 * Data structure for storing which hosts are permitted for forward requests.
105 * The local sides of any remote forwards are stored in this array to prevent
106 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
107 * network (which might be behind a firewall).
108 */
109typedef struct {
110 char *host_to_connect; /* Connect to 'host'. */
111 u_short port_to_connect; /* Connect to 'port'. */
112 u_short listen_port; /* Remote side should listen port number. */
113} ForwardPermission;
114
30460aeb 115/* List of all permitted host/port pairs to connect by the user. */
3c0ef626 116static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
117
30460aeb 118/* List of all permitted host/port pairs to connect by the admin. */
119static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
120
121/* Number of permitted host/port pairs in the array permitted by the user. */
3c0ef626 122static int num_permitted_opens = 0;
30460aeb 123
124/* Number of permitted host/port pair in the array permitted by the admin. */
125static int num_adm_permitted_opens = 0;
126
3c0ef626 127/*
128 * If this is true, all opens are permitted. This is the case on the server
129 * on which we have to trust the client anyway, and the user could do
130 * anything after logging in anyway.
131 */
132static int all_opens_permitted = 0;
133
134
135/* -- X11 forwarding */
136
137/* Maximum number of fake X11 displays to try. */
138#define MAX_DISPLAYS 1000
139
473db5ab 140/* Saved X11 local (client) display. */
141static char *x11_saved_display = NULL;
142
3c0ef626 143/* Saved X11 authentication protocol name. */
144static char *x11_saved_proto = NULL;
145
146/* Saved X11 authentication data. This is the real data. */
147static char *x11_saved_data = NULL;
148static u_int x11_saved_data_len = 0;
149
150/*
151 * Fake X11 authentication data. This is what the server will be sending us;
152 * we should replace any occurrences of this by the real data.
153 */
30460aeb 154static u_char *x11_fake_data = NULL;
3c0ef626 155static u_int x11_fake_data_len;
156
157
158/* -- agent forwarding */
159
160#define NUM_SOCKS 10
161
3c0ef626 162/* AF_UNSPEC or AF_INET or AF_INET6 */
163static int IPv4or6 = AF_UNSPEC;
164
165/* helper */
166static void port_open_helper(Channel *c, char *rtype);
167
5156b1a1 168/* non-blocking connect helpers */
169static int connect_next(struct channel_connect *);
170static void channel_connect_ctx_free(struct channel_connect *);
171
d3057ca4 172
173static int hpn_disabled = 0;
174static int hpn_buffer_size = 2 * 1024 * 1024;
175
3c0ef626 176/* -- channel core */
177
d3057ca4 178
179
3c0ef626 180Channel *
08822d99 181channel_by_id(int id)
3c0ef626 182{
183 Channel *c;
184
473db5ab 185 if (id < 0 || (u_int)id >= channels_alloc) {
08822d99 186 logit("channel_by_id: %d: bad id", id);
3c0ef626 187 return NULL;
188 }
189 c = channels[id];
190 if (c == NULL) {
08822d99 191 logit("channel_by_id: %d: bad id: channel free", id);
3c0ef626 192 return NULL;
193 }
194 return c;
195}
196
08822d99 197/*
198 * Returns the channel if it is allowed to receive protocol messages.
199 * Private channels, like listening sockets, may not receive messages.
200 */
201Channel *
202channel_lookup(int id)
203{
204 Channel *c;
205
206 if ((c = channel_by_id(id)) == NULL)
207 return (NULL);
208
30460aeb 209 switch (c->type) {
08822d99 210 case SSH_CHANNEL_X11_OPEN:
211 case SSH_CHANNEL_LARVAL:
212 case SSH_CHANNEL_CONNECTING:
213 case SSH_CHANNEL_DYNAMIC:
214 case SSH_CHANNEL_OPENING:
215 case SSH_CHANNEL_OPEN:
216 case SSH_CHANNEL_INPUT_DRAINING:
217 case SSH_CHANNEL_OUTPUT_DRAINING:
218 return (c);
08822d99 219 }
220 logit("Non-public channel %d, type %d.", id, c->type);
221 return (NULL);
222}
223
3c0ef626 224/*
225 * Register filedescriptors for a channel, used when allocating a channel or
226 * when the channel consumer/producer is ready, e.g. shell exec'd
227 */
3c0ef626 228static void
229channel_register_fds(Channel *c, int rfd, int wfd, int efd,
5156b1a1 230 int extusage, int nonblock, int is_tty)
3c0ef626 231{
232 /* Update the maximum file descriptor value. */
233 channel_max_fd = MAX(channel_max_fd, rfd);
234 channel_max_fd = MAX(channel_max_fd, wfd);
235 channel_max_fd = MAX(channel_max_fd, efd);
236
237 /* XXX set close-on-exec -markus */
238
239 c->rfd = rfd;
240 c->wfd = wfd;
241 c->sock = (rfd == wfd) ? rfd : -1;
473db5ab 242 c->ctl_fd = -1; /* XXX: set elsewhere */
3c0ef626 243 c->efd = efd;
244 c->extended_usage = extusage;
245
5156b1a1 246 if ((c->isatty = is_tty) != 0)
473db5ab 247 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
5156b1a1 248 c->wfd_isatty = is_tty || isatty(c->wfd);
3c0ef626 249
250 /* enable nonblocking mode */
251 if (nonblock) {
252 if (rfd != -1)
253 set_nonblock(rfd);
254 if (wfd != -1)
255 set_nonblock(wfd);
256 if (efd != -1)
257 set_nonblock(efd);
258 }
259}
260
261/*
262 * Allocate a new channel object and set its type and socket. This will cause
263 * remote_name to be freed.
264 */
3c0ef626 265Channel *
266channel_new(char *ctype, int type, int rfd, int wfd, int efd,
473db5ab 267 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
3c0ef626 268{
473db5ab 269 int found;
270 u_int i;
3c0ef626 271 Channel *c;
272
273 /* Do initial allocation if this is the first call. */
274 if (channels_alloc == 0) {
3c0ef626 275 channels_alloc = 10;
30460aeb 276 channels = xcalloc(channels_alloc, sizeof(Channel *));
3c0ef626 277 for (i = 0; i < channels_alloc; i++)
278 channels[i] = NULL;
3c0ef626 279 }
280 /* Try to find a free slot where to put the new channel. */
281 for (found = -1, i = 0; i < channels_alloc; i++)
282 if (channels[i] == NULL) {
283 /* Found a free slot. */
473db5ab 284 found = (int)i;
3c0ef626 285 break;
286 }
473db5ab 287 if (found < 0) {
3c0ef626 288 /* There are no free slots. Take last+1 slot and expand the array. */
289 found = channels_alloc;
473db5ab 290 if (channels_alloc > 10000)
291 fatal("channel_new: internal error: channels_alloc %d "
292 "too big.", channels_alloc);
30460aeb 293 channels = xrealloc(channels, channels_alloc + 10,
294 sizeof(Channel *));
3c0ef626 295 channels_alloc += 10;
296 debug2("channel: expanding %d", channels_alloc);
3c0ef626 297 for (i = found; i < channels_alloc; i++)
298 channels[i] = NULL;
299 }
300 /* Initialize and return new channel. */
30460aeb 301 c = channels[found] = xcalloc(1, sizeof(Channel));
3c0ef626 302 buffer_init(&c->input);
303 buffer_init(&c->output);
304 buffer_init(&c->extended);
473db5ab 305 c->ostate = CHAN_OUTPUT_OPEN;
306 c->istate = CHAN_INPUT_OPEN;
307 c->flags = 0;
5156b1a1 308 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
3c0ef626 309 c->self = found;
310 c->type = type;
311 c->ctype = ctype;
312 c->local_window = window;
313 c->local_window_max = window;
314 c->local_consumed = 0;
315 c->local_maxpacket = maxpack;
473db5ab 316 c->dynamic_window = 0;
3c0ef626 317 c->remote_id = -1;
473db5ab 318 c->remote_name = xstrdup(remote_name);
3c0ef626 319 c->remote_window = 0;
320 c->remote_maxpacket = 0;
3c0ef626 321 c->force_drain = 0;
473db5ab 322 c->single_connection = 0;
3c0ef626 323 c->detach_user = NULL;
08822d99 324 c->detach_close = 0;
5156b1a1 325 c->open_confirm = NULL;
326 c->open_confirm_ctx = NULL;
3c0ef626 327 c->input_filter = NULL;
08822d99 328 c->output_filter = NULL;
5156b1a1 329 c->filter_ctx = NULL;
330 c->filter_cleanup = NULL;
331 TAILQ_INIT(&c->status_confirms);
3c0ef626 332 debug("channel %d: new [%s]", found, remote_name);
333 return c;
334}
335
336static int
337channel_find_maxfd(void)
338{
473db5ab 339 u_int i;
340 int max = 0;
3c0ef626 341 Channel *c;
342
343 for (i = 0; i < channels_alloc; i++) {
344 c = channels[i];
345 if (c != NULL) {
346 max = MAX(max, c->rfd);
347 max = MAX(max, c->wfd);
348 max = MAX(max, c->efd);
349 }
350 }
351 return max;
352}
353
354int
355channel_close_fd(int *fdp)
356{
357 int ret = 0, fd = *fdp;
358
359 if (fd != -1) {
360 ret = close(fd);
361 *fdp = -1;
362 if (fd == channel_max_fd)
363 channel_max_fd = channel_find_maxfd();
364 }
365 return ret;
366}
367
368/* Close all channel fd/socket. */
3c0ef626 369static void
370channel_close_fds(Channel *c)
371{
473db5ab 372 debug3("channel %d: close_fds r %d w %d e %d c %d",
373 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
3c0ef626 374
375 channel_close_fd(&c->sock);
473db5ab 376 channel_close_fd(&c->ctl_fd);
3c0ef626 377 channel_close_fd(&c->rfd);
378 channel_close_fd(&c->wfd);
379 channel_close_fd(&c->efd);
380}
381
382/* Free the channel and close its fd/socket. */
3c0ef626 383void
384channel_free(Channel *c)
385{
386 char *s;
473db5ab 387 u_int i, n;
5156b1a1 388 struct channel_confirm *cc;
3c0ef626 389
390 for (n = 0, i = 0; i < channels_alloc; i++)
391 if (channels[i])
392 n++;
473db5ab 393 debug("channel %d: free: %s, nchannels %u", c->self,
3c0ef626 394 c->remote_name ? c->remote_name : "???", n);
395
396 s = channel_open_message();
473db5ab 397 debug3("channel %d: status: %s", c->self, s);
3c0ef626 398 xfree(s);
399
400 if (c->sock != -1)
401 shutdown(c->sock, SHUT_RDWR);
473db5ab 402 if (c->ctl_fd != -1)
403 shutdown(c->ctl_fd, SHUT_RDWR);
3c0ef626 404 channel_close_fds(c);
405 buffer_free(&c->input);
406 buffer_free(&c->output);
407 buffer_free(&c->extended);
408 if (c->remote_name) {
409 xfree(c->remote_name);
410 c->remote_name = NULL;
411 }
5156b1a1 412 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
413 if (cc->abandon_cb != NULL)
414 cc->abandon_cb(c, cc->ctx);
415 TAILQ_REMOVE(&c->status_confirms, cc, entry);
416 bzero(cc, sizeof(*cc));
417 xfree(cc);
418 }
419 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
420 c->filter_cleanup(c->self, c->filter_ctx);
3c0ef626 421 channels[c->self] = NULL;
422 xfree(c);
423}
424
425void
426channel_free_all(void)
427{
473db5ab 428 u_int i;
3c0ef626 429
430 for (i = 0; i < channels_alloc; i++)
431 if (channels[i] != NULL)
432 channel_free(channels[i]);
433}
434
435/*
436 * Closes the sockets/fds of all channels. This is used to close extra file
437 * descriptors after a fork.
438 */
3c0ef626 439void
473db5ab 440channel_close_all(void)
3c0ef626 441{
473db5ab 442 u_int i;
3c0ef626 443
444 for (i = 0; i < channels_alloc; i++)
445 if (channels[i] != NULL)
446 channel_close_fds(channels[i]);
447}
448
449/*
450 * Stop listening to channels.
451 */
3c0ef626 452void
453channel_stop_listening(void)
454{
473db5ab 455 u_int i;
3c0ef626 456 Channel *c;
457
458 for (i = 0; i < channels_alloc; i++) {
459 c = channels[i];
460 if (c != NULL) {
461 switch (c->type) {
462 case SSH_CHANNEL_AUTH_SOCKET:
463 case SSH_CHANNEL_PORT_LISTENER:
464 case SSH_CHANNEL_RPORT_LISTENER:
465 case SSH_CHANNEL_X11_LISTENER:
466 channel_close_fd(&c->sock);
467 channel_free(c);
468 break;
469 }
470 }
471 }
472}
473
474/*
475 * Returns true if no channel has too much buffered data, and false if one or
476 * more channel is overfull.
477 */
3c0ef626 478int
473db5ab 479channel_not_very_much_buffered_data(void)
3c0ef626 480{
481 u_int i;
482 Channel *c;
483
484 for (i = 0; i < channels_alloc; i++) {
485 c = channels[i];
486 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
487#if 0
488 if (!compat20 &&
489 buffer_len(&c->input) > packet_get_maxsize()) {
473db5ab 490 debug2("channel %d: big input buffer %d",
3c0ef626 491 c->self, buffer_len(&c->input));
492 return 0;
493 }
494#endif
495 if (buffer_len(&c->output) > packet_get_maxsize()) {
473db5ab 496 debug2("channel %d: big output buffer %u > %u",
3c0ef626 497 c->self, buffer_len(&c->output),
498 packet_get_maxsize());
499 return 0;
500 }
501 }
502 }
503 return 1;
504}
505
506/* Returns true if any channel is still open. */
3c0ef626 507int
473db5ab 508channel_still_open(void)
3c0ef626 509{
473db5ab 510 u_int i;
3c0ef626 511 Channel *c;
512
513 for (i = 0; i < channels_alloc; i++) {
514 c = channels[i];
515 if (c == NULL)
516 continue;
517 switch (c->type) {
518 case SSH_CHANNEL_X11_LISTENER:
519 case SSH_CHANNEL_PORT_LISTENER:
520 case SSH_CHANNEL_RPORT_LISTENER:
521 case SSH_CHANNEL_CLOSED:
522 case SSH_CHANNEL_AUTH_SOCKET:
523 case SSH_CHANNEL_DYNAMIC:
524 case SSH_CHANNEL_CONNECTING:
525 case SSH_CHANNEL_ZOMBIE:
526 continue;
527 case SSH_CHANNEL_LARVAL:
528 if (!compat20)
529 fatal("cannot happen: SSH_CHANNEL_LARVAL");
530 continue;
531 case SSH_CHANNEL_OPENING:
532 case SSH_CHANNEL_OPEN:
533 case SSH_CHANNEL_X11_OPEN:
534 return 1;
535 case SSH_CHANNEL_INPUT_DRAINING:
536 case SSH_CHANNEL_OUTPUT_DRAINING:
537 if (!compat13)
538 fatal("cannot happen: OUT_DRAIN");
539 return 1;
540 default:
541 fatal("channel_still_open: bad channel type %d", c->type);
542 /* NOTREACHED */
543 }
544 }
545 return 0;
546}
547
548/* Returns the id of an open channel suitable for keepaliving */
3c0ef626 549int
473db5ab 550channel_find_open(void)
3c0ef626 551{
473db5ab 552 u_int i;
3c0ef626 553 Channel *c;
554
555 for (i = 0; i < channels_alloc; i++) {
556 c = channels[i];
473db5ab 557 if (c == NULL || c->remote_id < 0)
3c0ef626 558 continue;
559 switch (c->type) {
560 case SSH_CHANNEL_CLOSED:
561 case SSH_CHANNEL_DYNAMIC:
562 case SSH_CHANNEL_X11_LISTENER:
563 case SSH_CHANNEL_PORT_LISTENER:
564 case SSH_CHANNEL_RPORT_LISTENER:
565 case SSH_CHANNEL_OPENING:
566 case SSH_CHANNEL_CONNECTING:
567 case SSH_CHANNEL_ZOMBIE:
568 continue;
569 case SSH_CHANNEL_LARVAL:
570 case SSH_CHANNEL_AUTH_SOCKET:
571 case SSH_CHANNEL_OPEN:
572 case SSH_CHANNEL_X11_OPEN:
573 return i;
574 case SSH_CHANNEL_INPUT_DRAINING:
575 case SSH_CHANNEL_OUTPUT_DRAINING:
576 if (!compat13)
577 fatal("cannot happen: OUT_DRAIN");
578 return i;
579 default:
580 fatal("channel_find_open: bad channel type %d", c->type);
581 /* NOTREACHED */
582 }
583 }
584 return -1;
585}
586
587
588/*
589 * Returns a message describing the currently open forwarded connections,
590 * suitable for sending to the client. The message contains crlf pairs for
591 * newlines.
592 */
3c0ef626 593char *
473db5ab 594channel_open_message(void)
3c0ef626 595{
596 Buffer buffer;
597 Channel *c;
598 char buf[1024], *cp;
473db5ab 599 u_int i;
3c0ef626 600
601 buffer_init(&buffer);
602 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
603 buffer_append(&buffer, buf, strlen(buf));
604 for (i = 0; i < channels_alloc; i++) {
605 c = channels[i];
606 if (c == NULL)
607 continue;
608 switch (c->type) {
609 case SSH_CHANNEL_X11_LISTENER:
610 case SSH_CHANNEL_PORT_LISTENER:
611 case SSH_CHANNEL_RPORT_LISTENER:
612 case SSH_CHANNEL_CLOSED:
613 case SSH_CHANNEL_AUTH_SOCKET:
614 case SSH_CHANNEL_ZOMBIE:
615 continue;
616 case SSH_CHANNEL_LARVAL:
617 case SSH_CHANNEL_OPENING:
618 case SSH_CHANNEL_CONNECTING:
619 case SSH_CHANNEL_DYNAMIC:
620 case SSH_CHANNEL_OPEN:
621 case SSH_CHANNEL_X11_OPEN:
622 case SSH_CHANNEL_INPUT_DRAINING:
623 case SSH_CHANNEL_OUTPUT_DRAINING:
473db5ab 624 snprintf(buf, sizeof buf,
625 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
3c0ef626 626 c->self, c->remote_name,
627 c->type, c->remote_id,
628 c->istate, buffer_len(&c->input),
629 c->ostate, buffer_len(&c->output),
473db5ab 630 c->rfd, c->wfd, c->ctl_fd);
3c0ef626 631 buffer_append(&buffer, buf, strlen(buf));
632 continue;
633 default:
634 fatal("channel_open_message: bad channel type %d", c->type);
635 /* NOTREACHED */
636 }
637 }
638 buffer_append(&buffer, "\0", 1);
639 cp = xstrdup(buffer_ptr(&buffer));
640 buffer_free(&buffer);
641 return cp;
642}
643
644void
645channel_send_open(int id)
646{
647 Channel *c = channel_lookup(id);
473db5ab 648
3c0ef626 649 if (c == NULL) {
473db5ab 650 logit("channel_send_open: %d: bad id", id);
3c0ef626 651 return;
652 }
473db5ab 653 debug2("channel %d: send open", id);
3c0ef626 654 packet_start(SSH2_MSG_CHANNEL_OPEN);
655 packet_put_cstring(c->ctype);
656 packet_put_int(c->self);
657 packet_put_int(c->local_window);
658 packet_put_int(c->local_maxpacket);
659 packet_send();
660}
661
3c0ef626 662void
663channel_request_start(int id, char *service, int wantconfirm)
664{
665 Channel *c = channel_lookup(id);
473db5ab 666
3c0ef626 667 if (c == NULL) {
473db5ab 668 logit("channel_request_start: %d: unknown channel id", id);
3c0ef626 669 return;
670 }
473db5ab 671 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
3c0ef626 672 packet_start(SSH2_MSG_CHANNEL_REQUEST);
673 packet_put_int(c->remote_id);
674 packet_put_cstring(service);
675 packet_put_char(wantconfirm);
676}
30460aeb 677
3c0ef626 678void
5156b1a1 679channel_register_status_confirm(int id, channel_confirm_cb *cb,
680 channel_confirm_abandon_cb *abandon_cb, void *ctx)
681{
682 struct channel_confirm *cc;
683 Channel *c;
684
685 if ((c = channel_lookup(id)) == NULL)
686 fatal("channel_register_expect: %d: bad id", id);
687
688 cc = xmalloc(sizeof(*cc));
689 cc->cb = cb;
690 cc->abandon_cb = abandon_cb;
691 cc->ctx = ctx;
692 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
693}
694
695void
696channel_register_open_confirm(int id, channel_callback_fn *fn, void *ctx)
3c0ef626 697{
698 Channel *c = channel_lookup(id);
473db5ab 699
3c0ef626 700 if (c == NULL) {
5156b1a1 701 logit("channel_register_open_comfirm: %d: bad id", id);
3c0ef626 702 return;
703 }
5156b1a1 704 c->open_confirm = fn;
705 c->open_confirm_ctx = ctx;
3c0ef626 706}
30460aeb 707
3c0ef626 708void
08822d99 709channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
3c0ef626 710{
08822d99 711 Channel *c = channel_by_id(id);
473db5ab 712
3c0ef626 713 if (c == NULL) {
473db5ab 714 logit("channel_register_cleanup: %d: bad id", id);
3c0ef626 715 return;
716 }
717 c->detach_user = fn;
08822d99 718 c->detach_close = do_close;
3c0ef626 719}
30460aeb 720
3c0ef626 721void
722channel_cancel_cleanup(int id)
723{
08822d99 724 Channel *c = channel_by_id(id);
473db5ab 725
3c0ef626 726 if (c == NULL) {
473db5ab 727 logit("channel_cancel_cleanup: %d: bad id", id);
3c0ef626 728 return;
729 }
730 c->detach_user = NULL;
08822d99 731 c->detach_close = 0;
3c0ef626 732}
30460aeb 733
3c0ef626 734void
08822d99 735channel_register_filter(int id, channel_infilter_fn *ifn,
5156b1a1 736 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
3c0ef626 737{
738 Channel *c = channel_lookup(id);
473db5ab 739
3c0ef626 740 if (c == NULL) {
473db5ab 741 logit("channel_register_filter: %d: bad id", id);
3c0ef626 742 return;
743 }
08822d99 744 c->input_filter = ifn;
745 c->output_filter = ofn;
5156b1a1 746 c->filter_ctx = ctx;
747 c->filter_cleanup = cfn;
3c0ef626 748}
749
750void
751channel_set_fds(int id, int rfd, int wfd, int efd,
5156b1a1 752 int extusage, int nonblock, int is_tty, u_int window_max)
3c0ef626 753{
754 Channel *c = channel_lookup(id);
473db5ab 755
3c0ef626 756 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
757 fatal("channel_activate for non-larval channel %d.", id);
5156b1a1 758 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
3c0ef626 759 c->type = SSH_CHANNEL_OPEN;
473db5ab 760 c->local_window = c->local_window_max = window_max;
3c0ef626 761 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
762 packet_put_int(c->remote_id);
763 packet_put_int(c->local_window);
764 packet_send();
765}
766
767/*
768 * 'channel_pre*' are called just before select() to add any bits relevant to
769 * channels in the select bitmasks.
770 */
771/*
772 * 'channel_post*': perform any appropriate operations for channels which
773 * have events pending.
774 */
30460aeb 775typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
3c0ef626 776chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
777chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
778
30460aeb 779/* ARGSUSED */
3c0ef626 780static void
30460aeb 781channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 782{
783 FD_SET(c->sock, readset);
784}
785
30460aeb 786/* ARGSUSED */
3c0ef626 787static void
30460aeb 788channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 789{
790 debug3("channel %d: waiting for connection", c->self);
791 FD_SET(c->sock, writeset);
792}
793
794static void
30460aeb 795channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 796{
797 if (buffer_len(&c->input) < packet_get_maxsize())
798 FD_SET(c->sock, readset);
799 if (buffer_len(&c->output) > 0)
800 FD_SET(c->sock, writeset);
801}
802
f713db99 803int channel_tcpwinsz () {
804 u_int32_t tcpwinsz = 0;
805 socklen_t optsz = sizeof(tcpwinsz);
806 int ret = -1;
6df46d40 807
808 /* if we aren't on a socket return 128KB*/
f713db99 809 if(!packet_connection_is_on_socket())
6df46d40 810 return(128*1024);
f713db99 811 ret = getsockopt(packet_get_connection_in(),
812 SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
6df46d40 813 /* return no more than 64MB */
f713db99 814 if ((ret == 0) && tcpwinsz > BUFFER_MAX_LEN_HPN)
815 tcpwinsz = BUFFER_MAX_LEN_HPN;
816 debug2("tcpwinsz: %d for connection: %d", tcpwinsz,
817 packet_get_connection_in());
818 return(tcpwinsz);
819}
820
3c0ef626 821static void
30460aeb 822channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 823{
473db5ab 824 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
f472818d 825
f713db99 826 /* check buffer limits */
6df46d40 827 if ((!c->tcpwinsz) || (c->dynamic_window > 0))
f713db99 828 c->tcpwinsz = channel_tcpwinsz();
f713db99 829
830 limit = MIN(limit, 2 * c->tcpwinsz);
831
3c0ef626 832 if (c->istate == CHAN_INPUT_OPEN &&
473db5ab 833 limit > 0 &&
30460aeb 834 buffer_len(&c->input) < limit &&
835 buffer_check_alloc(&c->input, CHAN_RBUF))
3c0ef626 836 FD_SET(c->rfd, readset);
837 if (c->ostate == CHAN_OUTPUT_OPEN ||
838 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
839 if (buffer_len(&c->output) > 0) {
840 FD_SET(c->wfd, writeset);
841 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
473db5ab 842 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
843 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
844 c->self, c->efd, buffer_len(&c->extended));
845 else
846 chan_obuf_empty(c);
3c0ef626 847 }
848 }
849 /** XXX check close conditions, too */
5156b1a1 850 if (compat20 && c->efd != -1 &&
851 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
3c0ef626 852 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
853 buffer_len(&c->extended) > 0)
854 FD_SET(c->efd, writeset);
473db5ab 855 else if (!(c->flags & CHAN_EOF_SENT) &&
856 c->extended_usage == CHAN_EXTENDED_READ &&
3c0ef626 857 buffer_len(&c->extended) < c->remote_window)
858 FD_SET(c->efd, readset);
859 }
473db5ab 860 /* XXX: What about efd? races? */
861 if (compat20 && c->ctl_fd != -1 &&
862 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
863 FD_SET(c->ctl_fd, readset);
3c0ef626 864}
865
30460aeb 866/* ARGSUSED */
3c0ef626 867static void
30460aeb 868channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 869{
870 if (buffer_len(&c->input) == 0) {
871 packet_start(SSH_MSG_CHANNEL_CLOSE);
872 packet_put_int(c->remote_id);
873 packet_send();
874 c->type = SSH_CHANNEL_CLOSED;
473db5ab 875 debug2("channel %d: closing after input drain.", c->self);
3c0ef626 876 }
877}
878
30460aeb 879/* ARGSUSED */
3c0ef626 880static void
30460aeb 881channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 882{
883 if (buffer_len(&c->output) == 0)
884 chan_mark_dead(c);
885 else
886 FD_SET(c->sock, writeset);
887}
888
889/*
890 * This is a special state for X11 authentication spoofing. An opened X11
891 * connection (when authentication spoofing is being done) remains in this
892 * state until the first packet has been completely read. The authentication
893 * data in that packet is then substituted by the real data if it matches the
894 * fake data, and the channel is put into normal mode.
895 * XXX All this happens at the client side.
896 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
897 */
898static int
899x11_open_helper(Buffer *b)
900{
901 u_char *ucp;
902 u_int proto_len, data_len;
903
904 /* Check if the fixed size part of the packet is in buffer. */
905 if (buffer_len(b) < 12)
906 return 0;
907
908 /* Parse the lengths of variable-length fields. */
473db5ab 909 ucp = buffer_ptr(b);
3c0ef626 910 if (ucp[0] == 0x42) { /* Byte order MSB first. */
911 proto_len = 256 * ucp[6] + ucp[7];
912 data_len = 256 * ucp[8] + ucp[9];
913 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
914 proto_len = ucp[6] + 256 * ucp[7];
915 data_len = ucp[8] + 256 * ucp[9];
916 } else {
473db5ab 917 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
918 ucp[0]);
3c0ef626 919 return -1;
920 }
921
922 /* Check if the whole packet is in buffer. */
923 if (buffer_len(b) <
924 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
925 return 0;
926
927 /* Check if authentication protocol matches. */
928 if (proto_len != strlen(x11_saved_proto) ||
929 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
473db5ab 930 debug2("X11 connection uses different authentication protocol.");
3c0ef626 931 return -1;
932 }
933 /* Check if authentication data matches our fake data. */
934 if (data_len != x11_fake_data_len ||
935 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
936 x11_fake_data, x11_fake_data_len) != 0) {
473db5ab 937 debug2("X11 auth data does not match fake data.");
3c0ef626 938 return -1;
939 }
940 /* Check fake data length */
941 if (x11_fake_data_len != x11_saved_data_len) {
942 error("X11 fake_data_len %d != saved_data_len %d",
943 x11_fake_data_len, x11_saved_data_len);
944 return -1;
945 }
946 /*
947 * Received authentication protocol and data match
948 * our fake data. Substitute the fake data with real
949 * data.
950 */
951 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
952 x11_saved_data, x11_saved_data_len);
953 return 1;
954}
955
956static void
30460aeb 957channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 958{
959 int ret = x11_open_helper(&c->output);
473db5ab 960
3c0ef626 961 if (ret == 1) {
962 /* Start normal processing for the channel. */
963 c->type = SSH_CHANNEL_OPEN;
964 channel_pre_open_13(c, readset, writeset);
965 } else if (ret == -1) {
966 /*
967 * We have received an X11 connection that has bad
968 * authentication information.
969 */
473db5ab 970 logit("X11 connection rejected because of wrong authentication.");
3c0ef626 971 buffer_clear(&c->input);
972 buffer_clear(&c->output);
973 channel_close_fd(&c->sock);
974 c->sock = -1;
975 c->type = SSH_CHANNEL_CLOSED;
976 packet_start(SSH_MSG_CHANNEL_CLOSE);
977 packet_put_int(c->remote_id);
978 packet_send();
979 }
980}
981
982static void
30460aeb 983channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 984{
985 int ret = x11_open_helper(&c->output);
986
987 /* c->force_drain = 1; */
988
989 if (ret == 1) {
990 c->type = SSH_CHANNEL_OPEN;
473db5ab 991 channel_pre_open(c, readset, writeset);
992 } else if (ret == -1) {
993 logit("X11 connection rejected because of wrong authentication.");
994 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
995 chan_read_failed(c);
996 buffer_clear(&c->input);
997 chan_ibuf_empty(c);
998 buffer_clear(&c->output);
999 /* for proto v1, the peer will send an IEOF */
3c0ef626 1000 if (compat20)
473db5ab 1001 chan_write_failed(c);
3c0ef626 1002 else
473db5ab 1003 c->type = SSH_CHANNEL_OPEN;
1004 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
3c0ef626 1005 }
1006}
1007
1008/* try to decode a socks4 header */
30460aeb 1009/* ARGSUSED */
3c0ef626 1010static int
30460aeb 1011channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1012{
473db5ab 1013 char *p, *host;
1014 u_int len, have, i, found;
1015 char username[256];
3c0ef626 1016 struct {
1017 u_int8_t version;
1018 u_int8_t command;
1019 u_int16_t dest_port;
1020 struct in_addr dest_addr;
1021 } s4_req, s4_rsp;
1022
1023 debug2("channel %d: decode socks4", c->self);
1024
1025 have = buffer_len(&c->input);
1026 len = sizeof(s4_req);
1027 if (have < len)
1028 return 0;
1029 p = buffer_ptr(&c->input);
1030 for (found = 0, i = len; i < have; i++) {
1031 if (p[i] == '\0') {
1032 found = 1;
1033 break;
1034 }
1035 if (i > 1024) {
1036 /* the peer is probably sending garbage */
1037 debug("channel %d: decode socks4: too long",
1038 c->self);
1039 return -1;
1040 }
1041 }
1042 if (!found)
1043 return 0;
1044 buffer_get(&c->input, (char *)&s4_req.version, 1);
1045 buffer_get(&c->input, (char *)&s4_req.command, 1);
1046 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1047 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1048 have = buffer_len(&c->input);
1049 p = buffer_ptr(&c->input);
1050 len = strlen(p);
1051 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1052 if (len > have)
1053 fatal("channel %d: decode socks4: len %d > have %d",
1054 c->self, len, have);
1055 strlcpy(username, p, sizeof(username));
1056 buffer_consume(&c->input, len);
1057 buffer_consume(&c->input, 1); /* trailing '\0' */
1058
1059 host = inet_ntoa(s4_req.dest_addr);
1060 strlcpy(c->path, host, sizeof(c->path));
1061 c->host_port = ntohs(s4_req.dest_port);
473db5ab 1062
1063 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
3c0ef626 1064 c->self, host, c->host_port, s4_req.command);
1065
1066 if (s4_req.command != 1) {
1067 debug("channel %d: cannot handle: socks4 cn %d",
1068 c->self, s4_req.command);
1069 return -1;
1070 }
1071 s4_rsp.version = 0; /* vn: 0 for reply */
1072 s4_rsp.command = 90; /* cd: req granted */
1073 s4_rsp.dest_port = 0; /* ignored */
1074 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
30460aeb 1075 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
3c0ef626 1076 return 1;
1077}
1078
473db5ab 1079/* try to decode a socks5 header */
1080#define SSH_SOCKS5_AUTHDONE 0x1000
1081#define SSH_SOCKS5_NOAUTH 0x00
1082#define SSH_SOCKS5_IPV4 0x01
1083#define SSH_SOCKS5_DOMAIN 0x03
1084#define SSH_SOCKS5_IPV6 0x04
1085#define SSH_SOCKS5_CONNECT 0x01
1086#define SSH_SOCKS5_SUCCESS 0x00
1087
30460aeb 1088/* ARGSUSED */
473db5ab 1089static int
30460aeb 1090channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
473db5ab 1091{
1092 struct {
1093 u_int8_t version;
1094 u_int8_t command;
1095 u_int8_t reserved;
1096 u_int8_t atyp;
1097 } s5_req, s5_rsp;
1098 u_int16_t dest_port;
1099 u_char *p, dest_addr[255+1];
30460aeb 1100 u_int have, need, i, found, nmethods, addrlen, af;
473db5ab 1101
1102 debug2("channel %d: decode socks5", c->self);
1103 p = buffer_ptr(&c->input);
1104 if (p[0] != 0x05)
1105 return -1;
1106 have = buffer_len(&c->input);
1107 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1108 /* format: ver | nmethods | methods */
1109 if (have < 2)
1110 return 0;
1111 nmethods = p[1];
1112 if (have < nmethods + 2)
1113 return 0;
1114 /* look for method: "NO AUTHENTICATION REQUIRED" */
0b90ac93 1115 for (found = 0, i = 2; i < nmethods + 2; i++) {
30460aeb 1116 if (p[i] == SSH_SOCKS5_NOAUTH) {
473db5ab 1117 found = 1;
1118 break;
1119 }
1120 }
1121 if (!found) {
1122 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1123 c->self);
1124 return -1;
1125 }
1126 buffer_consume(&c->input, nmethods + 2);
1127 buffer_put_char(&c->output, 0x05); /* version */
1128 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1129 FD_SET(c->sock, writeset);
1130 c->flags |= SSH_SOCKS5_AUTHDONE;
1131 debug2("channel %d: socks5 auth done", c->self);
1132 return 0; /* need more */
1133 }
1134 debug2("channel %d: socks5 post auth", c->self);
1135 if (have < sizeof(s5_req)+1)
1136 return 0; /* need more */
30460aeb 1137 memcpy(&s5_req, p, sizeof(s5_req));
473db5ab 1138 if (s5_req.version != 0x05 ||
1139 s5_req.command != SSH_SOCKS5_CONNECT ||
1140 s5_req.reserved != 0x00) {
1141 debug2("channel %d: only socks5 connect supported", c->self);
1142 return -1;
1143 }
1144 switch (s5_req.atyp){
1145 case SSH_SOCKS5_IPV4:
1146 addrlen = 4;
1147 af = AF_INET;
1148 break;
1149 case SSH_SOCKS5_DOMAIN:
1150 addrlen = p[sizeof(s5_req)];
1151 af = -1;
1152 break;
1153 case SSH_SOCKS5_IPV6:
1154 addrlen = 16;
1155 af = AF_INET6;
1156 break;
1157 default:
1158 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1159 return -1;
1160 }
30460aeb 1161 need = sizeof(s5_req) + addrlen + 2;
1162 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1163 need++;
1164 if (have < need)
473db5ab 1165 return 0;
1166 buffer_consume(&c->input, sizeof(s5_req));
1167 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1168 buffer_consume(&c->input, 1); /* host string length */
1169 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1170 buffer_get(&c->input, (char *)&dest_port, 2);
1171 dest_addr[addrlen] = '\0';
1172 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1173 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1174 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1175 return -1;
1176 c->host_port = ntohs(dest_port);
1177
1178 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1179 c->self, c->path, c->host_port, s5_req.command);
1180
1181 s5_rsp.version = 0x05;
1182 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1183 s5_rsp.reserved = 0; /* ignored */
1184 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1185 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1186 dest_port = 0; /* ignored */
1187
30460aeb 1188 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1189 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1190 buffer_append(&c->output, &dest_port, sizeof(dest_port));
473db5ab 1191 return 1;
1192}
1193
3c0ef626 1194/* dynamic port forwarding */
1195static void
30460aeb 1196channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1197{
1198 u_char *p;
473db5ab 1199 u_int have;
1200 int ret;
3c0ef626 1201
1202 have = buffer_len(&c->input);
1203 c->delayed = 0;
1204 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1205 /* buffer_dump(&c->input); */
1206 /* check if the fixed size part of the packet is in buffer. */
473db5ab 1207 if (have < 3) {
3c0ef626 1208 /* need more */
1209 FD_SET(c->sock, readset);
1210 return;
1211 }
1212 /* try to guess the protocol */
1213 p = buffer_ptr(&c->input);
1214 switch (p[0]) {
1215 case 0x04:
1216 ret = channel_decode_socks4(c, readset, writeset);
1217 break;
473db5ab 1218 case 0x05:
1219 ret = channel_decode_socks5(c, readset, writeset);
1220 break;
3c0ef626 1221 default:
1222 ret = -1;
1223 break;
1224 }
1225 if (ret < 0) {
1226 chan_mark_dead(c);
1227 } else if (ret == 0) {
1228 debug2("channel %d: pre_dynamic: need more", c->self);
1229 /* need more */
1230 FD_SET(c->sock, readset);
1231 } else {
1232 /* switch to the next state */
1233 c->type = SSH_CHANNEL_OPENING;
1234 port_open_helper(c, "direct-tcpip");
1235 }
1236}
1237
1238/* This is our fake X11 server socket. */
30460aeb 1239/* ARGSUSED */
3c0ef626 1240static void
30460aeb 1241channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1242{
1243 Channel *nc;
5156b1a1 1244 struct sockaddr_storage addr;
3c0ef626 1245 int newsock;
1246 socklen_t addrlen;
1247 char buf[16384], *remote_ipaddr;
1248 int remote_port;
1249
1250 if (FD_ISSET(c->sock, readset)) {
1251 debug("X11 connection requested.");
1252 addrlen = sizeof(addr);
5156b1a1 1253 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
473db5ab 1254 if (c->single_connection) {
1255 debug2("single_connection: closing X11 listener.");
1256 channel_close_fd(&c->sock);
1257 chan_mark_dead(c);
1258 }
3c0ef626 1259 if (newsock < 0) {
1260 error("accept: %.100s", strerror(errno));
1261 return;
1262 }
473db5ab 1263 set_nodelay(newsock);
3c0ef626 1264 remote_ipaddr = get_peer_ipaddr(newsock);
1265 remote_port = get_peer_port(newsock);
1266 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1267 remote_ipaddr, remote_port);
1268
1269 nc = channel_new("accepted x11 socket",
1270 SSH_CHANNEL_OPENING, newsock, newsock, -1,
473db5ab 1271 c->local_window_max, c->local_maxpacket, 0, buf, 1);
3c0ef626 1272 if (compat20) {
1273 packet_start(SSH2_MSG_CHANNEL_OPEN);
1274 packet_put_cstring("x11");
1275 packet_put_int(nc->self);
473db5ab 1276 packet_put_int(nc->local_window_max);
1277 packet_put_int(nc->local_maxpacket);
3c0ef626 1278 /* originator ipaddr and port */
1279 packet_put_cstring(remote_ipaddr);
1280 if (datafellows & SSH_BUG_X11FWD) {
473db5ab 1281 debug2("ssh2 x11 bug compat mode");
3c0ef626 1282 } else {
1283 packet_put_int(remote_port);
1284 }
1285 packet_send();
1286 } else {
1287 packet_start(SSH_SMSG_X11_OPEN);
1288 packet_put_int(nc->self);
1289 if (packet_get_protocol_flags() &
1290 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1291 packet_put_cstring(buf);
1292 packet_send();
1293 }
1294 xfree(remote_ipaddr);
1295 }
1296}
1297
1298static void
1299port_open_helper(Channel *c, char *rtype)
1300{
1301 int direct;
1302 char buf[1024];
1303 char *remote_ipaddr = get_peer_ipaddr(c->sock);
473db5ab 1304 int remote_port = get_peer_port(c->sock);
3c0ef626 1305
1306 direct = (strcmp(rtype, "direct-tcpip") == 0);
1307
1308 snprintf(buf, sizeof buf,
1309 "%s: listening port %d for %.100s port %d, "
1310 "connect from %.200s port %d",
1311 rtype, c->listening_port, c->path, c->host_port,
1312 remote_ipaddr, remote_port);
1313
1314 xfree(c->remote_name);
1315 c->remote_name = xstrdup(buf);
1316
1317 if (compat20) {
1318 packet_start(SSH2_MSG_CHANNEL_OPEN);
1319 packet_put_cstring(rtype);
1320 packet_put_int(c->self);
1321 packet_put_int(c->local_window_max);
1322 packet_put_int(c->local_maxpacket);
1323 if (direct) {
1324 /* target host, port */
1325 packet_put_cstring(c->path);
1326 packet_put_int(c->host_port);
1327 } else {
1328 /* listen address, port */
1329 packet_put_cstring(c->path);
1330 packet_put_int(c->listening_port);
1331 }
1332 /* originator host and port */
1333 packet_put_cstring(remote_ipaddr);
473db5ab 1334 packet_put_int((u_int)remote_port);
3c0ef626 1335 packet_send();
1336 } else {
1337 packet_start(SSH_MSG_PORT_OPEN);
1338 packet_put_int(c->self);
1339 packet_put_cstring(c->path);
1340 packet_put_int(c->host_port);
1341 if (packet_get_protocol_flags() &
1342 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1343 packet_put_cstring(c->remote_name);
1344 packet_send();
1345 }
1346 xfree(remote_ipaddr);
1347}
1348
08822d99 1349static void
1350channel_set_reuseaddr(int fd)
1351{
1352 int on = 1;
1353
1354 /*
1355 * Set socket options.
1356 * Allow local port reuse in TIME_WAIT.
1357 */
1358 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1359 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1360}
1361
3c0ef626 1362/*
1363 * This socket is listening for connections to a forwarded TCP/IP port.
1364 */
30460aeb 1365/* ARGSUSED */
3c0ef626 1366static void
30460aeb 1367channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1368{
1369 Channel *nc;
5156b1a1 1370 struct sockaddr_storage addr;
3c0ef626 1371 int newsock, nextstate;
1372 socklen_t addrlen;
1373 char *rtype;
1374
1375 if (FD_ISSET(c->sock, readset)) {
1376 debug("Connection to port %d forwarding "
1377 "to %.100s port %d requested.",
1378 c->listening_port, c->path, c->host_port);
1379
1380 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1381 nextstate = SSH_CHANNEL_OPENING;
1382 rtype = "forwarded-tcpip";
1383 } else {
1384 if (c->host_port == 0) {
1385 nextstate = SSH_CHANNEL_DYNAMIC;
1386 rtype = "dynamic-tcpip";
1387 } else {
1388 nextstate = SSH_CHANNEL_OPENING;
1389 rtype = "direct-tcpip";
1390 }
1391 }
1392
1393 addrlen = sizeof(addr);
5156b1a1 1394 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
3c0ef626 1395 if (newsock < 0) {
1396 error("accept: %.100s", strerror(errno));
1397 return;
1398 }
473db5ab 1399 set_nodelay(newsock);
1400 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1401 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
3c0ef626 1402 nc->listening_port = c->listening_port;
1403 nc->host_port = c->host_port;
1404 strlcpy(nc->path, c->path, sizeof(nc->path));
1405
1406 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1407 /*
1408 * do not call the channel_post handler until
1409 * this flag has been reset by a pre-handler.
1410 * otherwise the FD_ISSET calls might overflow
1411 */
1412 nc->delayed = 1;
1413 } else {
1414 port_open_helper(nc, rtype);
1415 }
1416 }
1417}
1418
1419/*
1420 * This is the authentication agent socket listening for connections from
1421 * clients.
1422 */
30460aeb 1423/* ARGSUSED */
3c0ef626 1424static void
30460aeb 1425channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1426{
1427 Channel *nc;
3c0ef626 1428 int newsock;
5156b1a1 1429 struct sockaddr_storage addr;
3c0ef626 1430 socklen_t addrlen;
1431
1432 if (FD_ISSET(c->sock, readset)) {
1433 addrlen = sizeof(addr);
5156b1a1 1434 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
3c0ef626 1435 if (newsock < 0) {
1436 error("accept from auth socket: %.100s", strerror(errno));
1437 return;
1438 }
3c0ef626 1439 nc = channel_new("accepted auth socket",
1440 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1441 c->local_window_max, c->local_maxpacket,
473db5ab 1442 0, "accepted auth socket", 1);
3c0ef626 1443 if (compat20) {
1444 packet_start(SSH2_MSG_CHANNEL_OPEN);
1445 packet_put_cstring("auth-agent@openssh.com");
1446 packet_put_int(nc->self);
1447 packet_put_int(c->local_window_max);
1448 packet_put_int(c->local_maxpacket);
1449 } else {
1450 packet_start(SSH_SMSG_AGENT_OPEN);
1451 packet_put_int(nc->self);
1452 }
1453 packet_send();
1454 }
1455}
1456
30460aeb 1457/* ARGSUSED */
3c0ef626 1458static void
30460aeb 1459channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1460{
5156b1a1 1461 int err = 0, sock;
3c0ef626 1462 socklen_t sz = sizeof(err);
1463
1464 if (FD_ISSET(c->sock, writeset)) {
473db5ab 1465 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
3c0ef626 1466 err = errno;
1467 error("getsockopt SO_ERROR failed");
1468 }
1469 if (err == 0) {
5156b1a1 1470 debug("channel %d: connected to %s port %d",
1471 c->self, c->connect_ctx.host, c->connect_ctx.port);
1472 channel_connect_ctx_free(&c->connect_ctx);
3c0ef626 1473 c->type = SSH_CHANNEL_OPEN;
1474 if (compat20) {
1475 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1476 packet_put_int(c->remote_id);
1477 packet_put_int(c->self);
1478 packet_put_int(c->local_window);
1479 packet_put_int(c->local_maxpacket);
1480 } else {
1481 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1482 packet_put_int(c->remote_id);
1483 packet_put_int(c->self);
1484 }
1485 } else {
5156b1a1 1486 debug("channel %d: connection failed: %s",
3c0ef626 1487 c->self, strerror(err));
5156b1a1 1488 /* Try next address, if any */
1489 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1490 close(c->sock);
1491 c->sock = c->rfd = c->wfd = sock;
1492 channel_max_fd = channel_find_maxfd();
1493 return;
1494 }
1495 /* Exhausted all addresses */
1496 error("connect_to %.100s port %d: failed.",
1497 c->connect_ctx.host, c->connect_ctx.port);
1498 channel_connect_ctx_free(&c->connect_ctx);
3c0ef626 1499 if (compat20) {
1500 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1501 packet_put_int(c->remote_id);
1502 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1503 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1504 packet_put_cstring(strerror(err));
1505 packet_put_cstring("");
1506 }
1507 } else {
1508 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1509 packet_put_int(c->remote_id);
1510 }
1511 chan_mark_dead(c);
1512 }
1513 packet_send();
1514 }
1515}
1516
30460aeb 1517/* ARGSUSED */
3c0ef626 1518static int
30460aeb 1519channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1520{
473db5ab 1521 char buf[CHAN_RBUF];
fa0f0f45 1522 int len, force;
3c0ef626 1523
fa0f0f45 1524 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1525 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
30460aeb 1526 errno = 0;
3c0ef626 1527 len = read(c->rfd, buf, sizeof(buf));
5156b1a1 1528 if (len < 0 && (errno == EINTR ||
1529 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
3c0ef626 1530 return 1;
30460aeb 1531#ifndef PTY_ZEROREAD
3c0ef626 1532 if (len <= 0) {
30460aeb 1533#else
1534 if ((!c->isatty && len <= 0) ||
1535 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1536#endif
473db5ab 1537 debug2("channel %d: read<=0 rfd %d len %d",
3c0ef626 1538 c->self, c->rfd, len);
1539 if (c->type != SSH_CHANNEL_OPEN) {
473db5ab 1540 debug2("channel %d: not open", c->self);
3c0ef626 1541 chan_mark_dead(c);
1542 return -1;
1543 } else if (compat13) {
473db5ab 1544 buffer_clear(&c->output);
3c0ef626 1545 c->type = SSH_CHANNEL_INPUT_DRAINING;
473db5ab 1546 debug2("channel %d: input draining.", c->self);
3c0ef626 1547 } else {
1548 chan_read_failed(c);
1549 }
1550 return -1;
1551 }
473db5ab 1552 if (c->input_filter != NULL) {
3c0ef626 1553 if (c->input_filter(c, buf, len) == -1) {
473db5ab 1554 debug2("channel %d: filter stops", c->self);
3c0ef626 1555 chan_read_failed(c);
1556 }
08822d99 1557 } else if (c->datagram) {
1558 buffer_put_string(&c->input, buf, len);
3c0ef626 1559 } else {
1560 buffer_append(&c->input, buf, len);
1561 }
1562 }
1563 return 1;
1564}
30460aeb 1565
1566/* ARGSUSED */
3c0ef626 1567static int
30460aeb 1568channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1569{
1570 struct termios tio;
08822d99 1571 u_char *data = NULL, *buf;
3c0ef626 1572 u_int dlen;
1573 int len;
1574
1575 /* Send buffered output data to the socket. */
1576 if (c->wfd != -1 &&
1577 FD_ISSET(c->wfd, writeset) &&
1578 buffer_len(&c->output) > 0) {
08822d99 1579 if (c->output_filter != NULL) {
1580 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1581 debug2("channel %d: filter stops", c->self);
1582 if (c->type != SSH_CHANNEL_OPEN)
1583 chan_mark_dead(c);
1584 else
1585 chan_write_failed(c);
1586 return -1;
1587 }
1588 } else if (c->datagram) {
1589 buf = data = buffer_get_string(&c->output, &dlen);
1590 } else {
1591 buf = data = buffer_ptr(&c->output);
1592 dlen = buffer_len(&c->output);
1593 }
1594
1595 if (c->datagram) {
1596 /* ignore truncated writes, datagrams might get lost */
1597 c->local_consumed += dlen + 4;
1598 len = write(c->wfd, buf, dlen);
1599 xfree(data);
5156b1a1 1600 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1601 errno == EWOULDBLOCK))
08822d99 1602 return 1;
1603 if (len <= 0) {
1604 if (c->type != SSH_CHANNEL_OPEN)
1605 chan_mark_dead(c);
1606 else
1607 chan_write_failed(c);
1608 return -1;
1609 }
1610 return 1;
1611 }
473db5ab 1612#ifdef _AIX
1613 /* XXX: Later AIX versions can't push as much data to tty */
1614 if (compat20 && c->wfd_isatty)
1615 dlen = MIN(dlen, 8*1024);
1616#endif
08822d99 1617
1618 len = write(c->wfd, buf, dlen);
5156b1a1 1619 if (len < 0 &&
1620 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
3c0ef626 1621 return 1;
1622 if (len <= 0) {
1623 if (c->type != SSH_CHANNEL_OPEN) {
473db5ab 1624 debug2("channel %d: not open", c->self);
3c0ef626 1625 chan_mark_dead(c);
1626 return -1;
1627 } else if (compat13) {
473db5ab 1628 buffer_clear(&c->output);
1629 debug2("channel %d: input draining.", c->self);
3c0ef626 1630 c->type = SSH_CHANNEL_INPUT_DRAINING;
1631 } else {
1632 chan_write_failed(c);
1633 }
1634 return -1;
1635 }
08822d99 1636 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
3c0ef626 1637 if (tcgetattr(c->wfd, &tio) == 0 &&
1638 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1639 /*
1640 * Simulate echo to reduce the impact of
1641 * traffic analysis. We need to match the
1642 * size of a SSH2_MSG_CHANNEL_DATA message
08822d99 1643 * (4 byte channel id + buf)
3c0ef626 1644 */
1645 packet_send_ignore(4 + len);
1646 packet_send();
1647 }
1648 }
1649 buffer_consume(&c->output, len);
1650 if (compat20 && len > 0) {
1651 c->local_consumed += len;
1652 }
1653 }
1654 return 1;
1655}
30460aeb 1656
3c0ef626 1657static int
30460aeb 1658channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1659{
473db5ab 1660 char buf[CHAN_RBUF];
3c0ef626 1661 int len;
1662
1663/** XXX handle drain efd, too */
1664 if (c->efd != -1) {
1665 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1666 FD_ISSET(c->efd, writeset) &&
1667 buffer_len(&c->extended) > 0) {
1668 len = write(c->efd, buffer_ptr(&c->extended),
1669 buffer_len(&c->extended));
1670 debug2("channel %d: written %d to efd %d",
1671 c->self, len, c->efd);
5156b1a1 1672 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1673 errno == EWOULDBLOCK))
3c0ef626 1674 return 1;
1675 if (len <= 0) {
1676 debug2("channel %d: closing write-efd %d",
1677 c->self, c->efd);
1678 channel_close_fd(&c->efd);
1679 } else {
1680 buffer_consume(&c->extended, len);
1681 c->local_consumed += len;
1682 }
1683 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
0b90ac93 1684 (c->detach_close || FD_ISSET(c->efd, readset))) {
3c0ef626 1685 len = read(c->efd, buf, sizeof(buf));
1686 debug2("channel %d: read %d from efd %d",
473db5ab 1687 c->self, len, c->efd);
5156b1a1 1688 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1689 errno == EWOULDBLOCK) && !c->detach_close)))
3c0ef626 1690 return 1;
1691 if (len <= 0) {
1692 debug2("channel %d: closing read-efd %d",
1693 c->self, c->efd);
1694 channel_close_fd(&c->efd);
1695 } else {
1696 buffer_append(&c->extended, buf, len);
1697 }
1698 }
1699 }
1700 return 1;
1701}
30460aeb 1702
1703/* ARGSUSED */
3c0ef626 1704static int
30460aeb 1705channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
473db5ab 1706{
1707 char buf[16];
1708 int len;
1709
1710 /* Monitor control fd to detect if the slave client exits */
1711 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1712 len = read(c->ctl_fd, buf, sizeof(buf));
5156b1a1 1713 if (len < 0 &&
1714 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
473db5ab 1715 return 1;
1716 if (len <= 0) {
1717 debug2("channel %d: ctl read<=0", c->self);
1718 if (c->type != SSH_CHANNEL_OPEN) {
1719 debug2("channel %d: not open", c->self);
1720 chan_mark_dead(c);
1721 return -1;
1722 } else {
1723 chan_read_failed(c);
1724 chan_write_failed(c);
1725 }
1726 return -1;
1727 } else
1728 fatal("%s: unexpected data on ctl fd", __func__);
1729 }
1730 return 1;
1731}
30460aeb 1732
473db5ab 1733static int
3c0ef626 1734channel_check_window(Channel *c)
1735{
1736 if (c->type == SSH_CHANNEL_OPEN &&
1737 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
fa0f0f45 1738 ((c->local_window_max - c->local_window >
1739 c->local_maxpacket*3) ||
1740 c->local_window < c->local_window_max/2) &&
3c0ef626 1741 c->local_consumed > 0) {
a7213e65 1742 u_int addition = 0;
1743 /* adjust max window size if we are in a dynamic environment */
1744 if (c->dynamic_window && (c->tcpwinsz > c->local_window_max)) {
6df46d40 1745 /* grow the window somewhat aggressively to maintain pressure */
1746 addition = 1.5*(c->tcpwinsz - c->local_window_max);
473db5ab 1747 c->local_window_max += addition;
1748 }
3c0ef626 1749 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1750 packet_put_int(c->remote_id);
473db5ab 1751 packet_put_int(c->local_consumed + addition);
3c0ef626 1752 packet_send();
1753 debug2("channel %d: window %d sent adjust %d",
1754 c->self, c->local_window,
1755 c->local_consumed);
473db5ab 1756 c->local_window += c->local_consumed + addition;
3c0ef626 1757 c->local_consumed = 0;
1758 }
1759 return 1;
1760}
1761
1762static void
30460aeb 1763channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1764{
1765 if (c->delayed)
1766 return;
1767 channel_handle_rfd(c, readset, writeset);
1768 channel_handle_wfd(c, readset, writeset);
473db5ab 1769 if (!compat20)
3c0ef626 1770 return;
3c0ef626 1771 channel_handle_efd(c, readset, writeset);
473db5ab 1772 channel_handle_ctl(c, readset, writeset);
3c0ef626 1773 channel_check_window(c);
1774}
1775
30460aeb 1776/* ARGSUSED */
3c0ef626 1777static void
30460aeb 1778channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
3c0ef626 1779{
1780 int len;
473db5ab 1781
3c0ef626 1782 /* Send buffered output data to the socket. */
1783 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1784 len = write(c->sock, buffer_ptr(&c->output),
1785 buffer_len(&c->output));
1786 if (len <= 0)
473db5ab 1787 buffer_clear(&c->output);
3c0ef626 1788 else
1789 buffer_consume(&c->output, len);
1790 }
1791}
1792
1793static void
1794channel_handler_init_20(void)
1795{
473db5ab 1796 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
3c0ef626 1797 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1798 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1799 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1800 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1801 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1802 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1803 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1804
473db5ab 1805 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
3c0ef626 1806 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1807 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1808 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1809 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1810 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
473db5ab 1811 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
3c0ef626 1812}
1813
1814static void
1815channel_handler_init_13(void)
1816{
1817 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1818 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1819 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1820 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1821 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1822 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1823 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1824 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1825 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1826
473db5ab 1827 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
3c0ef626 1828 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1829 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1830 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1831 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1832 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
473db5ab 1833 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
3c0ef626 1834}
1835
1836static void
1837channel_handler_init_15(void)
1838{
473db5ab 1839 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
3c0ef626 1840 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1841 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1842 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1843 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1844 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1845 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1846
1847 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1848 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1849 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
473db5ab 1850 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
3c0ef626 1851 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
473db5ab 1852 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
3c0ef626 1853}
1854
1855static void
1856channel_handler_init(void)
1857{
1858 int i;
473db5ab 1859
1860 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
3c0ef626 1861 channel_pre[i] = NULL;
1862 channel_post[i] = NULL;
1863 }
1864 if (compat20)
1865 channel_handler_init_20();
1866 else if (compat13)
1867 channel_handler_init_13();
1868 else
1869 channel_handler_init_15();
1870}
1871
1872/* gc dead channels */
1873static void
1874channel_garbage_collect(Channel *c)
1875{
1876 if (c == NULL)
1877 return;
1878 if (c->detach_user != NULL) {
08822d99 1879 if (!chan_is_dead(c, c->detach_close))
3c0ef626 1880 return;
473db5ab 1881 debug2("channel %d: gc: notify user", c->self);
3c0ef626 1882 c->detach_user(c->self, NULL);
1883 /* if we still have a callback */
1884 if (c->detach_user != NULL)
1885 return;
473db5ab 1886 debug2("channel %d: gc: user detached", c->self);
3c0ef626 1887 }
1888 if (!chan_is_dead(c, 1))
1889 return;
473db5ab 1890 debug2("channel %d: garbage collecting", c->self);
3c0ef626 1891 channel_free(c);
1892}
1893
1894static void
30460aeb 1895channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
3c0ef626 1896{
1897 static int did_init = 0;
473db5ab 1898 u_int i;
3c0ef626 1899 Channel *c;
1900
1901 if (!did_init) {
1902 channel_handler_init();
1903 did_init = 1;
1904 }
1905 for (i = 0; i < channels_alloc; i++) {
1906 c = channels[i];
1907 if (c == NULL)
1908 continue;
1909 if (ftab[c->type] != NULL)
1910 (*ftab[c->type])(c, readset, writeset);
1911 channel_garbage_collect(c);
1912 }
1913}
1914
1915/*
1916 * Allocate/update select bitmasks and add any bits relevant to channels in
1917 * select bitmasks.
1918 */
1919void
1920channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
473db5ab 1921 u_int *nallocp, int rekeying)
3c0ef626 1922{
30460aeb 1923 u_int n, sz, nfdset;
3c0ef626 1924
1925 n = MAX(*maxfdp, channel_max_fd);
1926
30460aeb 1927 nfdset = howmany(n+1, NFDBITS);
1928 /* Explicitly test here, because xrealloc isn't always called */
1929 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1930 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1931 sz = nfdset * sizeof(fd_mask);
1932
3c0ef626 1933 /* perhaps check sz < nalloc/2 and shrink? */
1934 if (*readsetp == NULL || sz > *nallocp) {
30460aeb 1935 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1936 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
3c0ef626 1937 *nallocp = sz;
1938 }
1939 *maxfdp = n;
1940 memset(*readsetp, 0, sz);
1941 memset(*writesetp, 0, sz);
1942
1943 if (!rekeying)
1944 channel_handler(channel_pre, *readsetp, *writesetp);
1945}
1946
1947/*
1948 * After select, perform any appropriate operations for channels which have
1949 * events pending.
1950 */
1951void
30460aeb 1952channel_after_select(fd_set *readset, fd_set *writeset)
3c0ef626 1953{
1954 channel_handler(channel_post, readset, writeset);
1955}
1956
1957
1958/* If there is data to send to the connection, enqueue some of it now. */
fa7499cc 1959int
473db5ab 1960channel_output_poll(void)
3c0ef626 1961{
3c0ef626 1962 Channel *c;
473db5ab 1963 u_int i, len;
fa7499cc 1964 int packet_length = 0;
3c0ef626 1965
1966 for (i = 0; i < channels_alloc; i++) {
1967 c = channels[i];
1968 if (c == NULL)
1969 continue;
1970
1971 /*
1972 * We are only interested in channels that can have buffered
1973 * incoming data.
1974 */
1975 if (compat13) {
1976 if (c->type != SSH_CHANNEL_OPEN &&
1977 c->type != SSH_CHANNEL_INPUT_DRAINING)
1978 continue;
1979 } else {
1980 if (c->type != SSH_CHANNEL_OPEN)
1981 continue;
1982 }
1983 if (compat20 &&
1984 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1985 /* XXX is this true? */
1986 debug3("channel %d: will not send data after close", c->self);
1987 continue;
1988 }
1989
1990 /* Get the amount of buffered data for this channel. */
1991 if ((c->istate == CHAN_INPUT_OPEN ||
1992 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1993 (len = buffer_len(&c->input)) > 0) {
08822d99 1994 if (c->datagram) {
1995 if (len > 0) {
1996 u_char *data;
1997 u_int dlen;
1998
1999 data = buffer_get_string(&c->input,
2000 &dlen);
2001 packet_start(SSH2_MSG_CHANNEL_DATA);
2002 packet_put_int(c->remote_id);
2003 packet_put_string(data, dlen);
fa7499cc 2004 packet_length = packet_send();
08822d99 2005 c->remote_window -= dlen + 4;
2006 xfree(data);
2007 }
2008 continue;
2009 }
3c0ef626 2010 /*
2011 * Send some data for the other side over the secure
2012 * connection.
2013 */
2014 if (compat20) {
2015 if (len > c->remote_window)
2016 len = c->remote_window;
2017 if (len > c->remote_maxpacket)
2018 len = c->remote_maxpacket;
2019 } else {
2020 if (packet_is_interactive()) {
2021 if (len > 1024)
2022 len = 512;
2023 } else {
2024 /* Keep the packets at reasonable size. */
2025 if (len > packet_get_maxsize()/2)
2026 len = packet_get_maxsize()/2;
2027 }
2028 }
2029 if (len > 0) {
2030 packet_start(compat20 ?
2031 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2032 packet_put_int(c->remote_id);
2033 packet_put_string(buffer_ptr(&c->input), len);
fa7499cc 2034 packet_length = packet_send();
3c0ef626 2035 buffer_consume(&c->input, len);
2036 c->remote_window -= len;
2037 }
2038 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2039 if (compat13)
2040 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2041 /*
2042 * input-buffer is empty and read-socket shutdown:
473db5ab 2043 * tell peer, that we will not send more data: send IEOF.
2044 * hack for extended data: delay EOF if EFD still in use.
3c0ef626 2045 */
473db5ab 2046 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2047 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2048 c->self, c->efd, buffer_len(&c->extended));
2049 else
2050 chan_ibuf_empty(c);
3c0ef626 2051 }
2052 /* Send extended data, i.e. stderr */
2053 if (compat20 &&
473db5ab 2054 !(c->flags & CHAN_EOF_SENT) &&
3c0ef626 2055 c->remote_window > 0 &&
2056 (len = buffer_len(&c->extended)) > 0 &&
2057 c->extended_usage == CHAN_EXTENDED_READ) {
473db5ab 2058 debug2("channel %d: rwin %u elen %u euse %d",
3c0ef626 2059 c->self, c->remote_window, buffer_len(&c->extended),
2060 c->extended_usage);
2061 if (len > c->remote_window)
2062 len = c->remote_window;
2063 if (len > c->remote_maxpacket)
2064 len = c->remote_maxpacket;
2065 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2066 packet_put_int(c->remote_id);
2067 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2068 packet_put_string(buffer_ptr(&c->extended), len);
fa7499cc 2069 packet_length = packet_send();
3c0ef626 2070 buffer_consume(&c->extended, len);
2071 c->remote_window -= len;
2072 debug2("channel %d: sent ext data %d", c->self, len);
2073 }
2074 }
fa7499cc 2075 return (packet_length);
3c0ef626 2076}
2077
2078
2079/* -- protocol input */
2080
30460aeb 2081/* ARGSUSED */
3c0ef626 2082void
473db5ab 2083channel_input_data(int type, u_int32_t seq, void *ctxt)
3c0ef626 2084{
2085 int id;
2086 char *data;
2087 u_int data_len;
2088 Channel *c;
2089
2090 /* Get the channel number and verify it. */
2091 id = packet_get_int();
2092 c = channel_lookup(id);
2093 if (c == NULL)
2094 packet_disconnect("Received data for nonexistent channel %d.", id);
2095
2096 /* Ignore any data for non-open channels (might happen on close) */
2097 if (c->type != SSH_CHANNEL_OPEN &&
2098 c->type != SSH_CHANNEL_X11_OPEN)
2099 return;
2100
3c0ef626 2101 /* Get the data. */
5156b1a1 2102 data = packet_get_string_ptr(&data_len);
3c0ef626 2103
473db5ab 2104 /*
2105 * Ignore data for protocol > 1.3 if output end is no longer open.
2106 * For protocol 2 the sending side is reducing its window as it sends
2107 * data, so we must 'fake' consumption of the data in order to ensure
2108 * that window updates are sent back. Otherwise the connection might
2109 * deadlock.
2110 */
2111 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2112 if (compat20) {
2113 c->local_window -= data_len;
2114 c->local_consumed += data_len;
2115 }
473db5ab 2116 return;
2117 }
2118
2119 if (compat20) {
3c0ef626 2120 if (data_len > c->local_maxpacket) {
473db5ab 2121 logit("channel %d: rcvd big packet %d, maxpack %d",
3c0ef626 2122 c->self, data_len, c->local_maxpacket);
2123 }
2124 if (data_len > c->local_window) {
473db5ab 2125 logit("channel %d: rcvd too much data %d, win %d",
3c0ef626 2126 c->self, data_len, c->local_window);
3c0ef626 2127 return;
2128 }
2129 c->local_window -= data_len;
3c0ef626 2130 }
08822d99 2131 if (c->datagram)
2132 buffer_put_string(&c->output, data, data_len);
2133 else
2134 buffer_append(&c->output, data, data_len);
5156b1a1 2135 packet_check_eom();
3c0ef626 2136}
2137
30460aeb 2138/* ARGSUSED */
3c0ef626 2139void
473db5ab 2140channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
3c0ef626 2141{
2142 int id;
3c0ef626 2143 char *data;
473db5ab 2144 u_int data_len, tcode;
3c0ef626 2145 Channel *c;
2146
2147 /* Get the channel number and verify it. */
2148 id = packet_get_int();
2149 c = channel_lookup(id);
2150
2151 if (c == NULL)
2152 packet_disconnect("Received extended_data for bad channel %d.", id);
2153 if (c->type != SSH_CHANNEL_OPEN) {
473db5ab 2154 logit("channel %d: ext data for non open", id);
3c0ef626 2155 return;
2156 }
473db5ab 2157 if (c->flags & CHAN_EOF_RCVD) {
2158 if (datafellows & SSH_BUG_EXTEOF)
2159 debug("channel %d: accepting ext data after eof", id);
2160 else
2161 packet_disconnect("Received extended_data after EOF "
2162 "on channel %d.", id);
2163 }
3c0ef626 2164 tcode = packet_get_int();
2165 if (c->efd == -1 ||
2166 c->extended_usage != CHAN_EXTENDED_WRITE ||
2167 tcode != SSH2_EXTENDED_DATA_STDERR) {
473db5ab 2168 logit("channel %d: bad ext data", c->self);
3c0ef626 2169 return;
2170 }
2171 data = packet_get_string(&data_len);
473db5ab 2172 packet_check_eom();
3c0ef626 2173 if (data_len > c->local_window) {
473db5ab 2174 logit("channel %d: rcvd too much extended_data %d, win %d",
3c0ef626 2175 c->self, data_len, c->local_window);
2176 xfree(data);
2177 return;
2178 }
2179 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2180 c->local_window -= data_len;
2181 buffer_append(&c->extended, data, data_len);
2182 xfree(data);
2183}
2184
30460aeb 2185/* ARGSUSED */
3c0ef626 2186void
473db5ab 2187channel_input_ieof(int type, u_int32_t seq, void *ctxt)
3c0ef626 2188{
2189 int id;
2190 Channel *c;
2191
3c0ef626 2192 id = packet_get_int();
473db5ab 2193 packet_check_eom();
3c0ef626 2194 c = channel_lookup(id);
2195 if (c == NULL)
2196 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2197 chan_rcvd_ieof(c);
2198
2199 /* XXX force input close */
473db5ab 2200 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3c0ef626 2201 debug("channel %d: FORCE input drain", c->self);
2202 c->istate = CHAN_INPUT_WAIT_DRAIN;
473db5ab 2203 if (buffer_len(&c->input) == 0)
2204 chan_ibuf_empty(c);
3c0ef626 2205 }
2206
2207}
2208
30460aeb 2209/* ARGSUSED */
3c0ef626 2210void
473db5ab 2211channel_input_close(int type, u_int32_t seq, void *ctxt)
3c0ef626 2212{
2213 int id;
2214 Channel *c;
2215
3c0ef626 2216 id = packet_get_int();
473db5ab 2217 packet_check_eom();
3c0ef626 2218 c = channel_lookup(id);
2219 if (c == NULL)
2220 packet_disconnect("Received close for nonexistent channel %d.", id);
2221
2222 /*
2223 * Send a confirmation that we have closed the channel and no more
2224 * data is coming for it.
2225 */
2226 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2227 packet_put_int(c->remote_id);
2228 packet_send();
2229
2230 /*
2231 * If the channel is in closed state, we have sent a close request,
2232 * and the other side will eventually respond with a confirmation.
2233 * Thus, we cannot free the channel here, because then there would be
2234 * no-one to receive the confirmation. The channel gets freed when
2235 * the confirmation arrives.
2236 */
2237 if (c->type != SSH_CHANNEL_CLOSED) {
2238 /*
2239 * Not a closed channel - mark it as draining, which will
2240 * cause it to be freed later.
2241 */
473db5ab 2242 buffer_clear(&c->input);
3c0ef626 2243 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2244 }
2245}
2246
2247/* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
30460aeb 2248/* ARGSUSED */
3c0ef626 2249void
473db5ab 2250channel_input_oclose(int type, u_int32_t seq, void *ctxt)
3c0ef626 2251{
2252 int id = packet_get_int();
2253 Channel *c = channel_lookup(id);
473db5ab 2254
2255 packet_check_eom();
3c0ef626 2256 if (c == NULL)
2257 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2258 chan_rcvd_oclose(c);
2259}
2260
30460aeb 2261/* ARGSUSED */
3c0ef626 2262void
473db5ab 2263channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
3c0ef626 2264{
2265 int id = packet_get_int();
2266 Channel *c = channel_lookup(id);
2267
473db5ab 2268 packet_check_eom();
3c0ef626 2269 if (c == NULL)
2270 packet_disconnect("Received close confirmation for "
2271 "out-of-range channel %d.", id);
2272 if (c->type != SSH_CHANNEL_CLOSED)
2273 packet_disconnect("Received close confirmation for "
2274 "non-closed channel %d (type %d).", id, c->type);
2275 channel_free(c);
2276}
2277
30460aeb 2278/* ARGSUSED */
3c0ef626 2279void
473db5ab 2280channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
3c0ef626 2281{
2282 int id, remote_id;
2283 Channel *c;
2284
3c0ef626 2285 id = packet_get_int();
2286 c = channel_lookup(id);
2287
2288 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2289 packet_disconnect("Received open confirmation for "
2290 "non-opening channel %d.", id);
2291 remote_id = packet_get_int();
2292 /* Record the remote channel number and mark that the channel is now open. */
2293 c->remote_id = remote_id;
2294 c->type = SSH_CHANNEL_OPEN;
2295
2296 if (compat20) {
2297 c->remote_window = packet_get_int();
2298 c->remote_maxpacket = packet_get_int();
5156b1a1 2299 if (c->open_confirm) {
3c0ef626 2300 debug2("callback start");
5156b1a1 2301 c->open_confirm(c->self, c->open_confirm_ctx);
3c0ef626 2302 debug2("callback done");
2303 }
473db5ab 2304 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3c0ef626 2305 c->remote_window, c->remote_maxpacket);
2306 }
473db5ab 2307 packet_check_eom();
3c0ef626 2308}
2309
2310static char *
2311reason2txt(int reason)
2312{
473db5ab 2313 switch (reason) {
3c0ef626 2314 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2315 return "administratively prohibited";
2316 case SSH2_OPEN_CONNECT_FAILED:
2317 return "connect failed";
2318 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2319 return "unknown channel type";
2320 case SSH2_OPEN_RESOURCE_SHORTAGE:
2321 return "resource shortage";
2322 }
2323 return "unknown reason";
2324}
2325
30460aeb 2326/* ARGSUSED */
3c0ef626 2327void
473db5ab 2328channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
3c0ef626 2329{
2330 int id, reason;
2331 char *msg = NULL, *lang = NULL;
2332 Channel *c;
2333
3c0ef626 2334 id = packet_get_int();
2335 c = channel_lookup(id);
2336
2337 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2338 packet_disconnect("Received open failure for "
2339 "non-opening channel %d.", id);
2340 if (compat20) {
2341 reason = packet_get_int();
2342 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2343 msg = packet_get_string(NULL);
2344 lang = packet_get_string(NULL);
2345 }
473db5ab 2346 logit("channel %d: open failed: %s%s%s", id,
3c0ef626 2347 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2348 if (msg != NULL)
2349 xfree(msg);
2350 if (lang != NULL)
2351 xfree(lang);
2352 }
473db5ab 2353 packet_check_eom();
3c0ef626 2354 /* Free the channel. This will also close the socket. */
2355 channel_free(c);
2356}
2357
30460aeb 2358/* ARGSUSED */
3c0ef626 2359void
473db5ab 2360channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
3c0ef626 2361{
3c0ef626 2362 Channel *c;
473db5ab 2363 int id;
2364 u_int adjust;
3c0ef626 2365
2366 if (!compat20)
2367 return;
2368
2369 /* Get the channel number and verify it. */
2370 id = packet_get_int();
2371 c = channel_lookup(id);
2372
08822d99 2373 if (c == NULL) {
2374 logit("Received window adjust for non-open channel %d.", id);
3c0ef626 2375 return;
2376 }
2377 adjust = packet_get_int();
473db5ab 2378 packet_check_eom();
2379 debug2("channel %d: rcvd adjust %u", id, adjust);
3c0ef626 2380 c->remote_window += adjust;
2381}
2382
30460aeb 2383/* ARGSUSED */
3c0ef626 2384void
473db5ab 2385channel_input_port_open(int type, u_int32_t seq, void *ctxt)
3c0ef626 2386{
2387 Channel *c = NULL;
2388 u_short host_port;
2389 char *host, *originator_string;
5156b1a1 2390 int remote_id;
3c0ef626 2391
2392 remote_id = packet_get_int();
2393 host = packet_get_string(NULL);
2394 host_port = packet_get_int();
2395
2396 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2397 originator_string = packet_get_string(NULL);
2398 } else {
2399 originator_string = xstrdup("unknown (remote did not supply name)");
2400 }
473db5ab 2401 packet_check_eom();
5156b1a1 2402 c = channel_connect_to(host, host_port,
2403 "connected socket", originator_string);
473db5ab 2404 xfree(originator_string);
5156b1a1 2405 xfree(host);
3c0ef626 2406 if (c == NULL) {
2407 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2408 packet_put_int(remote_id);
2409 packet_send();
5156b1a1 2410 } else
2411 c->remote_id = remote_id;
3c0ef626 2412}
2413
5156b1a1 2414/* ARGSUSED */
2415void
2416channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2417{
2418 Channel *c;
2419 struct channel_confirm *cc;
2420 int remote_id;
2421
2422 /* Reset keepalive timeout */
2423 keep_alive_timeouts = 0;
2424
2425 remote_id = packet_get_int();
2426 packet_check_eom();
2427
2428 debug2("channel_input_confirm: type %d id %d", type, remote_id);
2429
2430 if ((c = channel_lookup(remote_id)) == NULL) {
2431 logit("channel_input_success_failure: %d: unknown", remote_id);
2432 return;
2433 }
2434 ;
2435 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2436 return;
2437 cc->cb(type, c, cc->ctx);
2438 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2439 bzero(cc, sizeof(*cc));
2440 xfree(cc);
2441}
3c0ef626 2442
2443/* -- tcp forwarding */
2444
2445void
2446channel_set_af(int af)
2447{
2448 IPv4or6 = af;
2449}
2450
d3057ca4 2451
2452void
2453channel_set_hpn(int external_hpn_disabled, int external_hpn_buffer_size)
2454{
2455 hpn_disabled = external_hpn_disabled;
2456 hpn_buffer_size = external_hpn_buffer_size;
2457 debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled, hpn_buffer_size);
2458}
2459
473db5ab 2460static int
2461channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
d3057ca4 2462 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
3c0ef626 2463{
2464 Channel *c;
08822d99 2465 int sock, r, success = 0, wildcard = 0, is_client;
3c0ef626 2466 struct addrinfo hints, *ai, *aitop;
473db5ab 2467 const char *host, *addr;
3c0ef626 2468 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3c0ef626 2469
473db5ab 2470 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2471 listen_addr : host_to_connect;
2472 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3c0ef626 2473
473db5ab 2474 if (host == NULL) {
2475 error("No forward host name.");
2476 return 0;
3c0ef626 2477 }
3c0ef626 2478 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2479 error("Forward host name too long.");
473db5ab 2480 return 0;
3c0ef626 2481 }
2482
473db5ab 2483 /*
2484 * Determine whether or not a port forward listens to loopback,
2485 * specified address or wildcard. On the client, a specified bind
2486 * address will always override gateway_ports. On the server, a
2487 * gateway_ports of 1 (``yes'') will override the client's
2488 * specification and force a wildcard bind, whereas a value of 2
2489 * (``clientspecified'') will bind to whatever address the client
2490 * asked for.
2491 *
2492 * Special-case listen_addrs are:
2493 *
2494 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2495 * "" (empty string), "*" -> wildcard v4/v6
2496 * "localhost" -> loopback v4/v6
2497 */
2498 addr = NULL;
2499 if (listen_addr == NULL) {
2500 /* No address specified: default to gateway_ports setting */
2501 if (gateway_ports)
2502 wildcard = 1;
2503 } else if (gateway_ports || is_client) {
2504 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
e74dc197 2505 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
473db5ab 2506 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2507 (!is_client && gateway_ports == 1))
2508 wildcard = 1;
2509 else if (strcmp(listen_addr, "localhost") != 0)
2510 addr = listen_addr;
2511 }
2512
2513 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2514 type, wildcard, (addr == NULL) ? "NULL" : addr);
2515
3c0ef626 2516 /*
2517 * getaddrinfo returns a loopback address if the hostname is
2518 * set to NULL and hints.ai_flags is not AI_PASSIVE
2519 */
2520 memset(&hints, 0, sizeof(hints));
2521 hints.ai_family = IPv4or6;
473db5ab 2522 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3c0ef626 2523 hints.ai_socktype = SOCK_STREAM;
2524 snprintf(strport, sizeof strport, "%d", listen_port);
473db5ab 2525 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2526 if (addr == NULL) {
2527 /* This really shouldn't happen */
2528 packet_disconnect("getaddrinfo: fatal error: %s",
e74dc197 2529 ssh_gai_strerror(r));
473db5ab 2530 } else {
2531 error("channel_setup_fwd_listener: "
e74dc197 2532 "getaddrinfo(%.64s): %s", addr,
2533 ssh_gai_strerror(r));
473db5ab 2534 }
2535 return 0;
2536 }
3c0ef626 2537
2538 for (ai = aitop; ai; ai = ai->ai_next) {
2539 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2540 continue;
2541 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2542 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
473db5ab 2543 error("channel_setup_fwd_listener: getnameinfo failed");
3c0ef626 2544 continue;
2545 }
2546 /* Create a port to listen for the host. */
473db5ab 2547 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3c0ef626 2548 if (sock < 0) {
2549 /* this is no error since kernel may not support ipv6 */
2550 verbose("socket: %.100s", strerror(errno));
2551 continue;
2552 }
08822d99 2553
2554 channel_set_reuseaddr(sock);
473db5ab 2555
3c0ef626 2556 debug("Local forwarding listening on %s port %s.", ntop, strport);
2557
2558 /* Bind the socket to the address. */
2559 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2560 /* address can be in use ipv6 address is already bound */
2561 if (!ai->ai_next)
2562 error("bind: %.100s", strerror(errno));
2563 else
2564 verbose("bind: %.100s", strerror(errno));
2565
2566 close(sock);
2567 continue;
2568 }
2569 /* Start listening for connections on the socket. */
473db5ab 2570 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3c0ef626 2571 error("listen: %.100s", strerror(errno));
2572 close(sock);
2573 continue;
2574 }
2575 /* Allocate a channel number for the socket. */
a7213e65 2576 /* explicitly test for hpn disabled option. if true use smaller window size */
2577 if (hpn_disabled)
6df46d40 2578 c = channel_new("port listener", type, sock, sock, -1,
2579 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2580 0, "port listener", 1);
a7213e65 2581 else
2582 c = channel_new("port listener", type, sock, sock, -1,
2583 hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
2584 0, "port listener", 1);
3c0ef626 2585 strlcpy(c->path, host, sizeof(c->path));
2586 c->host_port = port_to_connect;
2587 c->listening_port = listen_port;
2588 success = 1;
2589 }
2590 if (success == 0)
473db5ab 2591 error("channel_setup_fwd_listener: cannot listen to port: %d",
3c0ef626 2592 listen_port);
2593 freeaddrinfo(aitop);
2594 return success;
2595}
2596
473db5ab 2597int
2598channel_cancel_rport_listener(const char *host, u_short port)
2599{
2600 u_int i;
2601 int found = 0;
2602
2603 for (i = 0; i < channels_alloc; i++) {
2604 Channel *c = channels[i];
2605
2606 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2607 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2608 c->listening_port == port) {
2609 debug2("%s: close channel %d", __func__, i);
2610 channel_free(c);
2611 found = 1;
2612 }
2613 }
2614
2615 return (found);
2616}
2617
2618/* protocol local port fwd, used by ssh (and sshd in v1) */
2619int
2620channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
d3057ca4 2621 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
473db5ab 2622{
2623 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2624 listen_host, listen_port, host_to_connect, port_to_connect,
d3057ca4 2625 gateway_ports);
473db5ab 2626}
2627
2628/* protocol v2 remote port fwd, used by sshd */
2629int
2630channel_setup_remote_fwd_listener(const char *listen_address,
d3057ca4 2631 u_short listen_port, int gateway_ports)
473db5ab 2632{
2633 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
d3057ca4 2634 listen_address, listen_port, NULL, 0, gateway_ports);
473db5ab 2635}
2636
3c0ef626 2637/*
2638 * Initiate forwarding of connections to port "port" on remote host through
2639 * the secure channel to host:port from local side.
2640 */
2641
30460aeb 2642int
473db5ab 2643channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
3c0ef626 2644 const char *host_to_connect, u_short port_to_connect)
2645{
473db5ab 2646 int type, success = 0;
3c0ef626 2647
2648 /* Record locally that connection to this host/port is permitted. */
2649 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2650 fatal("channel_request_remote_forwarding: too many forwards");
2651
2652 /* Send the forward request to the remote side. */
2653 if (compat20) {
473db5ab 2654 const char *address_to_bind;
0b90ac93 2655 if (listen_host == NULL) {
2656 if (datafellows & SSH_BUG_RFWD_ADDR)
2657 address_to_bind = "127.0.0.1";
2658 else
2659 address_to_bind = "localhost";
2660 } else if (*listen_host == '\0' ||
2661 strcmp(listen_host, "*") == 0) {
2662 if (datafellows & SSH_BUG_RFWD_ADDR)
2663 address_to_bind = "0.0.0.0";
2664 else
2665 address_to_bind = "";
2666 } else
473db5ab 2667 address_to_bind = listen_host;
2668
3c0ef626 2669 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2670 packet_put_cstring("tcpip-forward");
473db5ab 2671 packet_put_char(1); /* boolean: want reply */
3c0ef626 2672 packet_put_cstring(address_to_bind);
2673 packet_put_int(listen_port);
2674 packet_send();
2675 packet_write_wait();
2676 /* Assume that server accepts the request */
2677 success = 1;
2678 } else {
2679 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2680 packet_put_int(listen_port);
2681 packet_put_cstring(host_to_connect);
2682 packet_put_int(port_to_connect);
2683 packet_send();
2684 packet_write_wait();
2685
2686 /* Wait for response from the remote side. */
473db5ab 2687 type = packet_read();
3c0ef626 2688 switch (type) {
2689 case SSH_SMSG_SUCCESS:
2690 success = 1;
2691 break;
2692 case SSH_SMSG_FAILURE:
3c0ef626 2693 break;
2694 default:
2695 /* Unknown packet */
2696 packet_disconnect("Protocol error for port forward request:"
2697 "received packet type %d.", type);
2698 }
2699 }
2700 if (success) {
2701 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2702 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2703 permitted_opens[num_permitted_opens].listen_port = listen_port;
2704 num_permitted_opens++;
2705 }
30460aeb 2706 return (success ? 0 : -1);
3c0ef626 2707}
2708
473db5ab 2709/*
2710 * Request cancellation of remote forwarding of connection host:port from
2711 * local side.
2712 */
2713void
2714channel_request_rforward_cancel(const char *host, u_short port)
2715{
2716 int i;
2717
2718 if (!compat20)
2719 return;
2720
2721 for (i = 0; i < num_permitted_opens; i++) {
2722 if (permitted_opens[i].host_to_connect != NULL &&
2723 permitted_opens[i].listen_port == port)
2724 break;
2725 }
2726 if (i >= num_permitted_opens) {
2727 debug("%s: requested forward not found", __func__);
2728 return;
2729 }
2730 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2731 packet_put_cstring("cancel-tcpip-forward");
2732 packet_put_char(0);
2733 packet_put_cstring(host == NULL ? "" : host);
2734 packet_put_int(port);
2735 packet_send();
2736
2737 permitted_opens[i].listen_port = 0;
2738 permitted_opens[i].port_to_connect = 0;
08822d99 2739 xfree(permitted_opens[i].host_to_connect);
473db5ab 2740 permitted_opens[i].host_to_connect = NULL;
2741}
2742
3c0ef626 2743/*
2744 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2745 * listening for the port, and sends back a success reply (or disconnect
30460aeb 2746 * message if there was an error).
3c0ef626 2747 */
30460aeb 2748int
d3057ca4 2749channel_input_port_forward_request(int is_root, int gateway_ports)
3c0ef626 2750{
2751 u_short port, host_port;
30460aeb 2752 int success = 0;
3c0ef626 2753 char *hostname;
2754
2755 /* Get arguments from the packet. */
2756 port = packet_get_int();
2757 hostname = packet_get_string(NULL);
2758 host_port = packet_get_int();
2759
2760#ifndef HAVE_CYGWIN
2761 /*
2762 * Check that an unprivileged user is not trying to forward a
2763 * privileged port.
2764 */
2765 if (port < IPPORT_RESERVED && !is_root)
473db5ab 2766 packet_disconnect(
2767 "Requested forwarding of port %d but user is not root.",
2768 port);
2769 if (host_port == 0)
2770 packet_disconnect("Dynamic forwarding denied.");
3c0ef626 2771#endif
473db5ab 2772
3c0ef626 2773 /* Initiate forwarding */
30460aeb 2774 success = channel_setup_local_fwd_listener(NULL, port, hostname,
d3057ca4 2775 host_port, gateway_ports);
3c0ef626 2776
2777 /* Free the argument string. */
2778 xfree(hostname);
30460aeb 2779
2780 return (success ? 0 : -1);
3c0ef626 2781}
2782
2783/*
2784 * Permits opening to any host/port if permitted_opens[] is empty. This is
2785 * usually called by the server, because the user could connect to any port
2786 * anyway, and the server has no way to know but to trust the client anyway.
2787 */
2788void
473db5ab 2789channel_permit_all_opens(void)
3c0ef626 2790{
2791 if (num_permitted_opens == 0)
2792 all_opens_permitted = 1;
2793}
2794
2795void
2796channel_add_permitted_opens(char *host, int port)
2797{
2798 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
30460aeb 2799 fatal("channel_add_permitted_opens: too many forwards");
3c0ef626 2800 debug("allow port forwarding to host %s port %d", host, port);
2801
2802 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2803 permitted_opens[num_permitted_opens].port_to_connect = port;
2804 num_permitted_opens++;
2805
2806 all_opens_permitted = 0;
2807}
2808
30460aeb 2809int
2810channel_add_adm_permitted_opens(char *host, int port)
2811{
2812 if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2813 fatal("channel_add_adm_permitted_opens: too many forwards");
2814 debug("config allows port forwarding to host %s port %d", host, port);
2815
2816 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
2817 = xstrdup(host);
2818 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
2819 return ++num_adm_permitted_opens;
2820}
2821
3c0ef626 2822void
2823channel_clear_permitted_opens(void)
2824{
2825 int i;
2826
2827 for (i = 0; i < num_permitted_opens; i++)
473db5ab 2828 if (permitted_opens[i].host_to_connect != NULL)
2829 xfree(permitted_opens[i].host_to_connect);
3c0ef626 2830 num_permitted_opens = 0;
3c0ef626 2831}
2832
30460aeb 2833void
2834channel_clear_adm_permitted_opens(void)
2835{
2836 int i;
2837
2838 for (i = 0; i < num_adm_permitted_opens; i++)
2839 if (permitted_adm_opens[i].host_to_connect != NULL)
2840 xfree(permitted_adm_opens[i].host_to_connect);
2841 num_adm_permitted_opens = 0;
2842}
3c0ef626 2843
5156b1a1 2844void
2845channel_print_adm_permitted_opens(void)
2846{
2847 int i;
2848
2849 for (i = 0; i < num_adm_permitted_opens; i++)
2850 if (permitted_adm_opens[i].host_to_connect != NULL)
2851 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
2852 permitted_adm_opens[i].port_to_connect);
2853}
2854
2855/* Try to start non-blocking connect to next host in cctx list */
3c0ef626 2856static int
5156b1a1 2857connect_next(struct channel_connect *cctx)
3c0ef626 2858{
5156b1a1 2859 int sock, saved_errno;
3c0ef626 2860 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3c0ef626 2861
5156b1a1 2862 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
2863 if (cctx->ai->ai_family != AF_INET &&
2864 cctx->ai->ai_family != AF_INET6)
3c0ef626 2865 continue;
5156b1a1 2866 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
2867 ntop, sizeof(ntop), strport, sizeof(strport),
2868 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2869 error("connect_next: getnameinfo failed");
3c0ef626 2870 continue;
2871 }
5156b1a1 2872 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
2873 cctx->ai->ai_protocol)) == -1) {
2874 if (cctx->ai->ai_next == NULL)
473db5ab 2875 error("socket: %.100s", strerror(errno));
2876 else
2877 verbose("socket: %.100s", strerror(errno));
3c0ef626 2878 continue;
2879 }
473db5ab 2880 if (set_nonblock(sock) == -1)
2881 fatal("%s: set_nonblock(%d)", __func__, sock);
5156b1a1 2882 if (connect(sock, cctx->ai->ai_addr,
2883 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
2884 debug("connect_next: host %.100s ([%.100s]:%s): "
2885 "%.100s", cctx->host, ntop, strport,
3c0ef626 2886 strerror(errno));
5156b1a1 2887 saved_errno = errno;
3c0ef626 2888 close(sock);
5156b1a1 2889 errno = saved_errno;
3c0ef626 2890 continue; /* fail -- try next */
2891 }
5156b1a1 2892 debug("connect_next: host %.100s ([%.100s]:%s) "
2893 "in progress, fd=%d", cctx->host, ntop, strport, sock);
2894 cctx->ai = cctx->ai->ai_next;
2895 set_nodelay(sock);
2896 return sock;
2897 }
2898 return -1;
2899}
3c0ef626 2900
5156b1a1 2901static void
2902channel_connect_ctx_free(struct channel_connect *cctx)
2903{
2904 xfree(cctx->host);
2905 if (cctx->aitop)
2906 freeaddrinfo(cctx->aitop);
2907 bzero(cctx, sizeof(*cctx));
2908 cctx->host = NULL;
2909 cctx->ai = cctx->aitop = NULL;
2910}
2911
2912/* Return CONNECTING channel to remote host, port */
2913static Channel *
2914connect_to(const char *host, u_short port, char *ctype, char *rname)
2915{
2916 struct addrinfo hints;
2917 int gaierr;
2918 int sock = -1;
2919 char strport[NI_MAXSERV];
2920 struct channel_connect cctx;
2921 Channel *c;
2922
2923 memset(&cctx, 0, sizeof(cctx));
2924 memset(&hints, 0, sizeof(hints));
2925 hints.ai_family = IPv4or6;
2926 hints.ai_socktype = SOCK_STREAM;
2927 snprintf(strport, sizeof strport, "%d", port);
2928 if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
2929 error("connect_to %.100s: unknown host (%s)", host,
2930 ssh_gai_strerror(gaierr));
2931 return NULL;
3c0ef626 2932 }
5156b1a1 2933
2934 cctx.host = xstrdup(host);
2935 cctx.port = port;
2936 cctx.ai = cctx.aitop;
2937
2938 if ((sock = connect_next(&cctx)) == -1) {
2939 error("connect to %.100s port %d failed: %s",
2940 host, port, strerror(errno));
2941 channel_connect_ctx_free(&cctx);
2942 return NULL;
3c0ef626 2943 }
5156b1a1 2944 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
2945 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
2946 c->connect_ctx = cctx;
2947 return c;
3c0ef626 2948}
2949
5156b1a1 2950Channel *
2951channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
3c0ef626 2952{
2953 int i;
2954
5156b1a1 2955 for (i = 0; i < num_permitted_opens; i++) {
473db5ab 2956 if (permitted_opens[i].host_to_connect != NULL &&
5156b1a1 2957 permitted_opens[i].listen_port == listen_port) {
3c0ef626 2958 return connect_to(
2959 permitted_opens[i].host_to_connect,
5156b1a1 2960 permitted_opens[i].port_to_connect, ctype, rname);
2961 }
2962 }
3c0ef626 2963 error("WARNING: Server requests forwarding for unknown listen_port %d",
2964 listen_port);
5156b1a1 2965 return NULL;
3c0ef626 2966}
2967
2968/* Check if connecting to that port is permitted and connect. */
5156b1a1 2969Channel *
2970channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
3c0ef626 2971{
30460aeb 2972 int i, permit, permit_adm = 1;
3c0ef626 2973
2974 permit = all_opens_permitted;
2975 if (!permit) {
2976 for (i = 0; i < num_permitted_opens; i++)
473db5ab 2977 if (permitted_opens[i].host_to_connect != NULL &&
2978 permitted_opens[i].port_to_connect == port &&
3c0ef626 2979 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2980 permit = 1;
30460aeb 2981 }
3c0ef626 2982
30460aeb 2983 if (num_adm_permitted_opens > 0) {
2984 permit_adm = 0;
2985 for (i = 0; i < num_adm_permitted_opens; i++)
2986 if (permitted_adm_opens[i].host_to_connect != NULL &&
2987 permitted_adm_opens[i].port_to_connect == port &&
2988 strcmp(permitted_adm_opens[i].host_to_connect, host)
2989 == 0)
2990 permit_adm = 1;
3c0ef626 2991 }
30460aeb 2992
2993 if (!permit || !permit_adm) {
473db5ab 2994 logit("Received request to connect to host %.100s port %d, "
3c0ef626 2995 "but the request was denied.", host, port);
5156b1a1 2996 return NULL;
3c0ef626 2997 }
5156b1a1 2998 return connect_to(host, port, ctype, rname);
3c0ef626 2999}
3000
473db5ab 3001void
3002channel_send_window_changes(void)
3003{
3004 u_int i;
3005 struct winsize ws;
3006
3007 for (i = 0; i < channels_alloc; i++) {
3008 if (channels[i] == NULL || !channels[i]->client_tty ||
3009 channels[i]->type != SSH_CHANNEL_OPEN)
3010 continue;
3011 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3012 continue;
3013 channel_request_start(i, "window-change", 0);
30460aeb 3014 packet_put_int((u_int)ws.ws_col);
3015 packet_put_int((u_int)ws.ws_row);
3016 packet_put_int((u_int)ws.ws_xpixel);
3017 packet_put_int((u_int)ws.ws_ypixel);
473db5ab 3018 packet_send();
3019 }
3020}
3021
3c0ef626 3022/* -- X11 forwarding */
3023
3024/*
3025 * Creates an internet domain socket for listening for X11 connections.
473db5ab 3026 * Returns 0 and a suitable display number for the DISPLAY variable
3027 * stored in display_numberp , or -1 if an error occurs.
3c0ef626 3028 */
473db5ab 3029int
3030x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
d3057ca4 3031 int single_connection, u_int *display_numberp, int **chanids)
3c0ef626 3032{
473db5ab 3033 Channel *nc = NULL;
3c0ef626 3034 int display_number, sock;
3035 u_short port;
3036 struct addrinfo hints, *ai, *aitop;
3037 char strport[NI_MAXSERV];
3038 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3c0ef626 3039
08822d99 3040 if (chanids == NULL)
3041 return -1;
3042
3c0ef626 3043 for (display_number = x11_display_offset;
473db5ab 3044 display_number < MAX_DISPLAYS;
3045 display_number++) {
3c0ef626 3046 port = 6000 + display_number;
3047 memset(&hints, 0, sizeof(hints));
3048 hints.ai_family = IPv4or6;
473db5ab 3049 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3c0ef626 3050 hints.ai_socktype = SOCK_STREAM;
3051 snprintf(strport, sizeof strport, "%d", port);
3052 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
e74dc197 3053 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
473db5ab 3054 return -1;
3c0ef626 3055 }
3056 for (ai = aitop; ai; ai = ai->ai_next) {
3057 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3058 continue;
473db5ab 3059 sock = socket(ai->ai_family, ai->ai_socktype,
3060 ai->ai_protocol);
3c0ef626 3061 if (sock < 0) {
3062 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
3063 error("socket: %.100s", strerror(errno));
473db5ab 3064 freeaddrinfo(aitop);
3065 return -1;
3c0ef626 3066 } else {
3067 debug("x11_create_display_inet: Socket family %d not supported",
3068 ai->ai_family);
3069 continue;
3070 }
3071 }
473db5ab 3072#ifdef IPV6_V6ONLY
3073 if (ai->ai_family == AF_INET6) {
3074 int on = 1;
3075 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
3076 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
3077 }
3078#endif
5156b1a1 3079 if (x11_use_localhost)
3080 channel_set_reuseaddr(sock);
3c0ef626 3081 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
473db5ab 3082 debug2("bind port %d: %.100s", port, strerror(errno));
3c0ef626 3083 close(sock);
3084
3c0ef626 3085 for (n = 0; n < num_socks; n++) {
3c0ef626 3086 close(socks[n]);
3087 }
3088 num_socks = 0;
3089 break;
3090 }
3091 socks[num_socks++] = sock;
3c0ef626 3092 if (num_socks == NUM_SOCKS)
3093 break;
3c0ef626 3094 }
3095 freeaddrinfo(aitop);
3096 if (num_socks > 0)
3097 break;
3098 }
3099 if (display_number >= MAX_DISPLAYS) {
3100 error("Failed to allocate internet-domain X11 display socket.");
473db5ab 3101 return -1;
3c0ef626 3102 }
3103 /* Start listening for connections on the socket. */
3104 for (n = 0; n < num_socks; n++) {
3105 sock = socks[n];
473db5ab 3106 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3c0ef626 3107 error("listen: %.100s", strerror(errno));
3c0ef626 3108 close(sock);
473db5ab 3109 return -1;
3c0ef626 3110 }
3c0ef626 3111 }
3c0ef626 3112
3113 /* Allocate a channel for each socket. */
30460aeb 3114 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3c0ef626 3115 for (n = 0; n < num_socks; n++) {
3116 sock = socks[n];
6df46d40 3117 /* Is this really necassary? */
a7213e65 3118 if (hpn_disabled)
6df46d40 3119 nc = channel_new("x11 listener",
3120 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3121 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3122 0, "X11 inet listener", 1);
a7213e65 3123 else
3124 nc = channel_new("x11 listener",
3125 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3126 hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
3127 0, "X11 inet listener", 1);
473db5ab 3128 nc->single_connection = single_connection;
08822d99 3129 (*chanids)[n] = nc->self;
3c0ef626 3130 }
08822d99 3131 (*chanids)[n] = -1;
3c0ef626 3132
473db5ab 3133 /* Return the display number for the DISPLAY environment variable. */
3134 *display_numberp = display_number;
3135 return (0);
3c0ef626 3136}
3137
3c0ef626 3138static int
3139connect_local_xsocket(u_int dnr)
3140{
3c0ef626 3141 int sock;
3142 struct sockaddr_un addr;
3c0ef626 3143
473db5ab 3144 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3145 if (sock < 0)
3146 error("socket: %.100s", strerror(errno));
3147 memset(&addr, 0, sizeof(addr));
3148 addr.sun_family = AF_UNIX;
3149 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
30460aeb 3150 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
473db5ab 3151 return sock;
3152 close(sock);
3c0ef626 3153 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3154 return -1;
3155}
3156
3157int
3158x11_connect_display(void)
3159{
30460aeb 3160 u_int display_number;
3c0ef626 3161 const char *display;
3162 char buf[1024], *cp;
3163 struct addrinfo hints, *ai, *aitop;
3164 char strport[NI_MAXSERV];
30460aeb 3165 int gaierr, sock = 0;
3c0ef626 3166
3167 /* Try to open a socket for the local X server. */
3168 display = getenv("DISPLAY");
3169 if (!display) {
3170 error("DISPLAY not set.");
3171 return -1;
3172 }
3173 /*
3174 * Now we decode the value of the DISPLAY variable and make a
3175 * connection to the real X server.
3176 */
3177
3178 /*
3179 * Check if it is a unix domain socket. Unix domain displays are in
3180 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3181 */
3182 if (strncmp(display, "unix:", 5) == 0 ||
3183 display[0] == ':') {
3184 /* Connect to the unix domain socket. */
30460aeb 3185 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3c0ef626 3186 error("Could not parse display number from DISPLAY: %.100s",
473db5ab 3187 display);
3c0ef626 3188 return -1;
3189 }
3190 /* Create a socket. */
3191 sock = connect_local_xsocket(display_number);
3192 if (sock < 0)
3193 return -1;
3194
3195 /* OK, we now have a connection to the display. */
3196 return sock;
3197 }
3198 /*
3199 * Connect to an inet socket. The DISPLAY value is supposedly
3200 * hostname:d[.s], where hostname may also be numeric IP address.
3201 */
473db5ab 3202 strlcpy(buf, display, sizeof(buf));
3c0ef626 3203 cp = strchr(buf, ':');
3204 if (!cp) {
3205 error("Could not find ':' in DISPLAY: %.100s", display);
3206 return -1;
3207 }
3208 *cp = 0;
3209 /* buf now contains the host name. But first we parse the display number. */
30460aeb 3210 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3c0ef626 3211 error("Could not parse display number from DISPLAY: %.100s",
473db5ab 3212 display);
3c0ef626 3213 return -1;
3214 }
3215
3216 /* Look up the host address */
3217 memset(&hints, 0, sizeof(hints));
3218 hints.ai_family = IPv4or6;
3219 hints.ai_socktype = SOCK_STREAM;
30460aeb 3220 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3c0ef626 3221 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
e74dc197 3222 error("%.100s: unknown host. (%s)", buf,
3223 ssh_gai_strerror(gaierr));
3c0ef626 3224 return -1;
3225 }
3226 for (ai = aitop; ai; ai = ai->ai_next) {
3227 /* Create a socket. */
473db5ab 3228 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3c0ef626 3229 if (sock < 0) {
473db5ab 3230 debug2("socket: %.100s", strerror(errno));
3c0ef626 3231 continue;
3232 }
3233 /* Connect it to the display. */
3234 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
30460aeb 3235 debug2("connect %.100s port %u: %.100s", buf,
3c0ef626 3236 6000 + display_number, strerror(errno));
3237 close(sock);
3238 continue;
3239 }
3240 /* Success */
3241 break;
3242 }
3243 freeaddrinfo(aitop);
3244 if (!ai) {
30460aeb 3245 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3c0ef626 3246 strerror(errno));
3247 return -1;
3248 }
473db5ab 3249 set_nodelay(sock);
3c0ef626 3250 return sock;
3251}
3252
3253/*
3254 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3255 * the remote channel number. We should do whatever we want, and respond
3256 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3257 */
3258
30460aeb 3259/* ARGSUSED */
3c0ef626 3260void
473db5ab 3261x11_input_open(int type, u_int32_t seq, void *ctxt)
3c0ef626 3262{
3263 Channel *c = NULL;
3264 int remote_id, sock = 0;
3265 char *remote_host;
3266
3267 debug("Received X11 open request.");
3268
3269 remote_id = packet_get_int();
3270
3271 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3272 remote_host = packet_get_string(NULL);
3273 } else {
3274 remote_host = xstrdup("unknown (remote did not supply name)");
3275 }
473db5ab 3276 packet_check_eom();
3c0ef626 3277
3278 /* Obtain a connection to the real X display. */
3279 sock = x11_connect_display();
3280 if (sock != -1) {
3281 /* Allocate a channel for this connection. */
3282 c = channel_new("connected x11 socket",
3283 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3284 remote_host, 1);
473db5ab 3285 c->remote_id = remote_id;
3286 c->force_drain = 1;
3c0ef626 3287 }
473db5ab 3288 xfree(remote_host);
3c0ef626 3289 if (c == NULL) {
3290 /* Send refusal to the remote host. */
3291 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3292 packet_put_int(remote_id);
3293 } else {
3294 /* Send a confirmation to the remote host. */
3295 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3296 packet_put_int(remote_id);
3297 packet_put_int(c->self);
3298 }
3299 packet_send();
3300}
3301
3302/* dummy protocol handler that denies SSH-1 requests (agent/x11) */
30460aeb 3303/* ARGSUSED */
3c0ef626 3304void
473db5ab 3305deny_input_open(int type, u_int32_t seq, void *ctxt)
3c0ef626 3306{
3307 int rchan = packet_get_int();
473db5ab 3308
3309 switch (type) {
3c0ef626 3310 case SSH_SMSG_AGENT_OPEN:
3311 error("Warning: ssh server tried agent forwarding.");
3312 break;
3313 case SSH_SMSG_X11_OPEN:
3314 error("Warning: ssh server tried X11 forwarding.");
3315 break;
3316 default:
473db5ab 3317 error("deny_input_open: type %d", type);
3c0ef626 3318 break;
3319 }
08822d99 3320 error("Warning: this is probably a break-in attempt by a malicious server.");
3c0ef626 3321 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3322 packet_put_int(rchan);
3323 packet_send();
3324}
3325
3326/*
3327 * Requests forwarding of X11 connections, generates fake authentication
3328 * data, and enables authentication spoofing.
3329 * This should be called in the client only.
3330 */
3331void
473db5ab 3332x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3c0ef626 3333 const char *proto, const char *data)
3334{
3335 u_int data_len = (u_int) strlen(data) / 2;
473db5ab 3336 u_int i, value;
3c0ef626 3337 char *new_data;
3338 int screen_number;
3339 const char *cp;
473db5ab 3340 u_int32_t rnd = 0;
3c0ef626 3341
473db5ab 3342 if (x11_saved_display == NULL)
3343 x11_saved_display = xstrdup(disp);
3344 else if (strcmp(disp, x11_saved_display) != 0) {
3345 error("x11_request_forwarding_with_spoofing: different "
3346 "$DISPLAY already forwarded");
3347 return;
3348 }
3349
30460aeb 3350 cp = strchr(disp, ':');
3c0ef626 3351 if (cp)
3352 cp = strchr(cp, '.');
3353 if (cp)
30460aeb 3354 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3c0ef626 3355 else
3356 screen_number = 0;
3357
473db5ab 3358 if (x11_saved_proto == NULL) {
3359 /* Save protocol name. */
3360 x11_saved_proto = xstrdup(proto);
3361 /*
3362 * Extract real authentication data and generate fake data
3363 * of the same length.
3364 */
3365 x11_saved_data = xmalloc(data_len);
3366 x11_fake_data = xmalloc(data_len);
3367 for (i = 0; i < data_len; i++) {
3368 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3369 fatal("x11_request_forwarding: bad "
3370 "authentication data: %.100s", data);
3371 if (i % 4 == 0)
3372 rnd = arc4random();
3373 x11_saved_data[i] = value;
3374 x11_fake_data[i] = rnd & 0xff;
3375 rnd >>= 8;
3376 }
3377 x11_saved_data_len = data_len;
3378 x11_fake_data_len = data_len;
3379 }
3c0ef626 3380
3381 /* Convert the fake data into hex. */
473db5ab 3382 new_data = tohex(x11_fake_data, data_len);
3c0ef626 3383
3384 /* Send the request packet. */
3385 if (compat20) {
3386 channel_request_start(client_session_id, "x11-req", 0);
3387 packet_put_char(0); /* XXX bool single connection */
3388 } else {
3389 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3390 }
3391 packet_put_cstring(proto);
3392 packet_put_cstring(new_data);
3393 packet_put_int(screen_number);
3394 packet_send();
3395 packet_write_wait();
3396 xfree(new_data);
3397}
3398
3399
3400/* -- agent forwarding */
3401
3402/* Sends a message to the server to request authentication fd forwarding. */
3403
3404void
473db5ab 3405auth_request_forwarding(void)
3c0ef626 3406{
3407 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3408 packet_send();
3409 packet_write_wait();
3410}
This page took 0.798496 seconds and 5 git commands to generate.