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