]> andersk Git - openssh.git/blob - channels.c
a67615b3c3147d85e2d18a02a6f07a7b195730e9
[openssh.git] / channels.c
1 /*
2  *
3  * channels.c
4  *
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  *
7  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8  *                    All rights reserved
9  *
10  * Created: Fri Mar 24 16:35:24 1995 ylo
11  *
12  * This file contains functions for generic socket connection forwarding.
13  * There is also code for initiating connection forwarding for X11 connections,
14  * arbitrary tcp/ip connections, and the authentication agent connection.
15  *
16  * SSH2 support added by Markus Friedl.
17  */
18
19 #include "includes.h"
20 RCSID("$Id$");
21
22 #include "ssh.h"
23 #include "packet.h"
24 #include "xmalloc.h"
25 #include "buffer.h"
26 #include "authfd.h"
27 #include "uidswap.h"
28 #include "readconf.h"
29 #include "servconf.h"
30
31 #include "channels.h"
32 #include "nchan.h"
33 #include "compat.h"
34
35 #include "ssh2.h"
36
37 /* Maximum number of fake X11 displays to try. */
38 #define MAX_DISPLAYS  1000
39
40 /* Max len of agent socket */
41 #define MAX_SOCKET_NAME 100
42
43 /* default buffer for tcp-fwd-channel */
44 #define CHAN_WINDOW_DEFAULT      (8*1024)
45 #define CHAN_PACKET_DEFAULT      (CHAN_WINDOW_DEFAULT/2)
46
47 /*
48  * Pointer to an array containing all allocated channels.  The array is
49  * dynamically extended as needed.
50  */
51 static Channel *channels = NULL;
52
53 /*
54  * Size of the channel array.  All slots of the array must always be
55  * initialized (at least the type field); unused slots are marked with type
56  * SSH_CHANNEL_FREE.
57  */
58 static int channels_alloc = 0;
59
60 /*
61  * Maximum file descriptor value used in any of the channels.  This is
62  * updated in channel_allocate.
63  */
64 static int channel_max_fd_value = 0;
65
66 /* Name and directory of socket for authentication agent forwarding. */
67 static char *channel_forwarded_auth_socket_name = NULL;
68 static char *channel_forwarded_auth_socket_dir = NULL;
69
70 /* Saved X11 authentication protocol name. */
71 char *x11_saved_proto = NULL;
72
73 /* Saved X11 authentication data.  This is the real data. */
74 char *x11_saved_data = NULL;
75 unsigned int x11_saved_data_len = 0;
76
77 /*
78  * Fake X11 authentication data.  This is what the server will be sending us;
79  * we should replace any occurrences of this by the real data.
80  */
81 char *x11_fake_data = NULL;
82 unsigned int x11_fake_data_len;
83
84 /*
85  * Data structure for storing which hosts are permitted for forward requests.
86  * The local sides of any remote forwards are stored in this array to prevent
87  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
88  * network (which might be behind a firewall).
89  */
90 typedef struct {
91         char *host_to_connect;          /* Connect to 'host'. */
92         u_short port_to_connect;        /* Connect to 'port'. */
93         u_short listen_port;            /* Remote side should listen port number. */
94 } ForwardPermission;
95
96 /* List of all permitted host/port pairs to connect. */
97 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
98 /* Number of permitted host/port pairs in the array. */
99 static int num_permitted_opens = 0;
100 /*
101  * If this is true, all opens are permitted.  This is the case on the server
102  * on which we have to trust the client anyway, and the user could do
103  * anything after logging in anyway.
104  */
105 static int all_opens_permitted = 0;
106
107 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
108 static int have_hostname_in_open = 0;
109
110 /* Sets specific protocol options. */
111
112 void
113 channel_set_options(int hostname_in_open)
114 {
115         have_hostname_in_open = hostname_in_open;
116 }
117
118 /*
119  * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
120  * called by the server, because the user could connect to any port anyway,
121  * and the server has no way to know but to trust the client anyway.
122  */
123
124 void
125 channel_permit_all_opens()
126 {
127         all_opens_permitted = 1;
128 }
129
130 /* lookup channel by id */
131
132 Channel *
133 channel_lookup(int id)
134 {
135         Channel *c;
136         if (id < 0 && id > channels_alloc) {
137                 log("channel_lookup: %d: bad id", id);
138                 return NULL;
139         }
140         c = &channels[id];
141         if (c->type == SSH_CHANNEL_FREE) {
142                 log("channel_lookup: %d: bad id: channel free", id);
143                 return NULL;
144         }
145         return c;
146 }
147
148 /*
149  * Allocate a new channel object and set its type and socket. This will cause
150  * remote_name to be freed.
151  */
152
153 int
154 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
155     int window, int maxpack, int extended_usage, char *remote_name)
156 {
157         int i, found;
158         Channel *c;
159
160         /* Update the maximum file descriptor value. */
161         if (rfd > channel_max_fd_value)
162                 channel_max_fd_value = rfd;
163         if (wfd > channel_max_fd_value)
164                 channel_max_fd_value = wfd;
165         if (efd > channel_max_fd_value)
166                 channel_max_fd_value = efd;
167         /* XXX set close-on-exec -markus */
168
169         /* Do initial allocation if this is the first call. */
170         if (channels_alloc == 0) {
171                 chan_init();
172                 channels_alloc = 10;
173                 channels = xmalloc(channels_alloc * sizeof(Channel));
174                 for (i = 0; i < channels_alloc; i++)
175                         channels[i].type = SSH_CHANNEL_FREE;
176                 /*
177                  * Kludge: arrange a call to channel_stop_listening if we
178                  * terminate with fatal().
179                  */
180                 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
181         }
182         /* Try to find a free slot where to put the new channel. */
183         for (found = -1, i = 0; i < channels_alloc; i++)
184                 if (channels[i].type == SSH_CHANNEL_FREE) {
185                         /* Found a free slot. */
186                         found = i;
187                         break;
188                 }
189         if (found == -1) {
190                 /* There are no free slots.  Take last+1 slot and expand the array.  */
191                 found = channels_alloc;
192                 channels_alloc += 10;
193                 debug("channel: expanding %d", channels_alloc);
194                 channels = xrealloc(channels, channels_alloc * sizeof(Channel));
195                 for (i = found; i < channels_alloc; i++)
196                         channels[i].type = SSH_CHANNEL_FREE;
197         }
198         /* Initialize and return new channel number. */
199         c = &channels[found];
200         buffer_init(&c->input);
201         buffer_init(&c->output);
202         buffer_init(&c->extended);
203         chan_init_iostates(c);
204         c->self = found;
205         c->type = type;
206         c->ctype = ctype;
207         c->local_window = window;
208         c->local_window_max = window;
209         c->local_consumed = 0;
210         c->local_maxpacket = maxpack;
211         c->remote_window = 0;
212         c->remote_maxpacket = 0;
213         c->rfd = rfd;
214         c->wfd = wfd;
215         c->sock = (rfd == wfd) ? rfd : -1;
216         c->efd = efd;
217         c->extended_usage = extended_usage;
218         c->remote_id = -1;
219         c->remote_name = remote_name;
220         c->remote_window = 0;
221         c->remote_maxpacket = 0;
222         c->cb_fn = NULL;
223         c->cb_arg = NULL;
224         c->cb_event = 0;
225         c->dettach_user = NULL;
226         debug("channel %d: new [%s]", found, remote_name);
227         return found;
228 }
229 int
230 channel_allocate(int type, int sock, char *remote_name)
231 {
232         return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
233 }
234
235 /* Free the channel and close its socket. */
236
237 void
238 channel_free(int id)
239 {
240         Channel *c = channel_lookup(id);
241         if (c == NULL)
242                 packet_disconnect("channel free: bad local channel %d", id);
243         debug("channel_free: channel %d: status: %s", id, channel_open_message());
244         if (c->dettach_user != NULL) {
245                 debug("channel_free: channel %d: dettaching channel user", id);
246                 c->dettach_user(c->self, NULL);
247         }
248         if (c->sock != -1) {
249                 shutdown(c->sock, SHUT_RDWR);
250                 close(c->sock);
251                 c->sock = -1;
252         }
253         if (compat20) {
254                 if (c->rfd != -1) {
255                         close(c->rfd);
256                         c->rfd = -1;
257                 }
258                 if (c->wfd != -1) {
259                         close(c->wfd);
260                         c->wfd = -1;
261                 }
262                 if (c->efd != -1) {
263                         close(c->efd);
264                         c->efd = -1;
265                 }
266         }
267         buffer_free(&c->input);
268         buffer_free(&c->output);
269         buffer_free(&c->extended);
270         c->type = SSH_CHANNEL_FREE;
271         if (c->remote_name) {
272                 xfree(c->remote_name);
273                 c->remote_name = NULL;
274         }
275 }
276
277 /*
278  * 'channel_pre*' are called just before select() to add any bits relevant to
279  * channels in the select bitmasks.
280  */
281 /*
282  * 'channel_post*': perform any appropriate operations for channels which
283  * have events pending.
284  */
285 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
286 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
287 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
288
289 void
290 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
291 {
292         FD_SET(c->sock, readset);
293 }
294
295 void
296 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
297 {
298         if (buffer_len(&c->input) < packet_get_maxsize())
299                 FD_SET(c->sock, readset);
300         if (buffer_len(&c->output) > 0)
301                 FD_SET(c->sock, writeset);
302 }
303
304 void
305 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
306 {
307         /* test whether sockets are 'alive' for read/write */
308         if (c->istate == CHAN_INPUT_OPEN)
309                 if (buffer_len(&c->input) < packet_get_maxsize())
310                         FD_SET(c->sock, readset);
311         if (c->ostate == CHAN_OUTPUT_OPEN ||
312             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
313                 if (buffer_len(&c->output) > 0) {
314                         FD_SET(c->sock, writeset);
315                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
316                         chan_obuf_empty(c);
317                 }
318         }
319 }
320
321 void
322 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
323 {
324         if (c->istate == CHAN_INPUT_OPEN &&
325             c->remote_window > 0 &&
326             buffer_len(&c->input) < c->remote_window)
327                 FD_SET(c->rfd, readset);
328         if (c->ostate == CHAN_OUTPUT_OPEN ||
329             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
330                 if (buffer_len(&c->output) > 0) {
331                         FD_SET(c->wfd, writeset);
332                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
333                         chan_obuf_empty(c);
334                 }
335         }
336         /** XXX check close conditions, too */
337         if (c->efd != -1) {
338                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
339                     buffer_len(&c->extended) > 0)
340                         FD_SET(c->efd, writeset);
341                 else if (c->extended_usage == CHAN_EXTENDED_READ &&
342                     buffer_len(&c->extended) < c->remote_window)
343                         FD_SET(c->efd, readset);
344         }
345 }
346
347 void
348 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
349 {
350         if (buffer_len(&c->input) == 0) {
351                 packet_start(SSH_MSG_CHANNEL_CLOSE);
352                 packet_put_int(c->remote_id);
353                 packet_send();
354                 c->type = SSH_CHANNEL_CLOSED;
355                 debug("Closing channel %d after input drain.", c->self);
356         }
357 }
358
359 void
360 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
361 {
362         if (buffer_len(&c->output) == 0)
363                 channel_free(c->self);
364         else
365                 FD_SET(c->sock, writeset);
366 }
367
368 /*
369  * This is a special state for X11 authentication spoofing.  An opened X11
370  * connection (when authentication spoofing is being done) remains in this
371  * state until the first packet has been completely read.  The authentication
372  * data in that packet is then substituted by the real data if it matches the
373  * fake data, and the channel is put into normal mode.
374  */
375 int
376 x11_open_helper(Channel *c)
377 {
378         unsigned char *ucp;
379         unsigned int proto_len, data_len;
380
381         /* Check if the fixed size part of the packet is in buffer. */
382         if (buffer_len(&c->output) < 12)
383                 return 0;
384
385         /* Parse the lengths of variable-length fields. */
386         ucp = (unsigned char *) buffer_ptr(&c->output);
387         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
388                 proto_len = 256 * ucp[6] + ucp[7];
389                 data_len = 256 * ucp[8] + ucp[9];
390         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
391                 proto_len = ucp[6] + 256 * ucp[7];
392                 data_len = ucp[8] + 256 * ucp[9];
393         } else {
394                 debug("Initial X11 packet contains bad byte order byte: 0x%x",
395                       ucp[0]);
396                 return -1;
397         }
398
399         /* Check if the whole packet is in buffer. */
400         if (buffer_len(&c->output) <
401             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
402                 return 0;
403
404         /* Check if authentication protocol matches. */
405         if (proto_len != strlen(x11_saved_proto) ||
406             memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
407                 debug("X11 connection uses different authentication protocol.");
408                 return -1;
409         }
410         /* Check if authentication data matches our fake data. */
411         if (data_len != x11_fake_data_len ||
412             memcmp(ucp + 12 + ((proto_len + 3) & ~3),
413                 x11_fake_data, x11_fake_data_len) != 0) {
414                 debug("X11 auth data does not match fake data.");
415                 return -1;
416         }
417         /* Check fake data length */
418         if (x11_fake_data_len != x11_saved_data_len) {
419                 error("X11 fake_data_len %d != saved_data_len %d",
420                     x11_fake_data_len, x11_saved_data_len);
421                 return -1;
422         }
423         /*
424          * Received authentication protocol and data match
425          * our fake data. Substitute the fake data with real
426          * data.
427          */
428         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
429             x11_saved_data, x11_saved_data_len);
430         return 1;
431 }
432
433 void
434 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
435 {
436         int ret = x11_open_helper(c);
437         if (ret == 1) {
438                 /* Start normal processing for the channel. */
439                 c->type = SSH_CHANNEL_OPEN;
440                 channel_pre_open_13(c, readset, writeset);
441         } else if (ret == -1) {
442                 /*
443                  * We have received an X11 connection that has bad
444                  * authentication information.
445                  */
446                 log("X11 connection rejected because of wrong authentication.\r\n");
447                 buffer_clear(&c->input);
448                 buffer_clear(&c->output);
449                 close(c->sock);
450                 c->sock = -1;
451                 c->type = SSH_CHANNEL_CLOSED;
452                 packet_start(SSH_MSG_CHANNEL_CLOSE);
453                 packet_put_int(c->remote_id);
454                 packet_send();
455         }
456 }
457
458 void
459 channel_pre_x11_open_15(Channel *c, fd_set * readset, fd_set * writeset)
460 {
461         int ret = x11_open_helper(c);
462         if (ret == 1) {
463                 c->type = SSH_CHANNEL_OPEN;
464                 channel_pre_open_15(c, readset, writeset);
465         } else if (ret == -1) {
466                 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
467                 chan_read_failed(c);
468                 chan_write_failed(c);
469                 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
470         }
471 }
472
473 /* This is our fake X11 server socket. */
474 void
475 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
476 {
477         struct sockaddr addr;
478         int newsock, newch;
479         socklen_t addrlen;
480         char buf[16384], *remote_hostname;
481
482         if (FD_ISSET(c->sock, readset)) {
483                 debug("X11 connection requested.");
484                 addrlen = sizeof(addr);
485                 newsock = accept(c->sock, &addr, &addrlen);
486                 if (newsock < 0) {
487                         error("accept: %.100s", strerror(errno));
488                         return;
489                 }
490                 remote_hostname = get_remote_hostname(newsock);
491                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
492                 remote_hostname, get_peer_port(newsock));
493                 xfree(remote_hostname);
494                 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
495                                          xstrdup(buf));
496                 packet_start(SSH_SMSG_X11_OPEN);
497                 packet_put_int(newch);
498                 if (have_hostname_in_open)
499                         packet_put_string(buf, strlen(buf));
500                 packet_send();
501         }
502 }
503
504 /*
505  * This socket is listening for connections to a forwarded TCP/IP port.
506  */
507 void
508 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
509 {
510         struct sockaddr addr;
511         int newsock, newch;
512         socklen_t addrlen;
513         char buf[1024], *remote_hostname;
514         int remote_port;
515
516         if (FD_ISSET(c->sock, readset)) {
517                 debug("Connection to port %d forwarding "
518                     "to %.100s port %d requested.",
519                     c->listening_port, c->path, c->host_port);
520                 addrlen = sizeof(addr);
521                 newsock = accept(c->sock, &addr, &addrlen);
522                 if (newsock < 0) {
523                         error("accept: %.100s", strerror(errno));
524                         return;
525                 }
526                 remote_hostname = get_remote_hostname(newsock);
527                 remote_port = get_peer_port(newsock);
528                 snprintf(buf, sizeof buf,
529                     "listen port %d for %.100s port %d, "
530                     "connect from %.200s port %d",
531                     c->listening_port, c->path, c->host_port,
532                     remote_hostname, remote_port);
533                 newch = channel_new("direct-tcpip",
534                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
535                     c->local_window_max, c->local_maxpacket,
536                     0, xstrdup(buf));
537                 if (compat20) {
538                         packet_start(SSH2_MSG_CHANNEL_OPEN);
539                         packet_put_cstring("direct-tcpip");
540                         packet_put_int(newch);
541                         packet_put_int(c->local_window_max);
542                         packet_put_int(c->local_maxpacket);
543                         /* target host and port */
544                         packet_put_string(c->path, strlen(c->path));
545                         packet_put_int(c->host_port);
546                         /* originator host and port */
547                         packet_put_cstring(remote_hostname);
548                         packet_put_int(remote_port);
549                         packet_send();
550                 } else {
551                         packet_start(SSH_MSG_PORT_OPEN);
552                         packet_put_int(newch);
553                         packet_put_string(c->path, strlen(c->path));
554                         packet_put_int(c->host_port);
555                         if (have_hostname_in_open) {
556                                 packet_put_string(buf, strlen(buf));
557                         }
558                         packet_send();
559                 }
560                 xfree(remote_hostname);
561         }
562 }
563
564 /*
565  * This is the authentication agent socket listening for connections from
566  * clients.
567  */
568 void
569 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
570 {
571         struct sockaddr addr;
572         int newsock, newch;
573         socklen_t addrlen;
574
575         if (FD_ISSET(c->sock, readset)) {
576                 addrlen = sizeof(addr);
577                 newsock = accept(c->sock, &addr, &addrlen);
578                 if (newsock < 0) {
579                         error("accept from auth socket: %.100s", strerror(errno));
580                         return;
581                 }
582                 newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
583                     xstrdup("accepted auth socket"));
584                 packet_start(SSH_SMSG_AGENT_OPEN);
585                 packet_put_int(newch);
586                 packet_send();
587         }
588 }
589
590 int
591 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
592 {
593         char buf[16*1024];
594         int len;
595
596         if (c->rfd != -1 &&
597             FD_ISSET(c->rfd, readset)) {
598                 len = read(c->rfd, buf, sizeof(buf));
599                 if (len <= 0) {
600                         debug("channel %d: read<0 rfd %d len %d",
601                             c->self, c->rfd, len);
602                         if (compat13) {
603                                 buffer_consume(&c->output, buffer_len(&c->output));
604                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
605                                 debug("Channel %d status set to input draining.", c->self);
606                         } else {
607                                 chan_read_failed(c);
608                         }
609                         return -1;
610                 }
611                 buffer_append(&c->input, buf, len);
612         }
613         return 1;
614 }
615 int
616 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
617 {
618         int len;
619
620         /* Send buffered output data to the socket. */
621         if (c->wfd != -1 &&
622             FD_ISSET(c->wfd, writeset) &&
623             buffer_len(&c->output) > 0) {
624                 len = write(c->wfd, buffer_ptr(&c->output),
625                             buffer_len(&c->output));
626                 if (len <= 0) {
627                         if (compat13) {
628                                 buffer_consume(&c->output, buffer_len(&c->output));
629                                 debug("Channel %d status set to input draining.", c->self);
630                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
631                         } else {
632                                 chan_write_failed(c);
633                         }
634                         return -1;
635                 }
636                 buffer_consume(&c->output, len);
637                 if (compat20 && len > 0) {
638                         c->local_consumed += len;
639                 }
640         }
641         return 1;
642 }
643 int
644 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
645 {
646         char buf[16*1024];
647         int len;
648
649 /** XXX handle drain efd, too */
650         if (c->efd != -1) {
651                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
652                     FD_ISSET(c->efd, writeset) &&
653                     buffer_len(&c->extended) > 0) {
654                         len = write(c->efd, buffer_ptr(&c->extended),
655                             buffer_len(&c->extended));
656                         debug("channel %d: written %d to efd %d",
657                             c->self, len, c->efd);
658                         if (len > 0) {
659                                 buffer_consume(&c->extended, len);
660                                 c->local_consumed += len;
661                         }
662                 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
663                     FD_ISSET(c->efd, readset)) {
664                         len = read(c->efd, buf, sizeof(buf));
665                         debug("channel %d: read %d from efd %d",
666                              c->self, len, c->efd);
667                         if (len == 0) {
668                                 debug("channel %d: closing efd %d",
669                                     c->self, c->efd);
670                                 close(c->efd);
671                                 c->efd = -1;
672                         } else if (len > 0)
673                                 buffer_append(&c->extended, buf, len);
674                 }
675         }
676         return 1;
677 }
678 int
679 channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
680 {
681         if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
682             c->local_window < c->local_window_max/2 &&
683             c->local_consumed > 0) {
684                 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
685                 packet_put_int(c->remote_id);
686                 packet_put_int(c->local_consumed);
687                 packet_send();
688                 debug("channel %d: window %d sent adjust %d",
689                     c->self, c->local_window,
690                     c->local_consumed);
691                 c->local_window += c->local_consumed;
692                 c->local_consumed = 0;
693         }
694         return 1;
695 }
696
697 void
698 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
699 {
700         channel_handle_rfd(c, readset, writeset);
701         channel_handle_wfd(c, readset, writeset);
702 }
703
704 void
705 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
706 {
707         channel_handle_rfd(c, readset, writeset);
708         channel_handle_wfd(c, readset, writeset);
709         channel_handle_efd(c, readset, writeset);
710         channel_check_window(c, readset, writeset);
711 }
712
713 void
714 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
715 {
716         int len;
717         /* Send buffered output data to the socket. */
718         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
719                 len = write(c->sock, buffer_ptr(&c->output),
720                             buffer_len(&c->output));
721                 if (len <= 0)
722                         buffer_consume(&c->output, buffer_len(&c->output));
723                 else
724                         buffer_consume(&c->output, len);
725         }
726 }
727
728 void
729 channel_handler_init_20(void)
730 {
731         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_20;
732         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
733
734         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_2;
735         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
736 }
737
738 void
739 channel_handler_init_13(void)
740 {
741         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
742         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
743         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
744         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
745         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
746         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
747         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
748
749         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
750         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
751         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
752         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
753         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
754 }
755
756 void
757 channel_handler_init_15(void)
758 {
759         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_15;
760         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_15;
761         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
762         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
763         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
764
765         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
766         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
767         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
768         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open_1;
769 }
770
771 void
772 channel_handler_init(void)
773 {
774         int i;
775         for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
776                 channel_pre[i] = NULL;
777                 channel_post[i] = NULL;
778         }
779         if (compat20)
780                 channel_handler_init_20();
781         else if (compat13)
782                 channel_handler_init_13();
783         else
784                 channel_handler_init_15();
785 }
786
787 void
788 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
789 {
790         static int did_init = 0;
791         int i;
792         Channel *c;
793
794         if (!did_init) {
795                 channel_handler_init();
796                 did_init = 1;
797         }
798         for (i = 0; i < channels_alloc; i++) {
799                 c = &channels[i];
800                 if (c->type == SSH_CHANNEL_FREE)
801                         continue;
802                 if (ftab[c->type] == NULL)
803                         continue;
804                 (*ftab[c->type])(c, readset, writeset);
805                 chan_delete_if_full_closed(c);
806         }
807 }
808
809 void
810 channel_prepare_select(fd_set * readset, fd_set * writeset)
811 {
812         channel_handler(channel_pre, readset, writeset);
813 }
814
815 void
816 channel_after_select(fd_set * readset, fd_set * writeset)
817 {
818         channel_handler(channel_post, readset, writeset);
819 }
820
821 /* If there is data to send to the connection, send some of it now. */
822
823 void
824 channel_output_poll()
825 {
826         int len, i;
827         Channel *c;
828
829         for (i = 0; i < channels_alloc; i++) {
830                 c = &channels[i];
831
832                 /* We are only interested in channels that can have buffered incoming data. */
833                 if (compat13) {
834                         if (c->type != SSH_CHANNEL_OPEN &&
835                             c->type != SSH_CHANNEL_INPUT_DRAINING)
836                                 continue;
837                 } else {
838                         if (c->type != SSH_CHANNEL_OPEN)
839                                 continue;
840                         if (c->istate != CHAN_INPUT_OPEN &&
841                             c->istate != CHAN_INPUT_WAIT_DRAIN)
842                                 continue;
843                 }
844                 if (compat20 &&
845                     (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
846                         debug("channel: %d: no data after CLOSE", c->self);
847                         continue;
848                 }
849
850                 /* Get the amount of buffered data for this channel. */
851                 len = buffer_len(&c->input);
852                 if (len > 0) {
853                         /* Send some data for the other side over the secure connection. */
854                         if (compat20) {
855                                 if (len > c->remote_window)
856                                         len = c->remote_window;
857                                 if (len > c->remote_maxpacket)
858                                         len = c->remote_maxpacket;
859                         } else {
860                                 if (packet_is_interactive()) {
861                                         if (len > 1024)
862                                                 len = 512;
863                                 } else {
864                                         /* Keep the packets at reasonable size. */
865                                         if (len > packet_get_maxsize()/2)
866                                                 len = packet_get_maxsize()/2;
867                                 }
868                         }
869                         if (len > 0) {
870                                 packet_start(compat20 ?
871                                     SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
872                                 packet_put_int(c->remote_id);
873                                 packet_put_string(buffer_ptr(&c->input), len);
874                                 packet_send();
875                                 buffer_consume(&c->input, len);
876                                 c->remote_window -= len;
877                                 debug("channel %d: send data len %d", c->self, len);
878                         }
879                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
880                         if (compat13)
881                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
882                         /*
883                          * input-buffer is empty and read-socket shutdown:
884                          * tell peer, that we will not send more data: send IEOF
885                          */
886                         chan_ibuf_empty(c);
887                 }
888                 /* Send extended data, i.e. stderr */
889                 if (compat20 &&
890                     c->remote_window > 0 &&
891                     (len = buffer_len(&c->extended)) > 0 &&
892                     c->extended_usage == CHAN_EXTENDED_READ) {
893                         if (len > c->remote_window)
894                                 len = c->remote_window;
895                         if (len > c->remote_maxpacket)
896                                 len = c->remote_maxpacket;
897                         packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
898                         packet_put_int(c->remote_id);
899                         packet_put_int(SSH2_EXTENDED_DATA_STDERR);
900                         packet_put_string(buffer_ptr(&c->extended), len);
901                         packet_send();
902                         buffer_consume(&c->extended, len);
903                         c->remote_window -= len;
904                 }
905         }
906 }
907
908 /*
909  * This is called when a packet of type CHANNEL_DATA has just been received.
910  * The message type has already been consumed, but channel number and data is
911  * still there.
912  */
913
914 void
915 channel_input_data(int type, int plen)
916 {
917         int id;
918         char *data;
919         unsigned int data_len;
920         Channel *c;
921
922         /* Get the channel number and verify it. */
923         id = packet_get_int();
924         c = channel_lookup(id);
925         if (c == NULL)
926                 packet_disconnect("Received data for nonexistent channel %d.", id);
927
928         /* Ignore any data for non-open channels (might happen on close) */
929         if (c->type != SSH_CHANNEL_OPEN &&
930             c->type != SSH_CHANNEL_X11_OPEN)
931                 return;
932
933         /* same for protocol 1.5 if output end is no longer open */
934         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
935                 return;
936
937         /* Get the data. */
938         data = packet_get_string(&data_len);
939         packet_done();
940
941         if (compat20){
942                 if (data_len > c->local_maxpacket) {
943                         log("channel %d: rcvd big packet %d, maxpack %d",
944                             c->self, data_len, c->local_maxpacket);
945                 }
946                 if (data_len > c->local_window) {
947                         log("channel %d: rcvd too much data %d, win %d",
948                             c->self, data_len, c->local_window);
949                         xfree(data);
950                         return;
951                 }
952                 c->local_window -= data_len;
953         }else{
954                 packet_integrity_check(plen, 4 + 4 + data_len, type);
955         }
956         buffer_append(&c->output, data, data_len);
957         xfree(data);
958 }
959 void
960 channel_input_extended_data(int type, int plen)
961 {
962         int id;
963         int tcode;
964         char *data;
965         unsigned int data_len;
966         Channel *c;
967
968         /* Get the channel number and verify it. */
969         id = packet_get_int();
970         c = channel_lookup(id);
971
972         if (c == NULL)
973                 packet_disconnect("Received extended_data for bad channel %d.", id);
974         if (c->type != SSH_CHANNEL_OPEN) {
975                 log("channel %d: ext data for non open", id);
976                 return;
977         }
978         tcode = packet_get_int();
979         if (c->efd == -1 ||
980             c->extended_usage != CHAN_EXTENDED_WRITE ||
981             tcode != SSH2_EXTENDED_DATA_STDERR) {
982                 log("channel %d: bad ext data", c->self);
983                 return;
984         }
985         data = packet_get_string(&data_len);
986         packet_done();
987         if (data_len > c->local_window) {
988                 log("channel %d: rcvd too much extended_data %d, win %d",
989                     c->self, data_len, c->local_window);
990                 xfree(data);
991                 return;
992         }
993         debug("channel %d: rcvd ext data %d", c->self, data_len);
994         c->local_window -= data_len;
995         buffer_append(&c->extended, data, data_len);
996         xfree(data);
997 }
998
999
1000 /*
1001  * Returns true if no channel has too much buffered data, and false if one or
1002  * more channel is overfull.
1003  */
1004
1005 int
1006 channel_not_very_much_buffered_data()
1007 {
1008         unsigned int i;
1009         Channel *c;
1010
1011         for (i = 0; i < channels_alloc; i++) {
1012                 c = &channels[i];
1013                 if (c->type == SSH_CHANNEL_OPEN) {
1014                         if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1015                                 debug("channel %d: big input buffer %d",
1016                                     c->self, buffer_len(&c->input));
1017                                 return 0;
1018                         }
1019                         if (buffer_len(&c->output) > packet_get_maxsize()) {
1020                                 debug("channel %d: big output buffer %d",
1021                                     c->self, buffer_len(&c->output));
1022                                 return 0;
1023                         }
1024                 }
1025         }
1026         return 1;
1027 }
1028
1029 void
1030 channel_input_ieof(int type, int plen)
1031 {
1032         int id;
1033         Channel *c;
1034
1035         packet_integrity_check(plen, 4, type);
1036
1037         id = packet_get_int();
1038         c = channel_lookup(id);
1039         if (c == NULL)
1040                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1041         chan_rcvd_ieof(c);
1042 }
1043
1044 void
1045 channel_input_close(int type, int plen)
1046 {
1047         int id;
1048         Channel *c;
1049
1050         packet_integrity_check(plen, 4, type);
1051
1052         id = packet_get_int();
1053         c = channel_lookup(id);
1054         if (c == NULL)
1055                 packet_disconnect("Received close for nonexistent channel %d.", id);
1056
1057         /*
1058          * Send a confirmation that we have closed the channel and no more
1059          * data is coming for it.
1060          */
1061         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1062         packet_put_int(c->remote_id);
1063         packet_send();
1064
1065         /*
1066          * If the channel is in closed state, we have sent a close request,
1067          * and the other side will eventually respond with a confirmation.
1068          * Thus, we cannot free the channel here, because then there would be
1069          * no-one to receive the confirmation.  The channel gets freed when
1070          * the confirmation arrives.
1071          */
1072         if (c->type != SSH_CHANNEL_CLOSED) {
1073                 /*
1074                  * Not a closed channel - mark it as draining, which will
1075                  * cause it to be freed later.
1076                  */
1077                 buffer_consume(&c->input, buffer_len(&c->input));
1078                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1079         }
1080 }
1081
1082 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1083 void
1084 channel_input_oclose(int type, int plen)
1085 {
1086         int id = packet_get_int();
1087         Channel *c = channel_lookup(id);
1088         packet_integrity_check(plen, 4, type);
1089         if (c == NULL)
1090                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1091         chan_rcvd_oclose(c);
1092 }
1093
1094 void
1095 channel_input_close_confirmation(int type, int plen)
1096 {
1097         int id = packet_get_int();
1098         Channel *c = channel_lookup(id);
1099
1100         packet_done();
1101         if (c == NULL)
1102                 packet_disconnect("Received close confirmation for "
1103                     "out-of-range channel %d.", id);
1104         if (c->type != SSH_CHANNEL_CLOSED)
1105                 packet_disconnect("Received close confirmation for "
1106                     "non-closed channel %d (type %d).", id, c->type);
1107         channel_free(c->self);
1108 }
1109
1110 void
1111 channel_input_open_confirmation(int type, int plen)
1112 {
1113         int id, remote_id;
1114         Channel *c;
1115
1116         if (!compat20)
1117                 packet_integrity_check(plen, 4 + 4, type);
1118
1119         id = packet_get_int();
1120         c = channel_lookup(id);
1121
1122         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1123                 packet_disconnect("Received open confirmation for "
1124                     "non-opening channel %d.", id);
1125         remote_id = packet_get_int();
1126         /* Record the remote channel number and mark that the channel is now open. */
1127         c->remote_id = remote_id;
1128         c->type = SSH_CHANNEL_OPEN;
1129
1130         if (compat20) {
1131                 c->remote_window = packet_get_int();
1132                 c->remote_maxpacket = packet_get_int();
1133                 packet_done();
1134                 if (c->cb_fn != NULL && c->cb_event == type) {
1135                         debug("callback start");
1136                         c->cb_fn(c->self, c->cb_arg);
1137                         debug("callback done");
1138                 }
1139                 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1140                     c->remote_window, c->remote_maxpacket);
1141         }
1142 }
1143
1144 void
1145 channel_input_open_failure(int type, int plen)
1146 {
1147         int id;
1148         Channel *c;
1149
1150         if (!compat20)
1151                 packet_integrity_check(plen, 4, type);
1152
1153         id = packet_get_int();
1154         c = channel_lookup(id);
1155
1156         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1157                 packet_disconnect("Received open failure for "
1158                     "non-opening channel %d.", id);
1159         if (compat20) {
1160                 int reason = packet_get_int();
1161                 char *msg  = packet_get_string(NULL);
1162                 char *lang  = packet_get_string(NULL);
1163                 log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1164                 packet_done();
1165                 xfree(msg);
1166                 xfree(lang);
1167         }
1168         /* Free the channel.  This will also close the socket. */
1169         channel_free(id);
1170 }
1171
1172 void
1173 channel_input_channel_request(int type, int plen)
1174 {
1175         int id;
1176         Channel *c;
1177
1178         id = packet_get_int();
1179         c = channel_lookup(id);
1180
1181         if (c == NULL ||
1182             (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1183                 packet_disconnect("Received request for "
1184                     "non-open channel %d.", id);
1185         if (c->cb_fn != NULL && c->cb_event == type) {
1186                 debug("callback start");
1187                 c->cb_fn(c->self, c->cb_arg);
1188                 debug("callback done");
1189         } else {
1190                 char *service = packet_get_string(NULL);
1191                 debug("channel: %d rcvd request for %s", c->self, service);
1192 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1193                 xfree(service);
1194         }
1195 }
1196
1197 void
1198 channel_input_window_adjust(int type, int plen)
1199 {
1200         Channel *c;
1201         int id, adjust;
1202
1203         if (!compat20)
1204                 return;
1205
1206         /* Get the channel number and verify it. */
1207         id = packet_get_int();
1208         c = channel_lookup(id);
1209
1210         if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1211                 log("Received window adjust for "
1212                     "non-open channel %d.", id);
1213                 return;
1214         }
1215         adjust = packet_get_int();
1216         packet_done();
1217         debug("channel %d: rcvd adjust %d", id, adjust);
1218         c->remote_window += adjust;
1219 }
1220
1221 /*
1222  * Stops listening for channels, and removes any unix domain sockets that we
1223  * might have.
1224  */
1225
1226 void
1227 channel_stop_listening()
1228 {
1229         int i;
1230         for (i = 0; i < channels_alloc; i++) {
1231                 switch (channels[i].type) {
1232                 case SSH_CHANNEL_AUTH_SOCKET:
1233                         close(channels[i].sock);
1234                         remove(channels[i].path);
1235                         channel_free(i);
1236                         break;
1237                 case SSH_CHANNEL_PORT_LISTENER:
1238                 case SSH_CHANNEL_X11_LISTENER:
1239                         close(channels[i].sock);
1240                         channel_free(i);
1241                         break;
1242                 default:
1243                         break;
1244                 }
1245         }
1246 }
1247
1248 /*
1249  * Closes the sockets of all channels.  This is used to close extra file
1250  * descriptors after a fork.
1251  */
1252
1253 void
1254 channel_close_all()
1255 {
1256         int i;
1257         for (i = 0; i < channels_alloc; i++) {
1258                 if (channels[i].type != SSH_CHANNEL_FREE)
1259                         close(channels[i].sock);
1260         }
1261 }
1262
1263 /* Returns the maximum file descriptor number used by the channels. */
1264
1265 int
1266 channel_max_fd()
1267 {
1268         return channel_max_fd_value;
1269 }
1270
1271 /* Returns true if any channel is still open. */
1272
1273 int
1274 channel_still_open()
1275 {
1276         unsigned int i;
1277         for (i = 0; i < channels_alloc; i++)
1278                 switch (channels[i].type) {
1279                 case SSH_CHANNEL_FREE:
1280                 case SSH_CHANNEL_X11_LISTENER:
1281                 case SSH_CHANNEL_PORT_LISTENER:
1282                 case SSH_CHANNEL_CLOSED:
1283                 case SSH_CHANNEL_AUTH_SOCKET:
1284                         continue;
1285                 case SSH_CHANNEL_LARVAL:
1286                         if (!compat20)
1287                                 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1288                         continue;
1289                 case SSH_CHANNEL_OPENING:
1290                 case SSH_CHANNEL_OPEN:
1291                 case SSH_CHANNEL_X11_OPEN:
1292                         return 1;
1293                 case SSH_CHANNEL_INPUT_DRAINING:
1294                 case SSH_CHANNEL_OUTPUT_DRAINING:
1295                         if (!compat13)
1296                                 fatal("cannot happen: OUT_DRAIN");
1297                         return 1;
1298                 default:
1299                         fatal("channel_still_open: bad channel type %d", channels[i].type);
1300                         /* NOTREACHED */
1301                 }
1302         return 0;
1303 }
1304
1305 /*
1306  * Returns a message describing the currently open forwarded connections,
1307  * suitable for sending to the client.  The message contains crlf pairs for
1308  * newlines.
1309  */
1310
1311 char *
1312 channel_open_message()
1313 {
1314         Buffer buffer;
1315         int i;
1316         char buf[512], *cp;
1317
1318         buffer_init(&buffer);
1319         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1320         buffer_append(&buffer, buf, strlen(buf));
1321         for (i = 0; i < channels_alloc; i++) {
1322                 Channel *c = &channels[i];
1323                 switch (c->type) {
1324                 case SSH_CHANNEL_FREE:
1325                 case SSH_CHANNEL_X11_LISTENER:
1326                 case SSH_CHANNEL_PORT_LISTENER:
1327                 case SSH_CHANNEL_CLOSED:
1328                 case SSH_CHANNEL_AUTH_SOCKET:
1329                         continue;
1330                 case SSH_CHANNEL_LARVAL:
1331                 case SSH_CHANNEL_OPENING:
1332                 case SSH_CHANNEL_OPEN:
1333                 case SSH_CHANNEL_X11_OPEN:
1334                 case SSH_CHANNEL_INPUT_DRAINING:
1335                 case SSH_CHANNEL_OUTPUT_DRAINING:
1336                         snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1337                             c->self, c->remote_name,
1338                             c->type, c->remote_id,
1339                             c->istate, buffer_len(&c->input),
1340                             c->ostate, buffer_len(&c->output),
1341                             c->rfd, c->wfd);
1342                         buffer_append(&buffer, buf, strlen(buf));
1343                         continue;
1344                 default:
1345                         fatal("channel_open_message: bad channel type %d", c->type);
1346                         /* NOTREACHED */
1347                 }
1348         }
1349         buffer_append(&buffer, "\0", 1);
1350         cp = xstrdup(buffer_ptr(&buffer));
1351         buffer_free(&buffer);
1352         return cp;
1353 }
1354
1355 /*
1356  * Initiate forwarding of connections to local port "port" through the secure
1357  * channel to host:port from remote side.
1358  */
1359
1360 void
1361 channel_request_local_forwarding(u_short port, const char *host,
1362                                  u_short host_port, int gateway_ports)
1363 {
1364         int success, ch, sock, on = 1;
1365         struct addrinfo hints, *ai, *aitop;
1366         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1367         struct linger linger;
1368
1369         if (strlen(host) > sizeof(channels[0].path) - 1)
1370                 packet_disconnect("Forward host name too long.");
1371
1372         /*
1373          * getaddrinfo returns a loopback address if the hostname is
1374          * set to NULL and hints.ai_flags is not AI_PASSIVE
1375          */
1376         memset(&hints, 0, sizeof(hints));
1377         hints.ai_family = IPv4or6;
1378         hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1379         hints.ai_socktype = SOCK_STREAM;
1380         snprintf(strport, sizeof strport, "%d", port);
1381         if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1382                 packet_disconnect("getaddrinfo: fatal error");
1383
1384         success = 0;
1385         for (ai = aitop; ai; ai = ai->ai_next) {
1386                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1387                         continue;
1388                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1389                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1390                         error("channel_request_local_forwarding: getnameinfo failed");
1391                         continue;
1392                 }
1393                 /* Create a port to listen for the host. */
1394                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1395                 if (sock < 0) {
1396                         /* this is no error since kernel may not support ipv6 */
1397                         verbose("socket: %.100s", strerror(errno));
1398                         continue;
1399                 }
1400                 /*
1401                  * Set socket options.  We would like the socket to disappear
1402                  * as soon as it has been closed for whatever reason.
1403                  */
1404                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1405                 linger.l_onoff = 1;
1406                 linger.l_linger = 5;
1407                 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1408                 debug("Local forwarding listening on %s port %s.", ntop, strport);
1409
1410                 /* Bind the socket to the address. */
1411                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1412                         /* address can be in use ipv6 address is already bound */
1413                         if (!ai->ai_next)
1414                                 error("bind: %.100s", strerror(errno));
1415                         else
1416                                 verbose("bind: %.100s", strerror(errno));
1417                                 
1418                         close(sock);
1419                         continue;
1420                 }
1421                 /* Start listening for connections on the socket. */
1422                 if (listen(sock, 5) < 0) {
1423                         error("listen: %.100s", strerror(errno));
1424                         close(sock);
1425                         continue;
1426                 }
1427                 /* Allocate a channel number for the socket. */
1428                 ch = channel_new(
1429                     "port listener", SSH_CHANNEL_PORT_LISTENER,
1430                     sock, sock, -1,
1431                     CHAN_WINDOW_DEFAULT, CHAN_PACKET_DEFAULT,
1432                     0, xstrdup("port listener"));
1433                 strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1434                 channels[ch].host_port = host_port;
1435                 channels[ch].listening_port = port;
1436                 success = 1;
1437         }
1438         if (success == 0)
1439                 packet_disconnect("cannot listen port: %d", port);
1440         freeaddrinfo(aitop);
1441 }
1442
1443 /*
1444  * Initiate forwarding of connections to port "port" on remote host through
1445  * the secure channel to host:port from local side.
1446  */
1447
1448 void
1449 channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1450                                   u_short port_to_connect)
1451 {
1452         int payload_len;
1453         /* Record locally that connection to this host/port is permitted. */
1454         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1455                 fatal("channel_request_remote_forwarding: too many forwards");
1456
1457         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1458         permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1459         permitted_opens[num_permitted_opens].listen_port = listen_port;
1460         num_permitted_opens++;
1461
1462         /* Send the forward request to the remote side. */
1463         if (compat20) {
1464                 const char *address_to_bind = "0.0.0.0";
1465                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1466                 packet_put_cstring("tcpip-forward");
1467                 packet_put_char(0);                     /* boolean: want reply */
1468                 packet_put_cstring(address_to_bind);
1469                 packet_put_int(listen_port);
1470         } else {
1471                 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1472                 packet_put_int(port_to_connect);
1473                 packet_put_cstring(host_to_connect);
1474                 packet_put_int(listen_port);
1475                 packet_send();
1476                 packet_write_wait();
1477                 /*
1478                  * Wait for response from the remote side.  It will send a disconnect
1479                  * message on failure, and we will never see it here.
1480                  */
1481                 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1482         }
1483 }
1484
1485 /*
1486  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1487  * listening for the port, and sends back a success reply (or disconnect
1488  * message if there was an error).  This never returns if there was an error.
1489  */
1490
1491 void
1492 channel_input_port_forward_request(int is_root)
1493 {
1494         u_short port, host_port;
1495         char *hostname;
1496
1497         /* Get arguments from the packet. */
1498         port = packet_get_int();
1499         hostname = packet_get_string(NULL);
1500         host_port = packet_get_int();
1501
1502         /*
1503          * Check that an unprivileged user is not trying to forward a
1504          * privileged port.
1505          */
1506         if (port < IPPORT_RESERVED && !is_root)
1507                 packet_disconnect("Requested forwarding of port %d but user is not root.",
1508                                   port);
1509         /*
1510          * Initiate forwarding,
1511          * bind port to localhost only (gateway ports == 0).
1512          */
1513         channel_request_local_forwarding(port, hostname, host_port, 0);
1514
1515         /* Free the argument string. */
1516         xfree(hostname);
1517 }
1518
1519 /* XXX move to aux.c */
1520 int
1521 channel_connect_to(const char *host, u_short host_port)
1522 {
1523         struct addrinfo hints, *ai, *aitop;
1524         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1525         int gaierr;
1526         int sock = -1;
1527
1528         memset(&hints, 0, sizeof(hints));
1529         hints.ai_family = IPv4or6;
1530         hints.ai_socktype = SOCK_STREAM;
1531         snprintf(strport, sizeof strport, "%d", host_port);
1532         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1533                 error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1534                 return -1;
1535         }
1536         for (ai = aitop; ai; ai = ai->ai_next) {
1537                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1538                         continue;
1539                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1540                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1541                         error("channel_connect_to: getnameinfo failed");
1542                         continue;
1543                 }
1544                 /* Create the socket. */
1545                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1546                 if (sock < 0) {
1547                         error("socket: %.100s", strerror(errno));
1548                         continue;
1549                 }
1550                 /* Connect to the host/port. */
1551                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1552                         error("connect %.100s port %s: %.100s", ntop, strport,
1553                             strerror(errno));
1554                         close(sock);
1555                         continue;       /* fail -- try next */  
1556                 }
1557                 break; /* success */
1558
1559         }
1560         freeaddrinfo(aitop);
1561         if (!ai) {
1562                 error("connect %.100s port %d: failed.", host, host_port);      
1563                 return -1;
1564         }
1565         /* success */
1566         return sock;
1567 }
1568
1569 /*
1570  * This is called after receiving PORT_OPEN message.  This attempts to
1571  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1572  * or CHANNEL_OPEN_FAILURE.
1573  */
1574
1575 void
1576 channel_input_port_open(int type, int plen)
1577 {
1578         u_short host_port;
1579         char *host, *originator_string;
1580         int remote_channel, sock = -1, newch, i, denied;
1581         unsigned int host_len, originator_len;
1582
1583         /* Get remote channel number. */
1584         remote_channel = packet_get_int();
1585
1586         /* Get host name to connect to. */
1587         host = packet_get_string(&host_len);
1588
1589         /* Get port to connect to. */
1590         host_port = packet_get_int();
1591
1592         /* Get remote originator name. */
1593         if (have_hostname_in_open) {
1594                 originator_string = packet_get_string(&originator_len);
1595                 originator_len += 4;    /* size of packet_int */
1596         } else {
1597                 originator_string = xstrdup("unknown (remote did not supply name)");
1598                 originator_len = 0;     /* no originator supplied */
1599         }
1600
1601         packet_integrity_check(plen,
1602             4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1603
1604         /* Check if opening that port is permitted. */
1605         denied = 0;
1606         if (!all_opens_permitted) {
1607                 /* Go trough all permitted ports. */
1608                 for (i = 0; i < num_permitted_opens; i++)
1609                         if (permitted_opens[i].port_to_connect == host_port &&
1610                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
1611                                 break;
1612
1613                 /* Check if we found the requested port among those permitted. */
1614                 if (i >= num_permitted_opens) {
1615                         /* The port is not permitted. */
1616                         log("Received request to connect to %.100s:%d, but the request was denied.",
1617                             host, host_port);
1618                         denied = 1;
1619                 }
1620         }
1621         sock = denied ? -1 : channel_connect_to(host, host_port);
1622         if (sock > 0) {
1623                 /* Allocate a channel for this connection. */
1624                 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1625                 channels[newch].remote_id = remote_channel;
1626
1627                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1628                 packet_put_int(remote_channel);
1629                 packet_put_int(newch);
1630                 packet_send();
1631         } else {
1632                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1633                 packet_put_int(remote_channel);
1634                 packet_send();
1635         }
1636         xfree(host);
1637 }
1638
1639 /*
1640  * Creates an internet domain socket for listening for X11 connections.
1641  * Returns a suitable value for the DISPLAY variable, or NULL if an error
1642  * occurs.
1643  */
1644
1645 #define NUM_SOCKS       10
1646
1647 char *
1648 x11_create_display_inet(int screen_number, int x11_display_offset)
1649 {
1650         int display_number, sock;
1651         u_short port;
1652         struct addrinfo hints, *ai, *aitop;
1653         char strport[NI_MAXSERV];
1654         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1655         char display[512];
1656         char hostname[MAXHOSTNAMELEN];
1657
1658         for (display_number = x11_display_offset;
1659              display_number < MAX_DISPLAYS;
1660              display_number++) {
1661                 port = 6000 + display_number;
1662                 memset(&hints, 0, sizeof(hints));
1663                 hints.ai_family = IPv4or6;
1664                 hints.ai_flags = AI_PASSIVE;            /* XXX loopback only ? */
1665                 hints.ai_socktype = SOCK_STREAM;
1666                 snprintf(strport, sizeof strport, "%d", port);
1667                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1668                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
1669                         return NULL;
1670                 }
1671                 for (ai = aitop; ai; ai = ai->ai_next) {
1672                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1673                                 continue;
1674                         sock = socket(ai->ai_family, SOCK_STREAM, 0);
1675                         if (sock < 0) {
1676                                 if (errno != EINVAL) {
1677                                         error("socket: %.100s", strerror(errno));
1678                                         return NULL;
1679                                 } else {
1680                                         debug("Socket family %d not supported [X11 disp create]", ai->ai_family);
1681                                         continue;
1682                                 }
1683                         }
1684                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1685                                 debug("bind port %d: %.100s", port, strerror(errno));
1686                                 shutdown(sock, SHUT_RDWR);
1687                                 close(sock);
1688
1689                                 if (ai->ai_next)
1690                                         continue;
1691
1692                                 for (n = 0; n < num_socks; n++) {
1693                                         shutdown(socks[n], SHUT_RDWR);
1694                                         close(socks[n]);
1695                                 }
1696                                 num_socks = 0;
1697                                 break;
1698                         }
1699                         socks[num_socks++] = sock;
1700 #ifndef DONT_TRY_OTHER_AF
1701                         if (num_socks == NUM_SOCKS)
1702                                 break;
1703 #else
1704                         break;
1705 #endif
1706                 }
1707                 if (num_socks > 0)
1708                         break;
1709         }
1710         if (display_number >= MAX_DISPLAYS) {
1711                 error("Failed to allocate internet-domain X11 display socket.");
1712                 return NULL;
1713         }
1714         /* Start listening for connections on the socket. */
1715         for (n = 0; n < num_socks; n++) {
1716                 sock = socks[n];
1717                 if (listen(sock, 5) < 0) {
1718                         error("listen: %.100s", strerror(errno));
1719                         shutdown(sock, SHUT_RDWR);
1720                         close(sock);
1721                         return NULL;
1722                 }
1723         }
1724
1725         /* Set up a suitable value for the DISPLAY variable. */
1726
1727         if (gethostname(hostname, sizeof(hostname)) < 0)
1728                 fatal("gethostname: %.100s", strerror(errno));
1729
1730 #ifdef IPADDR_IN_DISPLAY
1731         /* 
1732          * HPUX detects the local hostname in the DISPLAY variable and tries
1733          * to set up a shared memory connection to the server, which it
1734          * incorrectly supposes to be local.
1735          *
1736          * The workaround - as used in later $$H and other programs - is
1737          * is to set display to the host's IP address.
1738          */
1739         {
1740                 struct hostent *he;
1741                 struct in_addr my_addr;
1742
1743                 he = gethostbyname(hostname);
1744                 if (he == NULL) {
1745                         error("[X11-broken-fwd-hostname-workaround] Could not get "
1746                                 "IP address for hostname %s.", hostname);
1747
1748                         packet_send_debug("[X11-broken-fwd-hostname-workaround]"
1749                                 "Could not get IP address for hostname %s.", hostname);
1750
1751                         shutdown(sock, SHUT_RDWR);
1752                         close(sock);
1753
1754                         return NULL;
1755                 }
1756
1757                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1758
1759                 /* Set DISPLAY to <ip address>:screen.display */
1760                 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr), 
1761                         display_number, screen_number);
1762         }
1763 #else /* IPADDR_IN_DISPLAY */
1764         /* Just set DISPLAY to hostname:screen.display */
1765         snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1766                 display_number, screen_number);
1767 #endif /* IPADDR_IN_DISPLAY */
1768
1769         /* Allocate a channel for each socket. */
1770         for (n = 0; n < num_socks; n++) {
1771                 sock = socks[n];
1772                 (void) channel_allocate(SSH_CHANNEL_X11_LISTENER, sock,
1773                                         xstrdup("X11 inet listener"));
1774         }
1775
1776         /* Return a suitable value for the DISPLAY environment variable. */
1777         return xstrdup(display);
1778 }
1779
1780 #ifndef X_UNIX_PATH
1781 #define X_UNIX_PATH "/tmp/.X11-unix/X"
1782 #endif
1783
1784 static
1785 int
1786 connect_local_xsocket(unsigned int dnr)
1787 {
1788         static const char *const x_sockets[] = {
1789                 X_UNIX_PATH "%u",
1790                 "/var/X/.X11-unix/X" "%u",
1791                 "/usr/spool/sockets/X11/" "%u",
1792                 NULL
1793         };
1794         int sock;
1795         struct sockaddr_un addr;
1796         const char *const * path;
1797
1798         for (path = x_sockets; *path; ++path) {
1799                 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1800                 if (sock < 0)
1801                         error("socket: %.100s", strerror(errno));
1802                 memset(&addr, 0, sizeof(addr));
1803                 addr.sun_family = AF_UNIX;
1804                 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1805                 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1806                         return sock;
1807                 close(sock);
1808         }
1809         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1810         return -1;
1811 }
1812
1813
1814 /*
1815  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1816  * the remote channel number.  We should do whatever we want, and respond
1817  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1818  */
1819
1820 void
1821 x11_input_open(int type, int plen)
1822 {
1823         int remote_channel, display_number, sock = 0, newch;
1824         const char *display;
1825         char buf[1024], *cp, *remote_host;
1826         unsigned int remote_len;
1827         struct addrinfo hints, *ai, *aitop;
1828         char strport[NI_MAXSERV];
1829         int gaierr;
1830
1831         /* Get remote channel number. */
1832         remote_channel = packet_get_int();
1833
1834         /* Get remote originator name. */
1835         if (have_hostname_in_open) {
1836                 remote_host = packet_get_string(&remote_len);
1837                 remote_len += 4;
1838         } else {
1839                 remote_host = xstrdup("unknown (remote did not supply name)");
1840                 remote_len = 0;
1841         }
1842
1843         debug("Received X11 open request.");
1844         packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1845
1846         /* Try to open a socket for the local X server. */
1847         display = getenv("DISPLAY");
1848         if (!display) {
1849                 error("DISPLAY not set.");
1850                 goto fail;
1851         }
1852         /*
1853          * Now we decode the value of the DISPLAY variable and make a
1854          * connection to the real X server.
1855          */
1856
1857         /*
1858          * Check if it is a unix domain socket.  Unix domain displays are in
1859          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1860          */
1861         if (strncmp(display, "unix:", 5) == 0 ||
1862             display[0] == ':') {
1863                 /* Connect to the unix domain socket. */
1864                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1865                         error("Could not parse display number from DISPLAY: %.100s",
1866                               display);
1867                         goto fail;
1868                 }
1869                 /* Create a socket. */
1870                 sock = connect_local_xsocket(display_number);
1871                 if (sock < 0)
1872                         goto fail;
1873
1874                 /* OK, we now have a connection to the display. */
1875                 goto success;
1876         }
1877         /*
1878          * Connect to an inet socket.  The DISPLAY value is supposedly
1879          * hostname:d[.s], where hostname may also be numeric IP address.
1880          */
1881         strncpy(buf, display, sizeof(buf));
1882         buf[sizeof(buf) - 1] = 0;
1883         cp = strchr(buf, ':');
1884         if (!cp) {
1885                 error("Could not find ':' in DISPLAY: %.100s", display);
1886                 goto fail;
1887         }
1888         *cp = 0;
1889         /* buf now contains the host name.  But first we parse the display number. */
1890         if (sscanf(cp + 1, "%d", &display_number) != 1) {
1891                 error("Could not parse display number from DISPLAY: %.100s",
1892                       display);
1893                 goto fail;
1894         }
1895
1896         /* Look up the host address */
1897         memset(&hints, 0, sizeof(hints));
1898         hints.ai_family = IPv4or6;
1899         hints.ai_socktype = SOCK_STREAM;
1900         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1901         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1902                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1903                 goto fail;
1904         }
1905         for (ai = aitop; ai; ai = ai->ai_next) {
1906                 /* Create a socket. */
1907                 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1908                 if (sock < 0) {
1909                         debug("socket: %.100s", strerror(errno));
1910                         continue;
1911                 }
1912                 /* Connect it to the display. */
1913                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1914                         debug("connect %.100s port %d: %.100s", buf,
1915                             6000 + display_number, strerror(errno));
1916                         close(sock);
1917                         continue;
1918                 }
1919                 /* Success */
1920                 break;
1921         }
1922         freeaddrinfo(aitop);
1923         if (!ai) {
1924                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1925                     strerror(errno));
1926                 goto fail;
1927         }
1928 success:
1929         /* We have successfully obtained a connection to the real X display. */
1930
1931         /* Allocate a channel for this connection. */
1932         if (x11_saved_proto == NULL)
1933                 newch = channel_allocate(SSH_CHANNEL_OPEN, sock, remote_host);
1934         else
1935                 newch = channel_allocate(SSH_CHANNEL_X11_OPEN, sock, remote_host);
1936         channels[newch].remote_id = remote_channel;
1937
1938         /* Send a confirmation to the remote host. */
1939         packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1940         packet_put_int(remote_channel);
1941         packet_put_int(newch);
1942         packet_send();
1943
1944         return;
1945
1946 fail:
1947         /* Send refusal to the remote host. */
1948         packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1949         packet_put_int(remote_channel);
1950         packet_send();
1951 }
1952
1953 /*
1954  * Requests forwarding of X11 connections, generates fake authentication
1955  * data, and enables authentication spoofing.
1956  */
1957
1958 void
1959 x11_request_forwarding_with_spoofing(const char *proto, const char *data)
1960 {
1961         unsigned int data_len = (unsigned int) strlen(data) / 2;
1962         unsigned int i, value;
1963         char *new_data;
1964         int screen_number;
1965         const char *cp;
1966         u_int32_t rand = 0;
1967
1968         cp = getenv("DISPLAY");
1969         if (cp)
1970                 cp = strchr(cp, ':');
1971         if (cp)
1972                 cp = strchr(cp, '.');
1973         if (cp)
1974                 screen_number = atoi(cp + 1);
1975         else
1976                 screen_number = 0;
1977
1978         /* Save protocol name. */
1979         x11_saved_proto = xstrdup(proto);
1980
1981         /*
1982          * Extract real authentication data and generate fake data of the
1983          * same length.
1984          */
1985         x11_saved_data = xmalloc(data_len);
1986         x11_fake_data = xmalloc(data_len);
1987         for (i = 0; i < data_len; i++) {
1988                 if (sscanf(data + 2 * i, "%2x", &value) != 1)
1989                         fatal("x11_request_forwarding: bad authentication data: %.100s", data);
1990                 if (i % 4 == 0)
1991                         rand = arc4random();
1992                 x11_saved_data[i] = value;
1993                 x11_fake_data[i] = rand & 0xff;
1994                 rand >>= 8;
1995         }
1996         x11_saved_data_len = data_len;
1997         x11_fake_data_len = data_len;
1998
1999         /* Convert the fake data into hex. */
2000         new_data = xmalloc(2 * data_len + 1);
2001         for (i = 0; i < data_len; i++)
2002                 sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2003
2004         /* Send the request packet. */
2005         packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2006         packet_put_string(proto, strlen(proto));
2007         packet_put_string(new_data, strlen(new_data));
2008         packet_put_int(screen_number);
2009         packet_send();
2010         packet_write_wait();
2011         xfree(new_data);
2012 }
2013
2014 /* Sends a message to the server to request authentication fd forwarding. */
2015
2016 void
2017 auth_request_forwarding()
2018 {
2019         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2020         packet_send();
2021         packet_write_wait();
2022 }
2023
2024 /*
2025  * Returns the name of the forwarded authentication socket.  Returns NULL if
2026  * there is no forwarded authentication socket.  The returned value points to
2027  * a static buffer.
2028  */
2029
2030 char *
2031 auth_get_socket_name()
2032 {
2033         return channel_forwarded_auth_socket_name;
2034 }
2035
2036 /* removes the agent forwarding socket */
2037
2038 void
2039 cleanup_socket(void)
2040 {
2041         remove(channel_forwarded_auth_socket_name);
2042         rmdir(channel_forwarded_auth_socket_dir);
2043 }
2044
2045 /*
2046  * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2047  * This starts forwarding authentication requests.
2048  */
2049
2050 void
2051 auth_input_request_forwarding(struct passwd * pw)
2052 {
2053         int sock, newch;
2054         struct sockaddr_un sunaddr;
2055
2056         if (auth_get_socket_name() != NULL)
2057                 fatal("Protocol error: authentication forwarding requested twice.");
2058
2059         /* Temporarily drop privileged uid for mkdir/bind. */
2060         temporarily_use_uid(pw->pw_uid);
2061
2062         /* Allocate a buffer for the socket name, and format the name. */
2063         channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2064         channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2065         strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2066
2067         /* Create private directory for socket */
2068         if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2069                 packet_disconnect("mkdtemp: %.100s", strerror(errno));
2070         snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2071                  channel_forwarded_auth_socket_dir, (int) getpid());
2072
2073         if (atexit(cleanup_socket) < 0) {
2074                 int saved = errno;
2075                 cleanup_socket();
2076                 packet_disconnect("socket: %.100s", strerror(saved));
2077         }
2078         /* Create the socket. */
2079         sock = socket(AF_UNIX, SOCK_STREAM, 0);
2080         if (sock < 0)
2081                 packet_disconnect("socket: %.100s", strerror(errno));
2082
2083         /* Bind it to the name. */
2084         memset(&sunaddr, 0, sizeof(sunaddr));
2085         sunaddr.sun_family = AF_UNIX;
2086         strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2087                 sizeof(sunaddr.sun_path));
2088
2089         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2090                 packet_disconnect("bind: %.100s", strerror(errno));
2091
2092         /* Restore the privileged uid. */
2093         restore_uid();
2094
2095         /* Start listening on the socket. */
2096         if (listen(sock, 5) < 0)
2097                 packet_disconnect("listen: %.100s", strerror(errno));
2098
2099         /* Allocate a channel for the authentication agent socket. */
2100         newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2101                                  xstrdup("auth socket"));
2102         strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2103             sizeof(channels[newch].path));
2104 }
2105
2106 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2107
2108 void
2109 auth_input_open_request(int type, int plen)
2110 {
2111         int remch, sock, newch;
2112         char *dummyname;
2113
2114         packet_integrity_check(plen, 4, type);
2115
2116         /* Read the remote channel number from the message. */
2117         remch = packet_get_int();
2118
2119         /*
2120          * Get a connection to the local authentication agent (this may again
2121          * get forwarded).
2122          */
2123         sock = ssh_get_authentication_socket();
2124
2125         /*
2126          * If we could not connect the agent, send an error message back to
2127          * the server. This should never happen unless the agent dies,
2128          * because authentication forwarding is only enabled if we have an
2129          * agent.
2130          */
2131         if (sock < 0) {
2132                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2133                 packet_put_int(remch);
2134                 packet_send();
2135                 return;
2136         }
2137         debug("Forwarding authentication connection.");
2138
2139         /*
2140          * Dummy host name.  This will be freed when the channel is freed; it
2141          * will still be valid in the packet_put_string below since the
2142          * channel cannot yet be freed at that point.
2143          */
2144         dummyname = xstrdup("authentication agent connection");
2145
2146         newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2147         channels[newch].remote_id = remch;
2148
2149         /* Send a confirmation to the remote host. */
2150         packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2151         packet_put_int(remch);
2152         packet_put_int(newch);
2153         packet_send();
2154 }
2155
2156 void
2157 channel_open(int id)
2158 {
2159         Channel *c = channel_lookup(id);
2160         if (c == NULL) {
2161                 log("channel_open: %d: bad id", id);
2162                 return;
2163         }
2164         packet_start(SSH2_MSG_CHANNEL_OPEN);
2165         packet_put_cstring(c->ctype);
2166         packet_put_int(c->self);
2167         packet_put_int(c->local_window);
2168         packet_put_int(c->local_maxpacket);
2169         packet_send();
2170         debug("channel open %d", id);
2171 }
2172 void
2173 channel_request(int id, char *service, int wantconfirm)
2174 {
2175         channel_request_start(id, service, wantconfirm);
2176         packet_send();
2177         debug("channel request %d: %s", id, service) ;
2178 }
2179 void
2180 channel_request_start(int id, char *service, int wantconfirm)
2181 {
2182         Channel *c = channel_lookup(id);
2183         if (c == NULL) {
2184                 log("channel_request: %d: bad id", id);
2185                 return;
2186         }
2187         packet_start(SSH2_MSG_CHANNEL_REQUEST);
2188         packet_put_int(c->remote_id);
2189         packet_put_cstring(service);
2190         packet_put_char(wantconfirm);
2191 }
2192 void
2193 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2194 {
2195         Channel *c = channel_lookup(id);
2196         if (c == NULL) {
2197                 log("channel_register_callback: %d: bad id", id);
2198                 return;
2199         }
2200         c->cb_event = mtype;
2201         c->cb_fn = fn;
2202         c->cb_arg = arg;
2203 }
2204 void
2205 channel_register_cleanup(int id, channel_callback_fn *fn)
2206 {
2207         Channel *c = channel_lookup(id);
2208         if (c == NULL) {
2209                 log("channel_register_cleanup: %d: bad id", id);
2210                 return;
2211         }
2212         c->dettach_user = fn;
2213 }
2214 void
2215 channel_cancel_cleanup(int id)
2216 {
2217         Channel *c = channel_lookup(id);
2218         if (c == NULL) {
2219                 log("channel_cancel_cleanup: %d: bad id", id);
2220                 return;
2221         }
2222         c->dettach_user = NULL;
2223 }
2224
2225 void
2226 channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2227 {
2228         Channel *c = channel_lookup(id);
2229         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2230                 fatal("channel_activate for non-larval channel %d.", id);
2231         if (rfd > channel_max_fd_value)
2232                 channel_max_fd_value = rfd;
2233         if (wfd > channel_max_fd_value)
2234                 channel_max_fd_value = wfd;
2235         if (efd > channel_max_fd_value)
2236                 channel_max_fd_value = efd;
2237         c->type = SSH_CHANNEL_OPEN;
2238         c->rfd = rfd;
2239         c->wfd = wfd;
2240         c->efd = efd;
2241         c->extended_usage = extusage;
2242         /* XXX window size? */
2243         c->local_window = c->local_window_max = c->local_maxpacket/2;
2244         packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2245         packet_put_int(c->remote_id);
2246         packet_put_int(c->local_window);
2247         packet_send();
2248 }
This page took 0.2773 seconds and 3 git commands to generate.