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