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