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