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