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