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