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