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