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