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