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