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