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