jcs's openbsd hax
openbsd
1/* $OpenBSD: channels.c,v 1.455 2026/02/14 00:18:34 jsg Exp $ */
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.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
20 *
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 */
41
42#include <sys/types.h>
43#include <sys/stat.h>
44#include <sys/ioctl.h>
45#include <sys/un.h>
46#include <sys/socket.h>
47#include <sys/queue.h>
48
49#include <netinet/in.h>
50#include <arpa/inet.h>
51
52#include <errno.h>
53#include <fcntl.h>
54#include <limits.h>
55#include <netdb.h>
56#include <poll.h>
57#include <stdarg.h>
58#include <stdint.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <termios.h>
63#include <unistd.h>
64
65#include "xmalloc.h"
66#include "ssh.h"
67#include "ssh2.h"
68#include "ssherr.h"
69#include "sshbuf.h"
70#include "packet.h"
71#include "log.h"
72#include "misc.h"
73#include "channels.h"
74#include "compat.h"
75#include "canohost.h"
76#include "pathnames.h"
77#include "match.h"
78
79/* XXX remove once we're satisfied there's no lurking bugs */
80/* #define DEBUG_CHANNEL_POLL 1 */
81
82/* -- agent forwarding */
83#define NUM_SOCKS 10
84
85/* -- X11 forwarding */
86/* X11 port for display :0 */
87#define X11_BASE_PORT 6000
88/* Maximum number of fake X11 displays to try. */
89#define MAX_DISPLAYS 1000
90
91/* Per-channel callback for pre/post IO actions */
92typedef void chan_fn(struct ssh *, Channel *c);
93
94/*
95 * Data structure for storing which hosts are permitted for forward requests.
96 * The local sides of any remote forwards are stored in this array to prevent
97 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
98 * network (which might be behind a firewall).
99 */
100/* XXX: streamlocal wants a path instead of host:port */
101/* Overload host_to_connect; we could just make this match Forward */
102/* XXX - can we use listen_host instead of listen_path? */
103struct permission {
104 char *host_to_connect; /* Connect to 'host'. */
105 int port_to_connect; /* Connect to 'port'. */
106 char *listen_host; /* Remote side should listen address. */
107 char *listen_path; /* Remote side should listen path. */
108 int listen_port; /* Remote side should listen port. */
109 Channel *downstream; /* Downstream mux*/
110};
111
112/*
113 * Stores the forwarding permission state for a single direction (local or
114 * remote).
115 */
116struct permission_set {
117 /*
118 * List of all local permitted host/port pairs to allow for the
119 * user.
120 */
121 u_int num_permitted_user;
122 struct permission *permitted_user;
123
124 /*
125 * List of all permitted host/port pairs to allow for the admin.
126 */
127 u_int num_permitted_admin;
128 struct permission *permitted_admin;
129
130 /*
131 * If this is true, all opens/listens are permitted. This is the
132 * case on the server on which we have to trust the client anyway,
133 * and the user could do anything after logging in.
134 */
135 int all_permitted;
136};
137
138/* Used to record timeouts per channel type */
139struct ssh_channel_timeout {
140 char *type_pattern;
141 int timeout_secs;
142};
143
144/* Master structure for channels state */
145struct ssh_channels {
146 /*
147 * Pointer to an array containing all allocated channels. The array
148 * is dynamically extended as needed.
149 */
150 Channel **channels;
151
152 /*
153 * Size of the channel array. All slots of the array must always be
154 * initialized (at least the type field); unused slots set to NULL
155 */
156 u_int channels_alloc;
157
158 /*
159 * 'channel_pre*' are called just before IO to add any bits
160 * relevant to channels in the c->io_want bitmasks.
161 *
162 * 'channel_post*': perform any appropriate operations for
163 * channels which have c->io_ready events pending.
164 */
165 chan_fn **channel_pre;
166 chan_fn **channel_post;
167
168 /* -- tcp forwarding */
169 struct permission_set local_perms;
170 struct permission_set remote_perms;
171
172 /* -- X11 forwarding */
173
174 /* Saved X11 local (client) display. */
175 char *x11_saved_display;
176
177 /* Saved X11 authentication protocol name. */
178 char *x11_saved_proto;
179
180 /* Saved X11 authentication data. This is the real data. */
181 char *x11_saved_data;
182 u_int x11_saved_data_len;
183
184 /* Deadline after which all X11 connections are refused */
185 time_t x11_refuse_time;
186
187 /*
188 * Fake X11 authentication data. This is what the server will be
189 * sending us; we should replace any occurrences of this by the
190 * real data.
191 */
192 u_char *x11_fake_data;
193 u_int x11_fake_data_len;
194
195 /* AF_UNSPEC or AF_INET or AF_INET6 */
196 int IPv4or6;
197
198 /* Channel timeouts by type */
199 struct ssh_channel_timeout *timeouts;
200 size_t ntimeouts;
201 /* Global timeout for all OPEN channels */
202 int global_deadline;
203 time_t lastused;
204 /* pattern-lists used to classify channels as bulk */
205 char *bulk_classifier_tty, *bulk_classifier_notty;
206 /* Number of active bulk channels (set by channel_handler) */
207 u_int nbulk;
208};
209
210/* helper */
211static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212static const char *channel_rfwd_bind_host(const char *listen_host);
213
214/* non-blocking connect helpers */
215static int connect_next(struct channel_connect *);
216static void channel_connect_ctx_free(struct channel_connect *);
217static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218static int rdynamic_connect_finish(struct ssh *, Channel *);
219
220/* Setup helper */
221static void channel_handler_init(struct ssh_channels *sc);
222
223/* -- channel core */
224
225void
226channel_init_channels(struct ssh *ssh)
227{
228 struct ssh_channels *sc;
229
230 if ((sc = calloc(1, sizeof(*sc))) == NULL)
231 fatal_f("allocation failed");
232 sc->channels_alloc = 10;
233 sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
234 sc->IPv4or6 = AF_UNSPEC;
235 sc->bulk_classifier_tty = xstrdup(CHANNEL_BULK_TTY);
236 sc->bulk_classifier_notty = xstrdup(CHANNEL_BULK_NOTTY);
237 channel_handler_init(sc);
238
239 ssh->chanctxt = sc;
240}
241
242Channel *
243channel_by_id(struct ssh *ssh, int id)
244{
245 Channel *c;
246
247 if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
248 logit_f("%d: bad id", id);
249 return NULL;
250 }
251 c = ssh->chanctxt->channels[id];
252 if (c == NULL) {
253 logit_f("%d: bad id: channel free", id);
254 return NULL;
255 }
256 return c;
257}
258
259Channel *
260channel_by_remote_id(struct ssh *ssh, u_int remote_id)
261{
262 Channel *c;
263 u_int i;
264
265 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
266 c = ssh->chanctxt->channels[i];
267 if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
268 return c;
269 }
270 return NULL;
271}
272
273/*
274 * Returns the channel if it is allowed to receive protocol messages.
275 * Private channels, like listening sockets, may not receive messages.
276 */
277Channel *
278channel_lookup(struct ssh *ssh, int id)
279{
280 Channel *c;
281
282 if ((c = channel_by_id(ssh, id)) == NULL)
283 return NULL;
284
285 switch (c->type) {
286 case SSH_CHANNEL_X11_OPEN:
287 case SSH_CHANNEL_LARVAL:
288 case SSH_CHANNEL_CONNECTING:
289 case SSH_CHANNEL_DYNAMIC:
290 case SSH_CHANNEL_RDYNAMIC_OPEN:
291 case SSH_CHANNEL_RDYNAMIC_FINISH:
292 case SSH_CHANNEL_OPENING:
293 case SSH_CHANNEL_OPEN:
294 case SSH_CHANNEL_ABANDONED:
295 case SSH_CHANNEL_MUX_PROXY:
296 return c;
297 }
298 logit("Non-public channel %d, type %d.", id, c->type);
299 return NULL;
300}
301
302/*
303 * Add a timeout for open channels whose c->ctype (or c->xctype if it is set)
304 * match type_pattern.
305 */
306void
307channel_add_timeout(struct ssh *ssh, const char *type_pattern,
308 int timeout_secs)
309{
310 struct ssh_channels *sc = ssh->chanctxt;
311
312 if (strcmp(type_pattern, "global") == 0) {
313 debug2_f("global channel timeout %d seconds", timeout_secs);
314 sc->global_deadline = timeout_secs;
315 return;
316 }
317 debug2_f("channel type \"%s\" timeout %d seconds",
318 type_pattern, timeout_secs);
319 sc->timeouts = xrecallocarray(sc->timeouts, sc->ntimeouts,
320 sc->ntimeouts + 1, sizeof(*sc->timeouts));
321 sc->timeouts[sc->ntimeouts].type_pattern = xstrdup(type_pattern);
322 sc->timeouts[sc->ntimeouts].timeout_secs = timeout_secs;
323 sc->ntimeouts++;
324}
325
326/* Clears all previously-added channel timeouts */
327void
328channel_clear_timeouts(struct ssh *ssh)
329{
330 struct ssh_channels *sc = ssh->chanctxt;
331 size_t i;
332
333 debug3_f("clearing");
334 for (i = 0; i < sc->ntimeouts; i++)
335 free(sc->timeouts[i].type_pattern);
336 free(sc->timeouts);
337 sc->timeouts = NULL;
338 sc->ntimeouts = 0;
339}
340
341static int
342lookup_timeout(struct ssh *ssh, const char *type)
343{
344 struct ssh_channels *sc = ssh->chanctxt;
345 size_t i;
346
347 for (i = 0; i < sc->ntimeouts; i++) {
348 if (match_pattern(type, sc->timeouts[i].type_pattern))
349 return sc->timeouts[i].timeout_secs;
350 }
351
352 return 0;
353}
354
355static void
356channel_classify(struct ssh *ssh, Channel *c)
357{
358 struct ssh_channels *sc = ssh->chanctxt;
359 const char *type = c->xctype == NULL ? c->ctype : c->xctype;
360 const char *classifier = (c->isatty || c->remote_has_tty) ?
361 sc->bulk_classifier_tty : sc->bulk_classifier_notty;
362
363 c->bulk = type != NULL && match_pattern_list(type, classifier, 0) == 1;
364}
365
366/*
367 * Sets "extended type" of a channel; used by session layer to add additional
368 * information about channel types (e.g. shell, login, subsystem) that can then
369 * be used to select timeouts.
370 * Will reset c->inactive_deadline as a side-effect.
371 */
372void
373channel_set_xtype(struct ssh *ssh, int id, const char *xctype)
374{
375 Channel *c;
376
377 if ((c = channel_by_id(ssh, id)) == NULL)
378 fatal_f("missing channel %d", id);
379 if (c->xctype != NULL)
380 free(c->xctype);
381 c->xctype = xstrdup(xctype);
382 /* Type has changed, so look up inactivity deadline again */
383 c->inactive_deadline = lookup_timeout(ssh, c->xctype);
384 channel_classify(ssh, c);
385 debug2_f("labeled channel %d as %s (inactive timeout %u)", id, xctype,
386 c->inactive_deadline);
387}
388
389/*
390 * update "last used" time on a channel.
391 * NB. nothing else should update lastused except to clear it.
392 */
393static void
394channel_set_used_time(struct ssh *ssh, Channel *c)
395{
396 ssh->chanctxt->lastused = monotime();
397 if (c != NULL)
398 c->lastused = ssh->chanctxt->lastused;
399}
400
401/*
402 * Get the time at which a channel is due to time out for inactivity.
403 * Returns 0 if the channel is not due to time out ever.
404 */
405static time_t
406channel_get_expiry(struct ssh *ssh, Channel *c)
407{
408 struct ssh_channels *sc = ssh->chanctxt;
409 time_t expiry = 0, channel_expiry;
410
411 if (sc->lastused != 0 && sc->global_deadline != 0)
412 expiry = sc->lastused + sc->global_deadline;
413 if (c->lastused != 0 && c->inactive_deadline != 0) {
414 channel_expiry = c->lastused + c->inactive_deadline;
415 if (expiry == 0 || channel_expiry < expiry)
416 expiry = channel_expiry;
417 }
418 return expiry;
419}
420
421/* Returns non-zero if there is an open, non-interactive channel */
422int
423channel_has_bulk(struct ssh *ssh)
424{
425 return ssh->chanctxt != NULL && ssh->chanctxt->nbulk != 0;
426}
427
428/*
429 * Register filedescriptors for a channel, used when allocating a channel or
430 * when the channel consumer/producer is ready, e.g. shell exec'd
431 */
432static void
433channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
434 int extusage, int nonblock, int is_tty)
435{
436 int val;
437
438 if (rfd != -1)
439 (void)fcntl(rfd, F_SETFD, FD_CLOEXEC);
440 if (wfd != -1 && wfd != rfd)
441 (void)fcntl(wfd, F_SETFD, FD_CLOEXEC);
442 if (efd != -1 && efd != rfd && efd != wfd)
443 (void)fcntl(efd, F_SETFD, FD_CLOEXEC);
444
445 c->rfd = rfd;
446 c->wfd = wfd;
447 c->sock = (rfd == wfd) ? rfd : -1;
448 c->efd = efd;
449 c->extended_usage = extusage;
450
451 if ((c->isatty = is_tty) != 0)
452 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
453
454 /* enable nonblocking mode */
455 c->restore_block = 0;
456 if (nonblock == CHANNEL_NONBLOCK_STDIO) {
457 /*
458 * Special handling for stdio file descriptors: do not set
459 * non-blocking mode if they are TTYs. Otherwise prepare to
460 * restore their blocking state on exit to avoid interfering
461 * with other programs that follow.
462 */
463 if (rfd != -1 && !isatty(rfd) &&
464 (val = fcntl(rfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
465 c->restore_flags[0] = val;
466 c->restore_block |= CHANNEL_RESTORE_RFD;
467 set_nonblock(rfd);
468 }
469 if (wfd != -1 && !isatty(wfd) &&
470 (val = fcntl(wfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
471 c->restore_flags[1] = val;
472 c->restore_block |= CHANNEL_RESTORE_WFD;
473 set_nonblock(wfd);
474 }
475 if (efd != -1 && !isatty(efd) &&
476 (val = fcntl(efd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
477 c->restore_flags[2] = val;
478 c->restore_block |= CHANNEL_RESTORE_EFD;
479 set_nonblock(efd);
480 }
481 } else if (nonblock) {
482 if (rfd != -1)
483 set_nonblock(rfd);
484 if (wfd != -1)
485 set_nonblock(wfd);
486 if (efd != -1)
487 set_nonblock(efd);
488 }
489 /* channel might be entering a larval state, so reset global timeout */
490 channel_set_used_time(ssh, NULL);
491 channel_classify(ssh, c);
492}
493
494/*
495 * Allocate a new channel object and set its type and socket.
496 */
497Channel *
498channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
499 u_int window, u_int maxpack, int extusage, const char *remote_name,
500 int nonblock)
501{
502 struct ssh_channels *sc = ssh->chanctxt;
503 u_int i, found;
504 Channel *c;
505 int r;
506
507 /* Try to find a free slot where to put the new channel. */
508 for (i = 0; i < sc->channels_alloc; i++) {
509 if (sc->channels[i] == NULL) {
510 /* Found a free slot. */
511 found = i;
512 break;
513 }
514 }
515 if (i >= sc->channels_alloc) {
516 /*
517 * There are no free slots. Take last+1 slot and expand
518 * the array.
519 */
520 found = sc->channels_alloc;
521 if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
522 fatal_f("internal error: channels_alloc %d too big",
523 sc->channels_alloc);
524 sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
525 sc->channels_alloc + 10, sizeof(*sc->channels));
526 sc->channels_alloc += 10;
527 debug2("channel: expanding %d", sc->channels_alloc);
528 }
529 /* Initialize and return new channel. */
530 c = sc->channels[found] = xcalloc(1, sizeof(Channel));
531 if ((c->input = sshbuf_new()) == NULL ||
532 (c->output = sshbuf_new()) == NULL ||
533 (c->extended = sshbuf_new()) == NULL)
534 fatal_f("sshbuf_new failed");
535 if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
536 fatal_fr(r, "sshbuf_set_max_size");
537 c->ostate = CHAN_OUTPUT_OPEN;
538 c->istate = CHAN_INPUT_OPEN;
539 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
540 c->self = found;
541 c->type = type;
542 c->ctype = ctype;
543 c->local_window = window;
544 c->local_window_max = window;
545 c->local_maxpacket = maxpack;
546 c->remote_name = xstrdup(remote_name);
547 c->ctl_chan = -1;
548 c->delayed = 1; /* prevent call to channel_post handler */
549 c->inactive_deadline = lookup_timeout(ssh, c->ctype);
550 TAILQ_INIT(&c->status_confirms);
551 channel_classify(ssh, c);
552 debug("channel %d: new %s [%s] (inactive timeout: %u)",
553 found, c->ctype, remote_name, c->inactive_deadline);
554 return c;
555}
556
557void
558channel_set_tty(struct ssh *ssh, Channel *c)
559{
560 c->remote_has_tty = 1;
561 channel_classify(ssh, c);
562}
563
564int
565channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
566{
567 int ret, fd = *fdp;
568
569 if (fd == -1)
570 return 0;
571
572 /* restore blocking */
573 if (*fdp == c->rfd &&
574 (c->restore_block & CHANNEL_RESTORE_RFD) != 0)
575 (void)fcntl(*fdp, F_SETFL, c->restore_flags[0]);
576 else if (*fdp == c->wfd &&
577 (c->restore_block & CHANNEL_RESTORE_WFD) != 0)
578 (void)fcntl(*fdp, F_SETFL, c->restore_flags[1]);
579 else if (*fdp == c->efd &&
580 (c->restore_block & CHANNEL_RESTORE_EFD) != 0)
581 (void)fcntl(*fdp, F_SETFL, c->restore_flags[2]);
582
583 if (*fdp == c->rfd) {
584 c->io_want &= ~SSH_CHAN_IO_RFD;
585 c->io_ready &= ~SSH_CHAN_IO_RFD;
586 c->rfd = -1;
587 c->pfds[0] = -1;
588 }
589 if (*fdp == c->wfd) {
590 c->io_want &= ~SSH_CHAN_IO_WFD;
591 c->io_ready &= ~SSH_CHAN_IO_WFD;
592 c->wfd = -1;
593 c->pfds[1] = -1;
594 }
595 if (*fdp == c->efd) {
596 c->io_want &= ~SSH_CHAN_IO_EFD;
597 c->io_ready &= ~SSH_CHAN_IO_EFD;
598 c->efd = -1;
599 c->pfds[2] = -1;
600 }
601 if (*fdp == c->sock) {
602 c->io_want &= ~SSH_CHAN_IO_SOCK;
603 c->io_ready &= ~SSH_CHAN_IO_SOCK;
604 c->sock = -1;
605 c->pfds[3] = -1;
606 }
607
608 ret = close(fd);
609 *fdp = -1; /* probably redundant */
610 return ret;
611}
612
613/* Close all channel fd/socket. */
614static void
615channel_close_fds(struct ssh *ssh, Channel *c)
616{
617 int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
618
619 channel_close_fd(ssh, c, &c->sock);
620 if (rfd != sock)
621 channel_close_fd(ssh, c, &c->rfd);
622 if (wfd != sock && wfd != rfd)
623 channel_close_fd(ssh, c, &c->wfd);
624 if (efd != sock && efd != rfd && efd != wfd)
625 channel_close_fd(ssh, c, &c->efd);
626}
627
628static void
629fwd_perm_clear(struct permission *perm)
630{
631 free(perm->host_to_connect);
632 free(perm->listen_host);
633 free(perm->listen_path);
634 memset(perm, 0, sizeof(*perm));
635}
636
637/* Returns an printable name for the specified forwarding permission list */
638static const char *
639fwd_ident(int who, int where)
640{
641 if (who == FORWARD_ADM) {
642 if (where == FORWARD_LOCAL)
643 return "admin local";
644 else if (where == FORWARD_REMOTE)
645 return "admin remote";
646 } else if (who == FORWARD_USER) {
647 if (where == FORWARD_LOCAL)
648 return "user local";
649 else if (where == FORWARD_REMOTE)
650 return "user remote";
651 }
652 fatal("Unknown forward permission list %d/%d", who, where);
653}
654
655/* Returns the forwarding permission list for the specified direction */
656static struct permission_set *
657permission_set_get(struct ssh *ssh, int where)
658{
659 struct ssh_channels *sc = ssh->chanctxt;
660
661 switch (where) {
662 case FORWARD_LOCAL:
663 return &sc->local_perms;
664 break;
665 case FORWARD_REMOTE:
666 return &sc->remote_perms;
667 break;
668 default:
669 fatal_f("invalid forwarding direction %d", where);
670 }
671}
672
673/* Returns pointers to the specified forwarding list and its element count */
674static void
675permission_set_get_array(struct ssh *ssh, int who, int where,
676 struct permission ***permpp, u_int **npermpp)
677{
678 struct permission_set *pset = permission_set_get(ssh, where);
679
680 switch (who) {
681 case FORWARD_USER:
682 *permpp = &pset->permitted_user;
683 *npermpp = &pset->num_permitted_user;
684 break;
685 case FORWARD_ADM:
686 *permpp = &pset->permitted_admin;
687 *npermpp = &pset->num_permitted_admin;
688 break;
689 default:
690 fatal_f("invalid forwarding client %d", who);
691 }
692}
693
694/* Adds an entry to the specified forwarding list */
695static int
696permission_set_add(struct ssh *ssh, int who, int where,
697 const char *host_to_connect, int port_to_connect,
698 const char *listen_host, const char *listen_path, int listen_port,
699 Channel *downstream)
700{
701 struct permission **permp;
702 u_int n, *npermp;
703
704 permission_set_get_array(ssh, who, where, &permp, &npermp);
705
706 if (*npermp >= INT_MAX)
707 fatal_f("%s overflow", fwd_ident(who, where));
708
709 *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
710 n = (*npermp)++;
711#define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
712 (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
713 (*permp)[n].port_to_connect = port_to_connect;
714 (*permp)[n].listen_host = MAYBE_DUP(listen_host);
715 (*permp)[n].listen_path = MAYBE_DUP(listen_path);
716 (*permp)[n].listen_port = listen_port;
717 (*permp)[n].downstream = downstream;
718#undef MAYBE_DUP
719 return (int)n;
720}
721
722static void
723mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
724{
725 struct ssh_channels *sc = ssh->chanctxt;
726 struct permission_set *pset = &sc->local_perms;
727 struct permission *perm;
728 int r;
729 u_int i;
730
731 for (i = 0; i < pset->num_permitted_user; i++) {
732 perm = &pset->permitted_user[i];
733 if (perm->downstream != c)
734 continue;
735
736 /* cancel on the server, since mux client is gone */
737 debug("channel %d: cleanup remote forward for %s:%u",
738 c->self, perm->listen_host, perm->listen_port);
739 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
740 (r = sshpkt_put_cstring(ssh,
741 "cancel-tcpip-forward")) != 0 ||
742 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
743 (r = sshpkt_put_cstring(ssh,
744 channel_rfwd_bind_host(perm->listen_host))) != 0 ||
745 (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
746 (r = sshpkt_send(ssh)) != 0) {
747 fatal_fr(r, "channel %i", c->self);
748 }
749 fwd_perm_clear(perm); /* unregister */
750 }
751}
752
753/* Free the channel and close its fd/socket. */
754void
755channel_free(struct ssh *ssh, Channel *c)
756{
757 struct ssh_channels *sc = ssh->chanctxt;
758 char *s;
759 u_int i, n;
760 Channel *other;
761 struct channel_confirm *cc;
762
763 for (n = 0, i = 0; i < sc->channels_alloc; i++) {
764 if ((other = sc->channels[i]) == NULL)
765 continue;
766 n++;
767 /* detach from mux client and prepare for closing */
768 if (c->type == SSH_CHANNEL_MUX_CLIENT &&
769 other->type == SSH_CHANNEL_MUX_PROXY &&
770 other->mux_ctx == c) {
771 other->mux_ctx = NULL;
772 other->type = SSH_CHANNEL_OPEN;
773 other->istate = CHAN_INPUT_CLOSED;
774 other->ostate = CHAN_OUTPUT_CLOSED;
775 }
776 }
777 debug("channel %d: free: %s, nchannels %u", c->self,
778 c->remote_name ? c->remote_name : "???", n);
779
780 if (c->type == SSH_CHANNEL_MUX_CLIENT) {
781 mux_remove_remote_forwardings(ssh, c);
782 free(c->mux_ctx);
783 c->mux_ctx = NULL;
784 } else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
785 free(c->mux_ctx);
786 c->mux_ctx = NULL;
787 }
788
789 if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
790 s = channel_open_message(ssh);
791 debug3("channel %d: status: %s", c->self, s);
792 free(s);
793 }
794
795 channel_close_fds(ssh, c);
796 sshbuf_free(c->input);
797 sshbuf_free(c->output);
798 sshbuf_free(c->extended);
799 c->input = c->output = c->extended = NULL;
800 free(c->remote_name);
801 c->remote_name = NULL;
802 free(c->path);
803 c->path = NULL;
804 free(c->listening_addr);
805 c->listening_addr = NULL;
806 free(c->xctype);
807 c->xctype = NULL;
808 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
809 if (cc->abandon_cb != NULL)
810 cc->abandon_cb(ssh, c, cc->ctx);
811 TAILQ_REMOVE(&c->status_confirms, cc, entry);
812 freezero(cc, sizeof(*cc));
813 }
814 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
815 c->filter_cleanup(ssh, c->self, c->filter_ctx);
816 sc->channels[c->self] = NULL;
817 freezero(c, sizeof(*c));
818}
819
820void
821channel_free_all(struct ssh *ssh)
822{
823 u_int i;
824 struct ssh_channels *sc = ssh->chanctxt;
825
826 for (i = 0; i < sc->channels_alloc; i++)
827 if (sc->channels[i] != NULL)
828 channel_free(ssh, sc->channels[i]);
829
830 free(sc->channels);
831 sc->channels = NULL;
832 sc->channels_alloc = 0;
833
834 free(sc->x11_saved_display);
835 sc->x11_saved_display = NULL;
836
837 free(sc->x11_saved_proto);
838 sc->x11_saved_proto = NULL;
839
840 free(sc->x11_saved_data);
841 sc->x11_saved_data = NULL;
842 sc->x11_saved_data_len = 0;
843
844 free(sc->x11_fake_data);
845 sc->x11_fake_data = NULL;
846 sc->x11_fake_data_len = 0;
847}
848
849void
850channel_free_channels(struct ssh *ssh)
851{
852 struct ssh_channels *sc;
853
854 if (ssh == NULL || ssh->chanctxt == NULL)
855 return;
856 channel_free_all(ssh);
857 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
858 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
859 channel_clear_permission(ssh, FORWARD_ADM, FORWARD_LOCAL);
860 channel_clear_permission(ssh, FORWARD_ADM, FORWARD_REMOTE);
861 sc = ssh->chanctxt;
862 free(sc->bulk_classifier_tty);
863 free(sc->bulk_classifier_notty);
864 free(sc->channel_pre);
865 free(sc->channel_post);
866 freezero(sc, sizeof(*sc));
867 ssh->chanctxt = NULL;
868}
869
870/*
871 * Closes the sockets/fds of all channels. This is used to close extra file
872 * descriptors after a fork.
873 */
874void
875channel_close_all(struct ssh *ssh)
876{
877 u_int i;
878
879 for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
880 if (ssh->chanctxt->channels[i] != NULL)
881 channel_close_fds(ssh, ssh->chanctxt->channels[i]);
882}
883
884/*
885 * Stop listening to channels.
886 */
887void
888channel_stop_listening(struct ssh *ssh)
889{
890 u_int i;
891 Channel *c;
892
893 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
894 c = ssh->chanctxt->channels[i];
895 if (c != NULL) {
896 switch (c->type) {
897 case SSH_CHANNEL_AUTH_SOCKET:
898 case SSH_CHANNEL_PORT_LISTENER:
899 case SSH_CHANNEL_RPORT_LISTENER:
900 case SSH_CHANNEL_X11_LISTENER:
901 case SSH_CHANNEL_UNIX_LISTENER:
902 case SSH_CHANNEL_RUNIX_LISTENER:
903 channel_close_fd(ssh, c, &c->sock);
904 channel_free(ssh, c);
905 break;
906 }
907 }
908 }
909}
910
911/*
912 * Returns true if no channel has too much buffered data, and false if one or
913 * more channel is overfull.
914 */
915int
916channel_not_very_much_buffered_data(struct ssh *ssh)
917{
918 u_int i;
919 u_int maxsize = ssh_packet_get_maxsize(ssh);
920 Channel *c;
921
922 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
923 c = ssh->chanctxt->channels[i];
924 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
925 continue;
926 if (sshbuf_len(c->output) > maxsize) {
927 debug2("channel %d: big output buffer %zu > %u",
928 c->self, sshbuf_len(c->output), maxsize);
929 return 0;
930 }
931 }
932 return 1;
933}
934
935/* Returns true if any channel is still open. */
936int
937channel_still_open(struct ssh *ssh)
938{
939 u_int i;
940 Channel *c;
941
942 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
943 c = ssh->chanctxt->channels[i];
944 if (c == NULL)
945 continue;
946 switch (c->type) {
947 case SSH_CHANNEL_X11_LISTENER:
948 case SSH_CHANNEL_PORT_LISTENER:
949 case SSH_CHANNEL_RPORT_LISTENER:
950 case SSH_CHANNEL_MUX_LISTENER:
951 case SSH_CHANNEL_CLOSED:
952 case SSH_CHANNEL_AUTH_SOCKET:
953 case SSH_CHANNEL_DYNAMIC:
954 case SSH_CHANNEL_RDYNAMIC_OPEN:
955 case SSH_CHANNEL_CONNECTING:
956 case SSH_CHANNEL_ZOMBIE:
957 case SSH_CHANNEL_ABANDONED:
958 case SSH_CHANNEL_UNIX_LISTENER:
959 case SSH_CHANNEL_RUNIX_LISTENER:
960 continue;
961 case SSH_CHANNEL_LARVAL:
962 continue;
963 case SSH_CHANNEL_OPENING:
964 case SSH_CHANNEL_OPEN:
965 case SSH_CHANNEL_RDYNAMIC_FINISH:
966 case SSH_CHANNEL_X11_OPEN:
967 case SSH_CHANNEL_MUX_CLIENT:
968 case SSH_CHANNEL_MUX_PROXY:
969 return 1;
970 default:
971 fatal_f("bad channel type %d", c->type);
972 /* NOTREACHED */
973 }
974 }
975 return 0;
976}
977
978/* Returns true if a channel with a TTY is open. */
979int
980channel_tty_open(struct ssh *ssh)
981{
982 u_int i;
983 Channel *c;
984
985 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
986 c = ssh->chanctxt->channels[i];
987 if (c == NULL || c->type != SSH_CHANNEL_OPEN)
988 continue;
989 if (c->client_tty)
990 return 1;
991 }
992 return 0;
993}
994
995/* Returns the id of an open channel suitable for keepaliving */
996int
997channel_find_open(struct ssh *ssh)
998{
999 u_int i;
1000 Channel *c;
1001
1002 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
1003 c = ssh->chanctxt->channels[i];
1004 if (c == NULL || !c->have_remote_id)
1005 continue;
1006 switch (c->type) {
1007 case SSH_CHANNEL_CLOSED:
1008 case SSH_CHANNEL_DYNAMIC:
1009 case SSH_CHANNEL_RDYNAMIC_OPEN:
1010 case SSH_CHANNEL_RDYNAMIC_FINISH:
1011 case SSH_CHANNEL_X11_LISTENER:
1012 case SSH_CHANNEL_PORT_LISTENER:
1013 case SSH_CHANNEL_RPORT_LISTENER:
1014 case SSH_CHANNEL_MUX_LISTENER:
1015 case SSH_CHANNEL_MUX_CLIENT:
1016 case SSH_CHANNEL_MUX_PROXY:
1017 case SSH_CHANNEL_OPENING:
1018 case SSH_CHANNEL_CONNECTING:
1019 case SSH_CHANNEL_ZOMBIE:
1020 case SSH_CHANNEL_ABANDONED:
1021 case SSH_CHANNEL_UNIX_LISTENER:
1022 case SSH_CHANNEL_RUNIX_LISTENER:
1023 continue;
1024 case SSH_CHANNEL_LARVAL:
1025 case SSH_CHANNEL_AUTH_SOCKET:
1026 case SSH_CHANNEL_OPEN:
1027 case SSH_CHANNEL_X11_OPEN:
1028 return i;
1029 default:
1030 fatal_f("bad channel type %d", c->type);
1031 /* NOTREACHED */
1032 }
1033 }
1034 return -1;
1035}
1036
1037/* Returns the state of the channel's extended usage flag */
1038const char *
1039channel_format_extended_usage(const Channel *c)
1040{
1041 if (c->efd == -1)
1042 return "closed";
1043
1044 switch (c->extended_usage) {
1045 case CHAN_EXTENDED_WRITE:
1046 return "write";
1047 case CHAN_EXTENDED_READ:
1048 return "read";
1049 case CHAN_EXTENDED_IGNORE:
1050 return "ignore";
1051 default:
1052 return "UNKNOWN";
1053 }
1054}
1055
1056static char *
1057channel_format_status(const Channel *c)
1058{
1059 char *ret = NULL;
1060
1061 xasprintf(&ret, "t%d [%s] %s%u %s%u i%u/%zu o%u/%zu e[%s]/%zu "
1062 "fd %d/%d/%d sock %d cc %d %s%u io 0x%02x/0x%02x %s%s",
1063 c->type, c->xctype != NULL ? c->xctype : c->ctype,
1064 c->have_remote_id ? "r" : "nr", c->remote_id,
1065 c->mux_ctx != NULL ? "m" : "nm", c->mux_downstream_id,
1066 c->istate, sshbuf_len(c->input),
1067 c->ostate, sshbuf_len(c->output),
1068 channel_format_extended_usage(c), sshbuf_len(c->extended),
1069 c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan,
1070 c->have_ctl_child_id ? "c" : "nc", c->ctl_child_id,
1071 c->io_want, c->io_ready,
1072 c->isatty ? "T" : (c->remote_has_tty ? "RT" : ""),
1073 c->bulk ? "B" : "I");
1074 return ret;
1075}
1076
1077/*
1078 * Returns a message describing the currently open forwarded connections,
1079 * suitable for sending to the client. The message contains crlf pairs for
1080 * newlines.
1081 */
1082char *
1083channel_open_message(struct ssh *ssh)
1084{
1085 struct sshbuf *buf;
1086 Channel *c;
1087 u_int i;
1088 int r;
1089 char *cp, *ret;
1090
1091 if ((buf = sshbuf_new()) == NULL)
1092 fatal_f("sshbuf_new");
1093 if ((r = sshbuf_putf(buf,
1094 "The following connections are open:\r\n")) != 0)
1095 fatal_fr(r, "sshbuf_putf");
1096 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
1097 c = ssh->chanctxt->channels[i];
1098 if (c == NULL)
1099 continue;
1100 switch (c->type) {
1101 case SSH_CHANNEL_X11_LISTENER:
1102 case SSH_CHANNEL_PORT_LISTENER:
1103 case SSH_CHANNEL_RPORT_LISTENER:
1104 case SSH_CHANNEL_CLOSED:
1105 case SSH_CHANNEL_AUTH_SOCKET:
1106 case SSH_CHANNEL_ZOMBIE:
1107 case SSH_CHANNEL_ABANDONED:
1108 case SSH_CHANNEL_MUX_LISTENER:
1109 case SSH_CHANNEL_UNIX_LISTENER:
1110 case SSH_CHANNEL_RUNIX_LISTENER:
1111 continue;
1112 case SSH_CHANNEL_LARVAL:
1113 case SSH_CHANNEL_OPENING:
1114 case SSH_CHANNEL_CONNECTING:
1115 case SSH_CHANNEL_DYNAMIC:
1116 case SSH_CHANNEL_RDYNAMIC_OPEN:
1117 case SSH_CHANNEL_RDYNAMIC_FINISH:
1118 case SSH_CHANNEL_OPEN:
1119 case SSH_CHANNEL_X11_OPEN:
1120 case SSH_CHANNEL_MUX_PROXY:
1121 case SSH_CHANNEL_MUX_CLIENT:
1122 cp = channel_format_status(c);
1123 if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
1124 c->self, c->remote_name, cp)) != 0) {
1125 free(cp);
1126 fatal_fr(r, "sshbuf_putf");
1127 }
1128 free(cp);
1129 continue;
1130 default:
1131 fatal_f("bad channel type %d", c->type);
1132 /* NOTREACHED */
1133 }
1134 }
1135 if ((ret = sshbuf_dup_string(buf)) == NULL)
1136 fatal_f("sshbuf_dup_string");
1137 sshbuf_free(buf);
1138 return ret;
1139}
1140
1141void
1142channel_report_open(struct ssh *ssh, int level)
1143{
1144 char *open, *oopen, *cp, ident[256];
1145
1146 sshpkt_fmt_connection_id(ssh, ident, sizeof(ident));
1147 do_log2(level, "Connection: %s (pid %ld)", ident, (long)getpid());
1148 open = oopen = channel_open_message(ssh);
1149 while ((cp = strsep(&open, "\r\n")) != NULL) {
1150 if (*cp != '\0')
1151 do_log2(level, "%s", cp);
1152 }
1153 free(oopen);
1154}
1155
1156static void
1157open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
1158{
1159 int r;
1160
1161 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1162 (r = sshpkt_put_cstring(ssh, type)) != 0 ||
1163 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1164 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1165 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
1166 fatal_r(r, "%s: channel %i: open", where, c->self);
1167 }
1168}
1169
1170void
1171channel_send_open(struct ssh *ssh, int id)
1172{
1173 Channel *c = channel_lookup(ssh, id);
1174 int r;
1175
1176 if (c == NULL) {
1177 logit("channel_send_open: %d: bad id", id);
1178 return;
1179 }
1180 debug2("channel %d: send open", id);
1181 open_preamble(ssh, __func__, c, c->ctype);
1182 if ((r = sshpkt_send(ssh)) != 0)
1183 fatal_fr(r, "channel %i", c->self);
1184}
1185
1186void
1187channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
1188{
1189 Channel *c = channel_lookup(ssh, id);
1190 int r;
1191
1192 if (c == NULL) {
1193 logit_f("%d: unknown channel id", id);
1194 return;
1195 }
1196 if (!c->have_remote_id)
1197 fatal_f("channel %d: no remote id", c->self);
1198
1199 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1200 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
1201 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1202 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
1203 (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
1204 fatal_fr(r, "channel %i", c->self);
1205 }
1206}
1207
1208void
1209channel_register_status_confirm(struct ssh *ssh, int id,
1210 channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1211{
1212 struct channel_confirm *cc;
1213 Channel *c;
1214
1215 if ((c = channel_lookup(ssh, id)) == NULL)
1216 fatal_f("%d: bad id", id);
1217
1218 cc = xcalloc(1, sizeof(*cc));
1219 cc->cb = cb;
1220 cc->abandon_cb = abandon_cb;
1221 cc->ctx = ctx;
1222 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1223}
1224
1225void
1226channel_register_open_confirm(struct ssh *ssh, int id,
1227 channel_open_fn *fn, void *ctx)
1228{
1229 Channel *c = channel_lookup(ssh, id);
1230
1231 if (c == NULL) {
1232 logit_f("%d: bad id", id);
1233 return;
1234 }
1235 c->open_confirm = fn;
1236 c->open_confirm_ctx = ctx;
1237}
1238
1239void
1240channel_register_cleanup(struct ssh *ssh, int id,
1241 channel_callback_fn *fn, int do_close)
1242{
1243 Channel *c = channel_by_id(ssh, id);
1244
1245 if (c == NULL) {
1246 logit_f("%d: bad id", id);
1247 return;
1248 }
1249 c->detach_user = fn;
1250 c->detach_close = do_close;
1251}
1252
1253void
1254channel_cancel_cleanup(struct ssh *ssh, int id)
1255{
1256 Channel *c = channel_by_id(ssh, id);
1257
1258 if (c == NULL) {
1259 logit_f("%d: bad id", id);
1260 return;
1261 }
1262 c->detach_user = NULL;
1263 c->detach_close = 0;
1264}
1265
1266void
1267channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1268 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1269{
1270 Channel *c = channel_lookup(ssh, id);
1271
1272 if (c == NULL) {
1273 logit_f("%d: bad id", id);
1274 return;
1275 }
1276 c->input_filter = ifn;
1277 c->output_filter = ofn;
1278 c->filter_ctx = ctx;
1279 c->filter_cleanup = cfn;
1280}
1281
1282void
1283channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1284 int extusage, int nonblock, int is_tty, u_int window_max)
1285{
1286 Channel *c = channel_lookup(ssh, id);
1287 int r;
1288
1289 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1290 fatal("channel_activate for non-larval channel %d.", id);
1291 if (!c->have_remote_id)
1292 fatal_f("channel %d: no remote id", c->self);
1293
1294 channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1295 c->type = SSH_CHANNEL_OPEN;
1296 channel_set_used_time(ssh, c);
1297 c->local_window = c->local_window_max = window_max;
1298
1299 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1300 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1301 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1302 (r = sshpkt_send(ssh)) != 0)
1303 fatal_fr(r, "channel %i", c->self);
1304}
1305
1306static void
1307channel_pre_listener(struct ssh *ssh, Channel *c)
1308{
1309 c->io_want = SSH_CHAN_IO_SOCK_R;
1310}
1311
1312static void
1313channel_pre_connecting(struct ssh *ssh, Channel *c)
1314{
1315 debug3("channel %d: waiting for connection", c->self);
1316 c->io_want = SSH_CHAN_IO_SOCK_W;
1317}
1318
1319static void
1320channel_pre_open(struct ssh *ssh, Channel *c)
1321{
1322 c->io_want = 0;
1323 if (c->istate == CHAN_INPUT_OPEN &&
1324 c->remote_window > 0 &&
1325 sshbuf_len(c->input) < c->remote_window &&
1326 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1327 c->io_want |= SSH_CHAN_IO_RFD;
1328 if (c->ostate == CHAN_OUTPUT_OPEN ||
1329 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1330 if (sshbuf_len(c->output) > 0) {
1331 c->io_want |= SSH_CHAN_IO_WFD;
1332 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1333 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1334 debug2("channel %d: "
1335 "obuf_empty delayed efd %d/(%zu)", c->self,
1336 c->efd, sshbuf_len(c->extended));
1337 else
1338 chan_obuf_empty(ssh, c);
1339 }
1340 }
1341 /** XXX check close conditions, too */
1342 if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1343 c->ostate == CHAN_OUTPUT_CLOSED)) {
1344 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1345 sshbuf_len(c->extended) > 0)
1346 c->io_want |= SSH_CHAN_IO_EFD_W;
1347 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1348 (c->extended_usage == CHAN_EXTENDED_READ ||
1349 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1350 sshbuf_len(c->extended) < c->remote_window)
1351 c->io_want |= SSH_CHAN_IO_EFD_R;
1352 }
1353 /* XXX: What about efd? races? */
1354}
1355
1356/*
1357 * This is a special state for X11 authentication spoofing. An opened X11
1358 * connection (when authentication spoofing is being done) remains in this
1359 * state until the first packet has been completely read. The authentication
1360 * data in that packet is then substituted by the real data if it matches the
1361 * fake data, and the channel is put into normal mode.
1362 * XXX All this happens at the client side.
1363 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1364 */
1365static int
1366x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1367{
1368 struct ssh_channels *sc = ssh->chanctxt;
1369 u_char *ucp;
1370 u_int proto_len, data_len;
1371
1372 /* Is this being called after the refusal deadline? */
1373 if (sc->x11_refuse_time != 0 &&
1374 monotime() >= sc->x11_refuse_time) {
1375 verbose("Rejected X11 connection after ForwardX11Timeout "
1376 "expired");
1377 return -1;
1378 }
1379
1380 /* Check if the fixed size part of the packet is in buffer. */
1381 if (sshbuf_len(b) < 12)
1382 return 0;
1383
1384 /* Parse the lengths of variable-length fields. */
1385 ucp = sshbuf_mutable_ptr(b);
1386 if (ucp[0] == 0x42) { /* Byte order MSB first. */
1387 proto_len = 256 * ucp[6] + ucp[7];
1388 data_len = 256 * ucp[8] + ucp[9];
1389 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
1390 proto_len = ucp[6] + 256 * ucp[7];
1391 data_len = ucp[8] + 256 * ucp[9];
1392 } else {
1393 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1394 ucp[0]);
1395 return -1;
1396 }
1397
1398 /* Check if the whole packet is in buffer. */
1399 if (sshbuf_len(b) <
1400 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1401 return 0;
1402
1403 /* Check if authentication protocol matches. */
1404 if (proto_len != strlen(sc->x11_saved_proto) ||
1405 memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1406 debug2("X11 connection uses different authentication protocol.");
1407 return -1;
1408 }
1409 /* Check if authentication data matches our fake data. */
1410 if (data_len != sc->x11_fake_data_len ||
1411 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1412 sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1413 debug2("X11 auth data does not match fake data.");
1414 return -1;
1415 }
1416 /* Check fake data length */
1417 if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1418 error("X11 fake_data_len %d != saved_data_len %d",
1419 sc->x11_fake_data_len, sc->x11_saved_data_len);
1420 return -1;
1421 }
1422 /*
1423 * Received authentication protocol and data match
1424 * our fake data. Substitute the fake data with real
1425 * data.
1426 */
1427 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1428 sc->x11_saved_data, sc->x11_saved_data_len);
1429 return 1;
1430}
1431
1432void
1433channel_force_close(struct ssh *ssh, Channel *c, int abandon)
1434{
1435 debug3_f("channel %d: forcibly closing", c->self);
1436 if (c->istate == CHAN_INPUT_OPEN)
1437 chan_read_failed(ssh, c);
1438 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1439 sshbuf_reset(c->input);
1440 chan_ibuf_empty(ssh, c);
1441 }
1442 if (c->ostate == CHAN_OUTPUT_OPEN ||
1443 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1444 sshbuf_reset(c->output);
1445 chan_write_failed(ssh, c);
1446 }
1447 if (c->detach_user)
1448 c->detach_user(ssh, c->self, 1, NULL);
1449 if (c->efd != -1)
1450 channel_close_fd(ssh, c, &c->efd);
1451 if (abandon)
1452 c->type = SSH_CHANNEL_ABANDONED;
1453 /* exempt from inactivity timeouts */
1454 c->inactive_deadline = 0;
1455 c->lastused = 0;
1456}
1457
1458static void
1459channel_pre_x11_open(struct ssh *ssh, Channel *c)
1460{
1461 int ret = x11_open_helper(ssh, c->output);
1462
1463 /* c->force_drain = 1; */
1464
1465 if (ret == 1) {
1466 c->type = SSH_CHANNEL_OPEN;
1467 channel_set_used_time(ssh, c);
1468 channel_pre_open(ssh, c);
1469 } else if (ret == -1) {
1470 logit("X11 connection rejected because of wrong "
1471 "authentication.");
1472 debug2("X11 rejected %d i%d/o%d",
1473 c->self, c->istate, c->ostate);
1474 channel_force_close(ssh, c, 0);
1475 }
1476}
1477
1478static void
1479channel_pre_mux_client(struct ssh *ssh, Channel *c)
1480{
1481 c->io_want = 0;
1482 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1483 sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1484 c->io_want |= SSH_CHAN_IO_RFD;
1485 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1486 /* clear buffer immediately (discard any partial packet) */
1487 sshbuf_reset(c->input);
1488 chan_ibuf_empty(ssh, c);
1489 /* Start output drain. XXX just kill chan? */
1490 chan_rcvd_oclose(ssh, c);
1491 }
1492 if (c->ostate == CHAN_OUTPUT_OPEN ||
1493 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1494 if (sshbuf_len(c->output) > 0)
1495 c->io_want |= SSH_CHAN_IO_WFD;
1496 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1497 chan_obuf_empty(ssh, c);
1498 }
1499}
1500
1501static inline int
1502socks_decode_error(Channel *c, int status, const char *func, const char *msg)
1503{
1504 if (status == SSH_ERR_MESSAGE_INCOMPLETE)
1505 return 0;
1506 else {
1507 debug_r(status, "%s: channel %d: decode %s",
1508 func, c->self, msg);
1509 return -1;
1510 }
1511}
1512
1513/* try to decode a socks4 header */
1514static int
1515channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1516{
1517 uint8_t socks_ver, socks_cmd, dest_addr[4];
1518 uint16_t dest_port;
1519 char *user = NULL, *host = NULL;
1520 int success = -1, socks4a = 0, r;
1521 struct sshbuf *b = NULL;
1522
1523 if (sshbuf_len(input) < 9)
1524 return 0;
1525
1526 /* We may not have a complete message, so work on a dup of the buffer */
1527 if ((b = sshbuf_fromb(input)) == NULL)
1528 fatal_f("sshbuf_fromb failed");
1529
1530 debug2("channel %d: decode socks4", c->self);
1531 if ((r = sshbuf_get_u8(b, &socks_ver)) != 0 ||
1532 (r = sshbuf_get_u8(b, &socks_cmd)) != 0 ||
1533 (r = sshbuf_get_u16(b, &dest_port)) != 0 ||
1534 (r = sshbuf_get(b, &dest_addr, sizeof(dest_addr))) != 0 ||
1535 (r = sshbuf_get_nulterminated_string(b, 1024, &user, NULL)) != 0) {
1536 success = socks_decode_error(c, r, __func__, "header");
1537 goto out;
1538 }
1539
1540 /* Is this a SOCKS4A request? (indicated by an address of 0.0.0.x) */
1541 if (dest_addr[0] == 0 && dest_addr[1] == 0 &&
1542 dest_addr[2] == 0 && dest_addr[3] != 0) {
1543 /* If so, then the hostname follows, also nul-terminated */
1544 if ((r = sshbuf_get_nulterminated_string(b, 1024,
1545 &host, NULL)) != 0) {
1546 success = socks_decode_error(c, r, __func__, "host");
1547 goto out;
1548 }
1549 socks4a = 1;
1550 } else {
1551 /* Plain SOCKS4 passes an IPv4 binary address; reconstruct */
1552 xasprintf(&host, "%d.%d.%d.%d",
1553 dest_addr[0], dest_addr[1], dest_addr[2], dest_addr[3]);
1554 }
1555
1556 /* We have a complete SOCKS4 message; consume it from input */
1557 if ((r = sshbuf_consume_upto_child(input, b)) != 0)
1558 fatal_fr(r, "channel %d: consume", c->self);
1559
1560 /* Handle the request */
1561 debug2("channel %d: %s: user=\"%s\" command=%d destination=[%s]:%d",
1562 c->self, socks4a ? "SOCKS4A" : "SOCKS4", user, (int)socks_cmd,
1563 host, dest_port);
1564 if (socks_cmd != 1) {
1565 debug("channel %d: cannot handle %s command 0x%02x",
1566 c->self, socks4a ? "SOCKS4A" : "SOCKS4", socks_cmd);
1567 goto out;
1568 }
1569 free(c->path);
1570 c->path = host;
1571 host = NULL; /* transferred */
1572 c->host_port = dest_port;
1573
1574 /* Reply to the SOCKS4 client */
1575 if ((r = sshbuf_put_u8(output, 0)) != 0 || /* vn: 0 for reply */
1576 (r = sshbuf_put_u8(output, 90)) != 0 || /* cd: req granted */
1577 (r = sshbuf_put_u16(output, 0)) != 0 || /* port: ignored */
1578 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0) /* ignored */
1579 fatal_fr(r, "channel %d: compose reply", c->self);
1580
1581 /* success */
1582 success = 1;
1583 out:
1584 sshbuf_free(b);
1585 free(user);
1586 free(host);
1587 return success;
1588}
1589
1590/* try to decode a socks5 header */
1591#define SSH_SOCKS5_AUTHDONE 0x1000
1592#define SSH_SOCKS5_NOAUTH 0x00
1593#define SSH_SOCKS5_IPV4 0x01
1594#define SSH_SOCKS5_DOMAIN 0x03
1595#define SSH_SOCKS5_IPV6 0x04
1596#define SSH_SOCKS5_CONNECT 0x01
1597#define SSH_SOCKS5_SUCCESS 0x00
1598
1599/*
1600 * Handles SOCKS5 authentication. Note 'b' must be a dup of 'input'
1601 * Returns 0 on insufficient queued date, 1 on authentication success or
1602 * -1 on error.
1603 */
1604static int
1605channel_socks5_check_auth(Channel *c, struct sshbuf *b, struct sshbuf *input,
1606 struct sshbuf *output)
1607{
1608 uint8_t socks_ver;
1609 uint8_t nmethods, method;
1610 int r;
1611 u_int i, found;
1612
1613 /* format: ver | nmethods | methods */
1614 if ((r = sshbuf_get_u8(b, &socks_ver)) != 0)
1615 return socks_decode_error(c, r, __func__, "version");
1616 if (socks_ver != 5) /* shouldn't happen; checked by caller^2 */
1617 fatal_fr(r, "channel %d: internal error: not socks5", c->self);
1618 if ((r = sshbuf_get_u8(b, &nmethods)) != 0)
1619 return socks_decode_error(c, r, __func__, "methods");
1620 for (found = i = 0; i < nmethods; i++) {
1621 if ((r = sshbuf_get_u8(b, &method)) != 0)
1622 return socks_decode_error(c, r, __func__, "method");
1623 if (method == SSH_SOCKS5_NOAUTH)
1624 found = 1;
1625 }
1626 if (!found) {
1627 debug("channel %d: didn't request SSH_SOCKS5_NOAUTH", c->self);
1628 return -1;
1629 }
1630 /* Consume completed request */
1631 if ((r = sshbuf_consume_upto_child(input, b)) != 0)
1632 fatal_fr(r, "channel %d: consume", c->self);
1633
1634 /* Compose reply: version, method */
1635 if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1636 (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1637 fatal_fr(r, "channel %d: append reply", c->self);
1638 /* success */
1639 debug2("channel %d: socks5 auth done", c->self);
1640 return 1;
1641}
1642
1643static int
1644channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1645{
1646 uint8_t socks_ver, socks_cmd, socks_reserved, socks_atyp, addrlen;
1647 uint16_t dest_port;
1648 char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1649 u_int af;
1650 int r, success = -1;;
1651 struct sshbuf *b = NULL;
1652
1653 debug2("channel %d: decode socks5 %s", c->self,
1654 (c->flags & SSH_SOCKS5_AUTHDONE) ? "request" : "auth");
1655
1656 /* We may not have a complete message, so work on a dup of the buffer */
1657 if ((b = sshbuf_fromb(input)) == NULL)
1658 fatal_f("sshbuf_fromb failed");
1659
1660 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1661 if ((r = channel_socks5_check_auth(c, b, input, output)) != 1) {
1662 success = r;
1663 goto out;
1664 }
1665 c->flags |= SSH_SOCKS5_AUTHDONE;
1666 /* Continue to parse request in case client speculated ahead */
1667 }
1668
1669 /* Request messages (auth or connect) always start with the version */
1670 if ((r = sshbuf_get_u8(b, &socks_ver)) != 0) {
1671 success = socks_decode_error(c, r, __func__, "version");
1672 goto out;
1673 }
1674 if (socks_ver != 5) /* shouldn't happen */
1675 fatal_fr(r, "channel %d: internal error: not socks5", c->self);
1676
1677 /* Parse SOCKS5 request header */
1678 debug2("channel %d: socks5 post auth", c->self);
1679 if ((r = sshbuf_get_u8(b, &socks_cmd)) != 0 ||
1680 (r = sshbuf_get_u8(b, &socks_reserved)) != 0 ||
1681 (r = sshbuf_get_u8(b, &socks_atyp)) != 0) {
1682 success = socks_decode_error(c, r, __func__, "request header");
1683 goto out;
1684 }
1685
1686 if (socks_ver != 0x05 ||
1687 socks_cmd != SSH_SOCKS5_CONNECT ||
1688 socks_reserved != 0x00) {
1689 debug2("channel %d: only socks5 connect supported", c->self);
1690 goto out;
1691 }
1692
1693 switch (socks_atyp) {
1694 case SSH_SOCKS5_IPV4:
1695 addrlen = 4;
1696 af = AF_INET;
1697 break;
1698 case SSH_SOCKS5_DOMAIN:
1699 if ((r = sshbuf_get_u8(b, &addrlen)) != 0) {
1700 success = socks_decode_error(c, r, __func__, "addrlen");
1701 goto out;
1702 }
1703 af = -1;
1704 break;
1705 case SSH_SOCKS5_IPV6:
1706 addrlen = 16;
1707 af = AF_INET6;
1708 break;
1709 default:
1710 debug2("channel %d: bad socks5 atyp %d", c->self, socks_atyp);
1711 goto out;
1712 }
1713 if ((r = sshbuf_get(b, &dest_addr, addrlen)) != 0 ||
1714 (r = sshbuf_get_u16(b, &dest_port)) != 0) {
1715 success = socks_decode_error(c, r, __func__, "addr/port");
1716 goto out;
1717 }
1718 dest_addr[addrlen] = '\0';
1719
1720 /* We have a complete SOCKS5 request; consume it from input */
1721 if ((r = sshbuf_consume_upto_child(input, b)) != 0)
1722 fatal_fr(r, "channel %d: consume", c->self);
1723
1724 free(c->path);
1725 c->path = NULL;
1726 if (socks_atyp == SSH_SOCKS5_DOMAIN)
1727 c->path = xstrdup(dest_addr);
1728 else {
1729 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1730 return -1;
1731 c->path = xstrdup(ntop);
1732 }
1733 c->host_port = dest_port;
1734
1735 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1736 c->self, c->path, c->host_port, socks_cmd);
1737
1738 /* Reply */
1739 if ((r = sshbuf_put_u8(output, 0x05)) != 0 || /* version */
1740 (r = sshbuf_put_u8(output, SSH_SOCKS5_SUCCESS)) != 0 || /* cmd */
1741 (r = sshbuf_put_u8(output, 0)) != 0 || /* reserved, ignored */
1742 (r = sshbuf_put_u8(output, SSH_SOCKS5_IPV4)) != 0 || /* addrtype */
1743 (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 || /* addr */
1744 (r = sshbuf_put_u16(output, dest_port)) != 0) /* port */
1745 fatal_fr(r, "channel %d: append reply", c->self);
1746
1747 /* success */
1748 success = 1;
1749 out:
1750 sshbuf_free(b);
1751 return success;
1752}
1753
1754Channel *
1755channel_connect_stdio_fwd(struct ssh *ssh,
1756 const char *host_to_connect, int port_to_connect,
1757 int in, int out, int nonblock)
1758{
1759 Channel *c;
1760
1761 debug_f("%s:%d", host_to_connect, port_to_connect);
1762
1763 c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1764 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1765 0, "stdio-forward", nonblock);
1766
1767 c->path = xstrdup(host_to_connect);
1768 c->host_port = port_to_connect;
1769 c->listening_port = 0;
1770 c->force_drain = 1;
1771
1772 channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1773 port_open_helper(ssh, c, port_to_connect == PORT_STREAMLOCAL ?
1774 "direct-streamlocal@openssh.com" : "direct-tcpip");
1775
1776 return c;
1777}
1778
1779/* dynamic port forwarding */
1780static void
1781channel_pre_dynamic(struct ssh *ssh, Channel *c)
1782{
1783 u_int have;
1784 u_char ver;
1785 int r, ret;
1786
1787 c->io_want = 0;
1788 have = sshbuf_len(c->input);
1789 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1790 /* sshbuf_dump(c->input, stderr); */
1791 /* check if the fixed size part of the packet is in buffer. */
1792 if (have < 3) {
1793 /* need more */
1794 c->io_want |= SSH_CHAN_IO_RFD;
1795 return;
1796 }
1797 /* try to guess the protocol */
1798 if ((r = sshbuf_peek_u8(c->input, 0, &ver)) != 0)
1799 fatal_fr(r, "sshbuf_peek_u8");
1800 switch (ver) {
1801 case 0x04:
1802 ret = channel_decode_socks4(c, c->input, c->output);
1803 break;
1804 case 0x05:
1805 ret = channel_decode_socks5(c, c->input, c->output);
1806 break;
1807 default:
1808 debug2_f("channel %d: unknown SOCKS version %u", c->self, ver);
1809 ret = -1;
1810 break;
1811 }
1812 if (ret < 0) {
1813 chan_mark_dead(ssh, c);
1814 } else if (ret == 0) {
1815 debug2("channel %d: pre_dynamic: need more", c->self);
1816 /* need more */
1817 c->io_want |= SSH_CHAN_IO_RFD;
1818 if (sshbuf_len(c->output))
1819 c->io_want |= SSH_CHAN_IO_WFD;
1820 } else {
1821 /* switch to the next state */
1822 c->type = SSH_CHANNEL_OPENING;
1823 port_open_helper(ssh, c, "direct-tcpip");
1824 }
1825}
1826
1827/* simulate read-error */
1828static void
1829rdynamic_close(struct ssh *ssh, Channel *c)
1830{
1831 c->type = SSH_CHANNEL_OPEN;
1832 channel_force_close(ssh, c, 0);
1833}
1834
1835/* reverse dynamic port forwarding */
1836static void
1837channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1838{
1839 const u_char *p;
1840 u_int have, len;
1841 int r, ret;
1842
1843 have = sshbuf_len(c->output);
1844 debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1845 /* sshbuf_dump(c->output, stderr); */
1846 /* EOF received */
1847 if (c->flags & CHAN_EOF_RCVD) {
1848 if ((r = sshbuf_consume(c->output, have)) != 0)
1849 fatal_fr(r, "channel %d: consume", c->self);
1850 rdynamic_close(ssh, c);
1851 return;
1852 }
1853 /* check if the fixed size part of the packet is in buffer. */
1854 if (have < 3)
1855 return;
1856 /* try to guess the protocol */
1857 p = sshbuf_ptr(c->output);
1858 switch (p[0]) {
1859 case 0x04:
1860 /* switch input/output for reverse forwarding */
1861 ret = channel_decode_socks4(c, c->output, c->input);
1862 break;
1863 case 0x05:
1864 ret = channel_decode_socks5(c, c->output, c->input);
1865 break;
1866 default:
1867 ret = -1;
1868 break;
1869 }
1870 if (ret < 0) {
1871 rdynamic_close(ssh, c);
1872 } else if (ret == 0) {
1873 debug2("channel %d: pre_rdynamic: need more", c->self);
1874 /* send socks request to peer */
1875 len = sshbuf_len(c->input);
1876 if (len > 0 && len < c->remote_window) {
1877 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1878 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1879 (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1880 (r = sshpkt_send(ssh)) != 0) {
1881 fatal_fr(r, "channel %i: rdynamic", c->self);
1882 }
1883 if ((r = sshbuf_consume(c->input, len)) != 0)
1884 fatal_fr(r, "channel %d: consume", c->self);
1885 c->remote_window -= len;
1886 }
1887 } else if (rdynamic_connect_finish(ssh, c) < 0) {
1888 /* the connect failed */
1889 rdynamic_close(ssh, c);
1890 }
1891}
1892
1893/* This is our fake X11 server socket. */
1894static void
1895channel_post_x11_listener(struct ssh *ssh, Channel *c)
1896{
1897 Channel *nc;
1898 struct sockaddr_storage addr;
1899 int r, newsock, oerrno, remote_port;
1900 socklen_t addrlen;
1901 char buf[16384], *remote_ipaddr;
1902
1903 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1904 return;
1905
1906 debug("X11 connection requested.");
1907 addrlen = sizeof(addr);
1908 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1909 if (c->single_connection) {
1910 oerrno = errno;
1911 debug2("single_connection: closing X11 listener.");
1912 channel_close_fd(ssh, c, &c->sock);
1913 chan_mark_dead(ssh, c);
1914 errno = oerrno;
1915 }
1916 if (newsock == -1) {
1917 if (errno != EINTR && errno != EWOULDBLOCK &&
1918 errno != ECONNABORTED)
1919 error("accept: %.100s", strerror(errno));
1920 if (errno == EMFILE || errno == ENFILE)
1921 c->notbefore = monotime() + 1;
1922 return;
1923 }
1924 set_nodelay(newsock);
1925 remote_ipaddr = get_peer_ipaddr(newsock);
1926 remote_port = get_peer_port(newsock);
1927 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1928 remote_ipaddr, remote_port);
1929
1930 nc = channel_new(ssh, "x11-connection",
1931 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1932 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1933 open_preamble(ssh, __func__, nc, "x11");
1934 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1935 (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1936 fatal_fr(r, "channel %i: reply", c->self);
1937 }
1938 if ((r = sshpkt_send(ssh)) != 0)
1939 fatal_fr(r, "channel %i: send", c->self);
1940 free(remote_ipaddr);
1941}
1942
1943static void
1944port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1945{
1946 char *local_ipaddr = get_local_ipaddr(c->sock);
1947 int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1948 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1949 int remote_port = get_peer_port(c->sock);
1950 int r;
1951
1952 if (remote_port == -1) {
1953 /* Fake addr/port to appease peers that validate it (Tectia) */
1954 free(remote_ipaddr);
1955 remote_ipaddr = xstrdup("127.0.0.1");
1956 remote_port = 65535;
1957 }
1958
1959 free(c->remote_name);
1960 xasprintf(&c->remote_name,
1961 "%s: listening port %d for %.100s port %d, "
1962 "connect from %.200s port %d to %.100s port %d",
1963 rtype, c->listening_port, c->path, c->host_port,
1964 remote_ipaddr, remote_port, local_ipaddr, local_port);
1965
1966 open_preamble(ssh, __func__, c, rtype);
1967 if (strcmp(rtype, "direct-tcpip") == 0) {
1968 /* target host, port */
1969 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1970 (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1971 fatal_fr(r, "channel %i: reply", c->self);
1972 } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1973 /* target path */
1974 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1975 fatal_fr(r, "channel %i: reply", c->self);
1976 } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1977 /* listen path */
1978 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1979 fatal_fr(r, "channel %i: reply", c->self);
1980 } else {
1981 /* listen address, port */
1982 if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1983 (r = sshpkt_put_u32(ssh, local_port)) != 0)
1984 fatal_fr(r, "channel %i: reply", c->self);
1985 }
1986 if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1987 /* reserved for future owner/mode info */
1988 if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1989 fatal_fr(r, "channel %i: reply", c->self);
1990 } else {
1991 /* originator host and port */
1992 if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1993 (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1994 fatal_fr(r, "channel %i: reply", c->self);
1995 }
1996 if ((r = sshpkt_send(ssh)) != 0)
1997 fatal_fr(r, "channel %i: send", c->self);
1998 free(remote_ipaddr);
1999 free(local_ipaddr);
2000}
2001
2002void
2003channel_set_x11_refuse_time(struct ssh *ssh, time_t refuse_time)
2004{
2005 ssh->chanctxt->x11_refuse_time = refuse_time;
2006}
2007
2008/*
2009 * This socket is listening for connections to a forwarded TCP/IP port.
2010 */
2011static void
2012channel_post_port_listener(struct ssh *ssh, Channel *c)
2013{
2014 Channel *nc;
2015 struct sockaddr_storage addr;
2016 int newsock, nextstate;
2017 socklen_t addrlen;
2018 char *rtype;
2019
2020 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2021 return;
2022
2023 debug("Connection to port %d forwarding to %.100s port %d requested.",
2024 c->listening_port, c->path, c->host_port);
2025
2026 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
2027 nextstate = SSH_CHANNEL_OPENING;
2028 rtype = "forwarded-tcpip";
2029 } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
2030 nextstate = SSH_CHANNEL_OPENING;
2031 rtype = "forwarded-streamlocal@openssh.com";
2032 } else if (c->host_port == PORT_STREAMLOCAL) {
2033 nextstate = SSH_CHANNEL_OPENING;
2034 rtype = "direct-streamlocal@openssh.com";
2035 } else if (c->host_port == 0) {
2036 nextstate = SSH_CHANNEL_DYNAMIC;
2037 rtype = "dynamic-tcpip";
2038 } else {
2039 nextstate = SSH_CHANNEL_OPENING;
2040 rtype = "direct-tcpip";
2041 }
2042
2043 addrlen = sizeof(addr);
2044 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
2045 if (newsock == -1) {
2046 if (errno != EINTR && errno != EWOULDBLOCK &&
2047 errno != ECONNABORTED)
2048 error("accept: %.100s", strerror(errno));
2049 if (errno == EMFILE || errno == ENFILE)
2050 c->notbefore = monotime() + 1;
2051 return;
2052 }
2053 if (c->host_port != PORT_STREAMLOCAL)
2054 set_nodelay(newsock);
2055 nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
2056 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
2057 nc->listening_port = c->listening_port;
2058 nc->host_port = c->host_port;
2059 if (c->path != NULL)
2060 nc->path = xstrdup(c->path);
2061
2062 if (nextstate != SSH_CHANNEL_DYNAMIC)
2063 port_open_helper(ssh, nc, rtype);
2064}
2065
2066/*
2067 * This is the authentication agent socket listening for connections from
2068 * clients.
2069 */
2070static void
2071channel_post_auth_listener(struct ssh *ssh, Channel *c)
2072{
2073 Channel *nc;
2074 int r, newsock;
2075 struct sockaddr_storage addr;
2076 socklen_t addrlen;
2077
2078 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2079 return;
2080
2081 addrlen = sizeof(addr);
2082 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
2083 if (newsock == -1) {
2084 error("accept from auth socket: %.100s", strerror(errno));
2085 if (errno == EMFILE || errno == ENFILE)
2086 c->notbefore = monotime() + 1;
2087 return;
2088 }
2089 nc = channel_new(ssh, "agent-connection",
2090 SSH_CHANNEL_OPENING, newsock, newsock, -1,
2091 c->local_window_max, c->local_maxpacket,
2092 0, "accepted auth socket", 1);
2093 open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
2094 if ((r = sshpkt_send(ssh)) != 0)
2095 fatal_fr(r, "channel %i", c->self);
2096}
2097
2098static void
2099channel_post_connecting(struct ssh *ssh, Channel *c)
2100{
2101 int err = 0, sock, isopen, r;
2102 socklen_t sz = sizeof(err);
2103
2104 if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
2105 return;
2106 if (!c->have_remote_id)
2107 fatal_f("channel %d: no remote id", c->self);
2108 /* for rdynamic the OPEN_CONFIRMATION has been sent already */
2109 isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
2110
2111 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
2112 err = errno;
2113 error("getsockopt SO_ERROR failed");
2114 }
2115
2116 if (err == 0) {
2117 /* Non-blocking connection completed */
2118 debug("channel %d: connected to %s port %d",
2119 c->self, c->connect_ctx.host, c->connect_ctx.port);
2120 channel_connect_ctx_free(&c->connect_ctx);
2121 c->type = SSH_CHANNEL_OPEN;
2122 channel_set_used_time(ssh, c);
2123 if (isopen) {
2124 /* no message necessary */
2125 } else {
2126 if ((r = sshpkt_start(ssh,
2127 SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
2128 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2129 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
2130 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
2131 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
2132 (r = sshpkt_send(ssh)) != 0)
2133 fatal_fr(r, "channel %i open confirm", c->self);
2134 }
2135 return;
2136 }
2137 if (err == EINTR || err == EAGAIN || err == EINPROGRESS)
2138 return;
2139
2140 /* Non-blocking connection failed */
2141 debug("channel %d: connection failed: %s", c->self, strerror(err));
2142
2143 /* Try next address, if any */
2144 if ((sock = connect_next(&c->connect_ctx)) == -1) {
2145 /* Exhausted all addresses for this destination */
2146 error("connect_to %.100s port %d: failed.",
2147 c->connect_ctx.host, c->connect_ctx.port);
2148 channel_connect_ctx_free(&c->connect_ctx);
2149 if (isopen) {
2150 rdynamic_close(ssh, c);
2151 } else {
2152 if ((r = sshpkt_start(ssh,
2153 SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
2154 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2155 (r = sshpkt_put_u32(ssh,
2156 SSH2_OPEN_CONNECT_FAILED)) != 0 ||
2157 (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
2158 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2159 (r = sshpkt_send(ssh)) != 0)
2160 fatal_fr(r, "channel %i: failure", c->self);
2161 chan_mark_dead(ssh, c);
2162 }
2163 }
2164
2165 /* New non-blocking connection in progress */
2166 close(c->sock);
2167 c->sock = c->rfd = c->wfd = sock;
2168}
2169
2170static int
2171channel_handle_rfd(struct ssh *ssh, Channel *c)
2172{
2173 char buf[CHAN_RBUF];
2174 ssize_t len;
2175 int r;
2176 size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
2177
2178 if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2179 return 1; /* Shouldn't happen */
2180 if ((avail = sshbuf_avail(c->input)) == 0)
2181 return 1; /* Shouldn't happen */
2182
2183 /*
2184 * For "simple" channels (i.e. not datagram or filtered), we can
2185 * read directly to the channel buffer.
2186 */
2187 if (c->input_filter == NULL && !c->datagram) {
2188 /* Only OPEN channels have valid rwin */
2189 if (c->type == SSH_CHANNEL_OPEN) {
2190 if ((have = sshbuf_len(c->input)) >= c->remote_window)
2191 return 1; /* shouldn't happen */
2192 if (maxlen > c->remote_window - have)
2193 maxlen = c->remote_window - have;
2194 }
2195 if (maxlen > avail)
2196 maxlen = avail;
2197 if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
2198 if (errno == EINTR || errno == EAGAIN)
2199 return 1;
2200 debug2("channel %d: read failed rfd %d maxlen %zu: %s",
2201 c->self, c->rfd, maxlen, ssh_err(r));
2202 goto rfail;
2203 }
2204 if (nr != 0)
2205 channel_set_used_time(ssh, c);
2206 return 1;
2207 }
2208
2209 len = read(c->rfd, buf, sizeof(buf));
2210 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2211 return 1;
2212 if (len <= 0) {
2213 debug2("channel %d: read<=0 rfd %d len %zd: %s",
2214 c->self, c->rfd, len,
2215 len == 0 ? "closed" : strerror(errno));
2216 rfail:
2217 if (c->type != SSH_CHANNEL_OPEN) {
2218 debug2("channel %d: not open", c->self);
2219 chan_mark_dead(ssh, c);
2220 return -1;
2221 } else {
2222 chan_read_failed(ssh, c);
2223 }
2224 return -1;
2225 }
2226 channel_set_used_time(ssh, c);
2227 if (c->input_filter != NULL) {
2228 if (c->input_filter(ssh, c, buf, len) == -1) {
2229 debug2("channel %d: filter stops", c->self);
2230 chan_read_failed(ssh, c);
2231 }
2232 } else if (c->datagram) {
2233 if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
2234 fatal_fr(r, "channel %i: put datagram", c->self);
2235 }
2236 return 1;
2237}
2238
2239static int
2240channel_handle_wfd(struct ssh *ssh, Channel *c)
2241{
2242 struct termios tio;
2243 u_char *data = NULL, *buf; /* XXX const; need filter API change */
2244 size_t dlen, olen = 0;
2245 int r, len;
2246
2247 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2248 return 1;
2249 if (sshbuf_len(c->output) == 0)
2250 return 1;
2251
2252 /* Send buffered output data to the socket. */
2253 olen = sshbuf_len(c->output);
2254 if (c->output_filter != NULL) {
2255 if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2256 debug2("channel %d: filter stops", c->self);
2257 if (c->type != SSH_CHANNEL_OPEN)
2258 chan_mark_dead(ssh, c);
2259 else
2260 chan_write_failed(ssh, c);
2261 return -1;
2262 }
2263 } else if (c->datagram) {
2264 if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2265 fatal_fr(r, "channel %i: get datagram", c->self);
2266 buf = data;
2267 } else {
2268 buf = data = sshbuf_mutable_ptr(c->output);
2269 dlen = sshbuf_len(c->output);
2270 }
2271
2272 if (c->datagram) {
2273 /* ignore truncated writes, datagrams might get lost */
2274 len = write(c->wfd, buf, dlen);
2275 free(data);
2276 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2277 return 1;
2278 if (len <= 0)
2279 goto write_fail;
2280 goto out;
2281 }
2282
2283 len = write(c->wfd, buf, dlen);
2284 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2285 return 1;
2286 if (len <= 0) {
2287 write_fail:
2288 if (c->type != SSH_CHANNEL_OPEN) {
2289 debug2("channel %d: not open", c->self);
2290 chan_mark_dead(ssh, c);
2291 return -1;
2292 } else {
2293 chan_write_failed(ssh, c);
2294 }
2295 return -1;
2296 }
2297 channel_set_used_time(ssh, c);
2298 if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2299 if (tcgetattr(c->wfd, &tio) == 0 &&
2300 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2301 /*
2302 * Simulate echo to reduce the impact of
2303 * traffic analysis. We need to match the
2304 * size of a SSH2_MSG_CHANNEL_DATA message
2305 * (4 byte channel id + buf)
2306 */
2307 if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2308 (r = sshpkt_send(ssh)) != 0)
2309 fatal_fr(r, "channel %i: ignore", c->self);
2310 }
2311 }
2312 if ((r = sshbuf_consume(c->output, len)) != 0)
2313 fatal_fr(r, "channel %i: consume", c->self);
2314 out:
2315 c->local_consumed += olen - sshbuf_len(c->output);
2316
2317 return 1;
2318}
2319
2320static int
2321channel_handle_efd_write(struct ssh *ssh, Channel *c)
2322{
2323 int r;
2324 ssize_t len;
2325
2326 if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2327 return 1;
2328 if (sshbuf_len(c->extended) == 0)
2329 return 1;
2330
2331 len = write(c->efd, sshbuf_ptr(c->extended),
2332 sshbuf_len(c->extended));
2333 debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2334 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2335 return 1;
2336 if (len <= 0) {
2337 debug2("channel %d: closing write-efd %d", c->self, c->efd);
2338 channel_close_fd(ssh, c, &c->efd);
2339 } else {
2340 if ((r = sshbuf_consume(c->extended, len)) != 0)
2341 fatal_fr(r, "channel %i: consume", c->self);
2342 c->local_consumed += len;
2343 channel_set_used_time(ssh, c);
2344 }
2345 return 1;
2346}
2347
2348static int
2349channel_handle_efd_read(struct ssh *ssh, Channel *c)
2350{
2351 char buf[CHAN_RBUF];
2352 int r;
2353 ssize_t len;
2354
2355 if ((c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2356 return 1;
2357
2358 len = read(c->efd, buf, sizeof(buf));
2359 debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2360 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2361 return 1;
2362 if (len <= 0) {
2363 debug2("channel %d: closing read-efd %d", c->self, c->efd);
2364 channel_close_fd(ssh, c, &c->efd);
2365 return 1;
2366 }
2367 channel_set_used_time(ssh, c);
2368 if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2369 debug3("channel %d: discard efd", c->self);
2370 else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2371 fatal_fr(r, "channel %i: append", c->self);
2372 return 1;
2373}
2374
2375static int
2376channel_handle_efd(struct ssh *ssh, Channel *c)
2377{
2378 if (c->efd == -1)
2379 return 1;
2380
2381 /** XXX handle drain efd, too */
2382
2383 if (c->extended_usage == CHAN_EXTENDED_WRITE)
2384 return channel_handle_efd_write(ssh, c);
2385 else if (c->extended_usage == CHAN_EXTENDED_READ ||
2386 c->extended_usage == CHAN_EXTENDED_IGNORE)
2387 return channel_handle_efd_read(ssh, c);
2388
2389 return 1;
2390}
2391
2392static int
2393channel_check_window(struct ssh *ssh, Channel *c)
2394{
2395 int r;
2396
2397 if (c->type == SSH_CHANNEL_OPEN &&
2398 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2399 ((c->local_window_max - c->local_window >
2400 c->local_maxpacket*3) ||
2401 c->local_window < c->local_window_max/2) &&
2402 c->local_consumed > 0) {
2403 if (!c->have_remote_id)
2404 fatal_f("channel %d: no remote id", c->self);
2405 if ((r = sshpkt_start(ssh,
2406 SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2407 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2408 (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2409 (r = sshpkt_send(ssh)) != 0) {
2410 fatal_fr(r, "channel %i", c->self);
2411 }
2412 debug2("channel %d: window %d sent adjust %d", c->self,
2413 c->local_window, c->local_consumed);
2414 c->local_window += c->local_consumed;
2415 c->local_consumed = 0;
2416 }
2417 return 1;
2418}
2419
2420static void
2421channel_post_open(struct ssh *ssh, Channel *c)
2422{
2423 channel_handle_rfd(ssh, c);
2424 channel_handle_wfd(ssh, c);
2425 channel_handle_efd(ssh, c);
2426 channel_check_window(ssh, c);
2427}
2428
2429static u_int
2430read_mux(struct ssh *ssh, Channel *c, u_int need)
2431{
2432 char buf[CHAN_RBUF];
2433 ssize_t len;
2434 u_int rlen;
2435 int r;
2436
2437 if (sshbuf_len(c->input) < need) {
2438 rlen = need - sshbuf_len(c->input);
2439 len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2440 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2441 return sshbuf_len(c->input);
2442 if (len <= 0) {
2443 debug2("channel %d: ctl read<=0 rfd %d len %zd",
2444 c->self, c->rfd, len);
2445 chan_read_failed(ssh, c);
2446 return 0;
2447 } else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2448 fatal_fr(r, "channel %i: append", c->self);
2449 }
2450 return sshbuf_len(c->input);
2451}
2452
2453static void
2454channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2455{
2456 u_int need;
2457
2458 if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2459 return;
2460 if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2461 return;
2462 if (c->mux_pause)
2463 return;
2464
2465 /*
2466 * Don't not read past the precise end of packets to
2467 * avoid disrupting fd passing.
2468 */
2469 if (read_mux(ssh, c, 4) < 4) /* read header */
2470 return;
2471 /* XXX sshbuf_peek_u32 */
2472 need = PEEK_U32(sshbuf_ptr(c->input));
2473#define CHANNEL_MUX_MAX_PACKET (256 * 1024)
2474 if (need > CHANNEL_MUX_MAX_PACKET) {
2475 debug2("channel %d: packet too big %u > %u",
2476 c->self, CHANNEL_MUX_MAX_PACKET, need);
2477 chan_rcvd_oclose(ssh, c);
2478 return;
2479 }
2480 if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2481 return;
2482 if (c->mux_rcb(ssh, c) != 0) {
2483 debug("channel %d: mux_rcb failed", c->self);
2484 chan_mark_dead(ssh, c);
2485 return;
2486 }
2487}
2488
2489static void
2490channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2491{
2492 ssize_t len;
2493 int r;
2494
2495 if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2496 return;
2497 if (sshbuf_len(c->output) == 0)
2498 return;
2499
2500 len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2501 if (len == -1 && (errno == EINTR || errno == EAGAIN))
2502 return;
2503 if (len <= 0) {
2504 chan_mark_dead(ssh, c);
2505 return;
2506 }
2507 if ((r = sshbuf_consume(c->output, len)) != 0)
2508 fatal_fr(r, "channel %i: consume", c->self);
2509}
2510
2511static void
2512channel_post_mux_client(struct ssh *ssh, Channel *c)
2513{
2514 channel_post_mux_client_read(ssh, c);
2515 channel_post_mux_client_write(ssh, c);
2516}
2517
2518static void
2519channel_post_mux_listener(struct ssh *ssh, Channel *c)
2520{
2521 Channel *nc;
2522 struct sockaddr_storage addr;
2523 socklen_t addrlen;
2524 int newsock;
2525 uid_t euid;
2526 gid_t egid;
2527
2528 if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2529 return;
2530
2531 debug("multiplexing control connection");
2532
2533 /*
2534 * Accept connection on control socket
2535 */
2536 memset(&addr, 0, sizeof(addr));
2537 addrlen = sizeof(addr);
2538 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2539 &addrlen)) == -1) {
2540 error_f("accept: %s", strerror(errno));
2541 if (errno == EMFILE || errno == ENFILE)
2542 c->notbefore = monotime() + 1;
2543 return;
2544 }
2545
2546 if (getpeereid(newsock, &euid, &egid) == -1) {
2547 error_f("getpeereid failed: %s", strerror(errno));
2548 close(newsock);
2549 return;
2550 }
2551 if ((euid != 0) && (getuid() != euid)) {
2552 error("multiplex uid mismatch: peer euid %u != uid %u",
2553 (u_int)euid, (u_int)getuid());
2554 close(newsock);
2555 return;
2556 }
2557 nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
2558 newsock, newsock, -1, c->local_window_max,
2559 c->local_maxpacket, 0, "mux-control", 1);
2560 nc->mux_rcb = c->mux_rcb;
2561 debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2562 /* establish state */
2563 nc->mux_rcb(ssh, nc);
2564 /* mux state transitions must not elicit protocol messages */
2565 nc->flags |= CHAN_LOCAL;
2566}
2567
2568static void
2569channel_handler_init(struct ssh_channels *sc)
2570{
2571 chan_fn **pre, **post;
2572
2573 if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2574 (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2575 fatal_f("allocation failed");
2576
2577 pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2578 pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2579 pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2580 pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2581 pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
2582 pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
2583 pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2584 pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2585 pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2586 pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2587 pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
2588 pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2589 pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2590
2591 post[SSH_CHANNEL_OPEN] = &channel_post_open;
2592 post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2593 post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2594 post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
2595 post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
2596 post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2597 post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2598 post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2599 post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2600 post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
2601 post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2602 post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2603
2604 sc->channel_pre = pre;
2605 sc->channel_post = post;
2606}
2607
2608/* gc dead channels */
2609static void
2610channel_garbage_collect(struct ssh *ssh, Channel *c)
2611{
2612 if (c == NULL)
2613 return;
2614 if (c->detach_user != NULL) {
2615 if (!chan_is_dead(ssh, c, c->detach_close))
2616 return;
2617
2618 debug2("channel %d: gc: notify user", c->self);
2619 c->detach_user(ssh, c->self, 0, NULL);
2620 /* if we still have a callback */
2621 if (c->detach_user != NULL)
2622 return;
2623 debug2("channel %d: gc: user detached", c->self);
2624 }
2625 if (!chan_is_dead(ssh, c, 1))
2626 return;
2627 debug2("channel %d: garbage collecting", c->self);
2628 channel_free(ssh, c);
2629}
2630
2631enum channel_table { CHAN_PRE, CHAN_POST };
2632
2633static void
2634channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
2635{
2636 struct ssh_channels *sc = ssh->chanctxt;
2637 chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2638 u_int i, oalloc;
2639 Channel *c;
2640 time_t now;
2641
2642 now = monotime();
2643 for (sc->nbulk = i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2644 c = sc->channels[i];
2645 if (c == NULL)
2646 continue;
2647 /* Count open channels in bulk state */
2648 if (c->type == SSH_CHANNEL_OPEN && c->bulk)
2649 sc->nbulk++;
2650 /* Try to keep IO going while rekeying */
2651 if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
2652 continue;
2653 if (c->delayed) {
2654 if (table == CHAN_PRE)
2655 c->delayed = 0;
2656 else
2657 continue;
2658 }
2659 if (ftab[c->type] != NULL) {
2660 if (table == CHAN_PRE && c->type == SSH_CHANNEL_OPEN &&
2661 channel_get_expiry(ssh, c) != 0 &&
2662 now >= channel_get_expiry(ssh, c)) {
2663 /* channel closed for inactivity */
2664 verbose("channel %d: closing after %u seconds "
2665 "of inactivity", c->self,
2666 c->inactive_deadline);
2667 channel_force_close(ssh, c, 1);
2668 } else if (c->notbefore <= now) {
2669 /* Run handlers that are not paused. */
2670 (*ftab[c->type])(ssh, c);
2671 /* inactivity timeouts must interrupt poll() */
2672 if (timeout != NULL &&
2673 c->type == SSH_CHANNEL_OPEN &&
2674 channel_get_expiry(ssh, c) != 0) {
2675 ptimeout_deadline_monotime(timeout,
2676 channel_get_expiry(ssh, c));
2677 }
2678 } else if (timeout != NULL) {
2679 /*
2680 * Arrange for poll() wakeup when channel pause
2681 * timer expires.
2682 */
2683 ptimeout_deadline_monotime(timeout,
2684 c->notbefore);
2685 }
2686 }
2687 channel_garbage_collect(ssh, c);
2688 }
2689}
2690
2691/*
2692 * Create sockets before preparing IO.
2693 * This is necessary for things that need to happen after reading
2694 * the network-input but need to be completed before IO event setup, e.g.
2695 * because they may create new channels.
2696 */
2697static void
2698channel_before_prepare_io(struct ssh *ssh)
2699{
2700 struct ssh_channels *sc = ssh->chanctxt;
2701 Channel *c;
2702 u_int i, oalloc;
2703
2704 for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2705 c = sc->channels[i];
2706 if (c == NULL)
2707 continue;
2708 if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2709 channel_before_prepare_io_rdynamic(ssh, c);
2710 }
2711}
2712
2713static void
2714dump_channel_poll(const char *func, const char *what, Channel *c,
2715 u_int pollfd_offset, struct pollfd *pfd)
2716{
2717#ifdef DEBUG_CHANNEL_POLL
2718 debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2719 "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2720 "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2721 c->rfd, c->wfd, c->efd, c->sock,
2722 c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2723 c->io_want, c->io_ready,
2724 pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2725#endif
2726}
2727
2728/* Prepare pollfd entries for a single channel */
2729static void
2730channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2731 struct pollfd *pfd, u_int npfd)
2732{
2733 u_int ev, p = *next_pollfd;
2734
2735 if (c == NULL)
2736 return;
2737 if (p + 4 > npfd) {
2738 /* Shouldn't happen */
2739 fatal_f("channel %d: bad pfd offset %u (max %u)",
2740 c->self, p, npfd);
2741 }
2742 c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2743 /*
2744 * prepare c->rfd
2745 *
2746 * This is a special case, since c->rfd might be the same as
2747 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2748 * IO too.
2749 */
2750 if (c->rfd != -1) {
2751 ev = 0;
2752 if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2753 ev |= POLLIN;
2754 /* rfd == wfd */
2755 if (c->wfd == c->rfd) {
2756 if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2757 ev |= POLLOUT;
2758 }
2759 /* rfd == efd */
2760 if (c->efd == c->rfd) {
2761 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2762 ev |= POLLIN;
2763 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2764 ev |= POLLOUT;
2765 }
2766 /* rfd == sock */
2767 if (c->sock == c->rfd) {
2768 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2769 ev |= POLLIN;
2770 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2771 ev |= POLLOUT;
2772 }
2773 /* Pack a pfd entry if any event armed for this fd */
2774 if (ev != 0) {
2775 c->pfds[0] = p;
2776 pfd[p].fd = c->rfd;
2777 pfd[p].events = ev;
2778 dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2779 p++;
2780 }
2781 }
2782 /* prepare c->wfd if wanting IO and not already handled above */
2783 if (c->wfd != -1 && c->rfd != c->wfd) {
2784 ev = 0;
2785 if ((c->io_want & SSH_CHAN_IO_WFD))
2786 ev |= POLLOUT;
2787 /* Pack a pfd entry if any event armed for this fd */
2788 if (ev != 0) {
2789 c->pfds[1] = p;
2790 pfd[p].fd = c->wfd;
2791 pfd[p].events = ev;
2792 dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2793 p++;
2794 }
2795 }
2796 /* prepare c->efd if wanting IO and not already handled above */
2797 if (c->efd != -1 && c->rfd != c->efd) {
2798 ev = 0;
2799 if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2800 ev |= POLLIN;
2801 if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2802 ev |= POLLOUT;
2803 /* Pack a pfd entry if any event armed for this fd */
2804 if (ev != 0) {
2805 c->pfds[2] = p;
2806 pfd[p].fd = c->efd;
2807 pfd[p].events = ev;
2808 dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2809 p++;
2810 }
2811 }
2812 /* prepare c->sock if wanting IO and not already handled above */
2813 if (c->sock != -1 && c->rfd != c->sock) {
2814 ev = 0;
2815 if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2816 ev |= POLLIN;
2817 if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2818 ev |= POLLOUT;
2819 /* Pack a pfd entry if any event armed for this fd */
2820 if (ev != 0) {
2821 c->pfds[3] = p;
2822 pfd[p].fd = c->sock;
2823 pfd[p].events = 0;
2824 dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2825 p++;
2826 }
2827 }
2828 *next_pollfd = p;
2829}
2830
2831/* * Allocate/prepare poll structure */
2832void
2833channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2834 u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
2835{
2836 struct ssh_channels *sc = ssh->chanctxt;
2837 u_int i, oalloc, p, npfd = npfd_reserved;
2838
2839 channel_before_prepare_io(ssh); /* might create a new channel */
2840 /* clear out I/O flags from last poll */
2841 for (i = 0; i < sc->channels_alloc; i++) {
2842 if (sc->channels[i] == NULL)
2843 continue;
2844 sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2845 }
2846 /* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2847 if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2848 fatal_f("too many channels"); /* shouldn't happen */
2849 npfd += sc->channels_alloc * 4;
2850 if (npfd > *npfd_allocp) {
2851 *pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2852 npfd, sizeof(**pfdp));
2853 *npfd_allocp = npfd;
2854 }
2855 *npfd_activep = npfd_reserved;
2856 oalloc = sc->channels_alloc;
2857
2858 channel_handler(ssh, CHAN_PRE, timeout);
2859
2860 if (oalloc != sc->channels_alloc) {
2861 /* shouldn't happen */
2862 fatal_f("channels_alloc changed during CHAN_PRE "
2863 "(was %u, now %u)", oalloc, sc->channels_alloc);
2864 }
2865
2866 /* Prepare pollfd */
2867 p = npfd_reserved;
2868 for (i = 0; i < sc->channels_alloc; i++)
2869 channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2870 *npfd_activep = p;
2871}
2872
2873static void
2874fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2875 const char *what, u_int revents_mask, u_int ready)
2876{
2877 struct pollfd *pfd = &pfds[p];
2878
2879 if (fd == -1)
2880 return;
2881 if (p == -1 || (u_int)p >= npfd)
2882 fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2883 dump_channel_poll(__func__, what, c, p, pfd);
2884 if (pfd->fd != fd) {
2885 fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2886 "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2887 c->rfd, c->wfd, c->efd, c->sock);
2888 }
2889 if ((pfd->revents & POLLNVAL) != 0) {
2890 fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2891 c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2892 }
2893 if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2894 c->io_ready |= ready & c->io_want;
2895}
2896
2897/*
2898 * After poll, perform any appropriate operations for channels which have
2899 * events pending.
2900 */
2901void
2902channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2903{
2904 struct ssh_channels *sc = ssh->chanctxt;
2905 u_int i;
2906 int p;
2907 Channel *c;
2908
2909#ifdef DEBUG_CHANNEL_POLL
2910 for (p = 0; p < (int)npfd; p++) {
2911 if (pfd[p].revents == 0)
2912 continue;
2913 debug_f("pfd[%u].fd %d rev 0x%04x",
2914 p, pfd[p].fd, pfd[p].revents);
2915 }
2916#endif
2917
2918 /* Convert pollfd into c->io_ready */
2919 for (i = 0; i < sc->channels_alloc; i++) {
2920 c = sc->channels[i];
2921 if (c == NULL)
2922 continue;
2923 /* if rfd is shared with efd/sock then wfd should be too */
2924 if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2925 (c->rfd == c->efd || c->rfd == c->sock)) {
2926 /* Shouldn't happen */
2927 fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2928 c->self, c->rfd, c->wfd, c->efd, c->sock);
2929 }
2930 c->io_ready = 0;
2931 /* rfd, potentially shared with wfd, efd and sock */
2932 if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2933 fd_ready(c, p, pfd, npfd, c->rfd,
2934 "rfd", POLLIN, SSH_CHAN_IO_RFD);
2935 if (c->rfd == c->wfd) {
2936 fd_ready(c, p, pfd, npfd, c->wfd,
2937 "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2938 }
2939 if (c->rfd == c->efd) {
2940 fd_ready(c, p, pfd, npfd, c->efd,
2941 "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2942 fd_ready(c, p, pfd, npfd, c->efd,
2943 "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2944 }
2945 if (c->rfd == c->sock) {
2946 fd_ready(c, p, pfd, npfd, c->sock,
2947 "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2948 fd_ready(c, p, pfd, npfd, c->sock,
2949 "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2950 }
2951 dump_channel_poll(__func__, "rfd", c, p, pfd);
2952 }
2953 /* wfd */
2954 if (c->wfd != -1 && c->wfd != c->rfd &&
2955 (p = c->pfds[1]) != -1) {
2956 fd_ready(c, p, pfd, npfd, c->wfd,
2957 "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2958 dump_channel_poll(__func__, "wfd", c, p, pfd);
2959 }
2960 /* efd */
2961 if (c->efd != -1 && c->efd != c->rfd &&
2962 (p = c->pfds[2]) != -1) {
2963 fd_ready(c, p, pfd, npfd, c->efd,
2964 "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2965 fd_ready(c, p, pfd, npfd, c->efd,
2966 "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2967 dump_channel_poll(__func__, "efd", c, p, pfd);
2968 }
2969 /* sock */
2970 if (c->sock != -1 && c->sock != c->rfd &&
2971 (p = c->pfds[3]) != -1) {
2972 fd_ready(c, p, pfd, npfd, c->sock,
2973 "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2974 fd_ready(c, p, pfd, npfd, c->sock,
2975 "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2976 dump_channel_poll(__func__, "sock", c, p, pfd);
2977 }
2978 }
2979 channel_handler(ssh, CHAN_POST, NULL);
2980}
2981
2982/*
2983 * Enqueue data for channels with open or draining c->input.
2984 * Returns non-zero if a packet was enqueued.
2985 */
2986static int
2987channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2988{
2989 size_t len, plen;
2990 const u_char *pkt;
2991 int r;
2992
2993 if ((len = sshbuf_len(c->input)) == 0) {
2994 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2995 /*
2996 * input-buffer is empty and read-socket shutdown:
2997 * tell peer, that we will not send more data:
2998 * send IEOF.
2999 * hack for extended data: delay EOF if EFD still
3000 * in use.
3001 */
3002 if (CHANNEL_EFD_INPUT_ACTIVE(c))
3003 debug2("channel %d: "
3004 "ibuf_empty delayed efd %d/(%zu)",
3005 c->self, c->efd, sshbuf_len(c->extended));
3006 else
3007 chan_ibuf_empty(ssh, c);
3008 }
3009 return 0;
3010 }
3011
3012 if (!c->have_remote_id)
3013 fatal_f("channel %d: no remote id", c->self);
3014
3015 if (c->datagram) {
3016 /* Check datagram will fit; drop if not */
3017 if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
3018 fatal_fr(r, "channel %i: get datagram", c->self);
3019 /*
3020 * XXX this does tail-drop on the datagram queue which is
3021 * usually suboptimal compared to head-drop. Better to have
3022 * backpressure at read time? (i.e. read + discard)
3023 */
3024 if (plen > c->remote_window || plen > c->remote_maxpacket) {
3025 debug("channel %d: datagram too big", c->self);
3026 return 0;
3027 }
3028 /* Enqueue it */
3029 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
3030 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
3031 (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
3032 (r = sshpkt_send(ssh)) != 0)
3033 fatal_fr(r, "channel %i: send datagram", c->self);
3034 c->remote_window -= plen;
3035 return 1;
3036 }
3037
3038 /* Enqueue packet for buffered data. */
3039 if (len > c->remote_window)
3040 len = c->remote_window;
3041 if (len > c->remote_maxpacket)
3042 len = c->remote_maxpacket;
3043 if (len == 0)
3044 return 0;
3045 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
3046 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
3047 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
3048 (r = sshpkt_send(ssh)) != 0)
3049 fatal_fr(r, "channel %i: send data", c->self);
3050 if ((r = sshbuf_consume(c->input, len)) != 0)
3051 fatal_fr(r, "channel %i: consume", c->self);
3052 c->remote_window -= len;
3053 return 1;
3054}
3055
3056/*
3057 * Enqueue data for channels with open c->extended in read mode.
3058 * Returns non-zero if a packet was enqueued.
3059 */
3060static int
3061channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
3062{
3063 size_t len;
3064 int r;
3065
3066 if ((len = sshbuf_len(c->extended)) == 0)
3067 return 0;
3068
3069 debug2("channel %d: rwin %u elen %zu euse %d", c->self,
3070 c->remote_window, sshbuf_len(c->extended), c->extended_usage);
3071 if (len > c->remote_window)
3072 len = c->remote_window;
3073 if (len > c->remote_maxpacket)
3074 len = c->remote_maxpacket;
3075 if (len == 0)
3076 return 0;
3077 if (!c->have_remote_id)
3078 fatal_f("channel %d: no remote id", c->self);
3079 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
3080 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
3081 (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
3082 (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
3083 (r = sshpkt_send(ssh)) != 0)
3084 fatal_fr(r, "channel %i: data", c->self);
3085 if ((r = sshbuf_consume(c->extended, len)) != 0)
3086 fatal_fr(r, "channel %i: consume", c->self);
3087 c->remote_window -= len;
3088 debug2("channel %d: sent ext data %zu", c->self, len);
3089 return 1;
3090}
3091
3092/*
3093 * If there is data to send to the connection, enqueue some of it now.
3094 * Returns non-zero if data was enqueued.
3095 */
3096int
3097channel_output_poll(struct ssh *ssh)
3098{
3099 struct ssh_channels *sc = ssh->chanctxt;
3100 Channel *c;
3101 u_int i;
3102 int ret = 0;
3103
3104 for (i = 0; i < sc->channels_alloc; i++) {
3105 c = sc->channels[i];
3106 if (c == NULL)
3107 continue;
3108
3109 /*
3110 * We are only interested in channels that can have buffered
3111 * incoming data.
3112 */
3113 if (c->type != SSH_CHANNEL_OPEN)
3114 continue;
3115 if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
3116 /* XXX is this true? */
3117 debug3("channel %d: will not send data after close",
3118 c->self);
3119 continue;
3120 }
3121
3122 /* Get the amount of buffered data for this channel. */
3123 if (c->istate == CHAN_INPUT_OPEN ||
3124 c->istate == CHAN_INPUT_WAIT_DRAIN)
3125 ret |= channel_output_poll_input_open(ssh, c);
3126 /* Send extended data, i.e. stderr */
3127 if (!(c->flags & CHAN_EOF_SENT) &&
3128 c->extended_usage == CHAN_EXTENDED_READ)
3129 ret |= channel_output_poll_extended_read(ssh, c);
3130 }
3131 return ret;
3132}
3133
3134/* -- mux proxy support */
3135
3136/*
3137 * When multiplexing channel messages for mux clients we have to deal
3138 * with downstream messages from the mux client and upstream messages
3139 * from the ssh server:
3140 * 1) Handling downstream messages is straightforward and happens
3141 * in channel_proxy_downstream():
3142 * - We forward all messages (mostly) unmodified to the server.
3143 * - However, in order to route messages from upstream to the correct
3144 * downstream client, we have to replace the channel IDs used by the
3145 * mux clients with a unique channel ID because the mux clients might
3146 * use conflicting channel IDs.
3147 * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
3148 * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
3149 * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
3150 * with the newly allocated channel ID.
3151 * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
3152 * channels and processed by channel_proxy_upstream(). The local channel ID
3153 * is then translated back to the original mux client ID.
3154 * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
3155 * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
3156 * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
3157 * downstream mux client are removed.
3158 * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
3159 * requires more work, because they are not addressed to a specific
3160 * channel. E.g. client_request_forwarded_tcpip() needs to figure
3161 * out whether the request is addressed to the local client or a
3162 * specific downstream client based on the listen-address/port.
3163 * 6) Agent and X11-Forwarding have a similar problem and are currently
3164 * not supported as the matching session/channel cannot be identified
3165 * easily.
3166 */
3167
3168/*
3169 * receive packets from downstream mux clients:
3170 * channel callback fired on read from mux client, creates
3171 * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
3172 * on channel creation.
3173 */
3174int
3175channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
3176{
3177 Channel *c = NULL;
3178 struct sshbuf *original = NULL, *modified = NULL;
3179 const u_char *cp;
3180 char *ctype = NULL, *listen_host = NULL;
3181 u_char type;
3182 size_t have;
3183 int ret = -1, r;
3184 u_int id, remote_id, listen_port;
3185
3186 /* sshbuf_dump(downstream->input, stderr); */
3187 if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
3188 != 0) {
3189 error_fr(r, "parse");
3190 return -1;
3191 }
3192 if (have < 2) {
3193 error_f("short message");
3194 return -1;
3195 }
3196 type = cp[1];
3197 /* skip padlen + type */
3198 cp += 2;
3199 have -= 2;
3200 if (ssh_packet_log_type(type))
3201 debug3_f("channel %u: down->up: type %u",
3202 downstream->self, type);
3203
3204 switch (type) {
3205 case SSH2_MSG_CHANNEL_OPEN:
3206 if ((original = sshbuf_from(cp, have)) == NULL ||
3207 (modified = sshbuf_new()) == NULL) {
3208 error_f("alloc");
3209 goto out;
3210 }
3211 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
3212 (r = sshbuf_get_u32(original, &id)) != 0) {
3213 error_fr(r, "parse");
3214 goto out;
3215 }
3216 c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3217 -1, -1, -1, 0, 0, 0, ctype, 1);
3218 c->mux_ctx = downstream; /* point to mux client */
3219 c->mux_downstream_id = id; /* original downstream id */
3220 if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
3221 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3222 (r = sshbuf_putb(modified, original)) != 0) {
3223 error_fr(r, "compose");
3224 channel_free(ssh, c);
3225 goto out;
3226 }
3227 break;
3228 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3229 /*
3230 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
3231 * need to parse 'remote_id' instead of 'ctype'.
3232 */
3233 if ((original = sshbuf_from(cp, have)) == NULL ||
3234 (modified = sshbuf_new()) == NULL) {
3235 error_f("alloc");
3236 goto out;
3237 }
3238 if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
3239 (r = sshbuf_get_u32(original, &id)) != 0) {
3240 error_fr(r, "parse");
3241 goto out;
3242 }
3243 c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3244 -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3245 c->mux_ctx = downstream; /* point to mux client */
3246 c->mux_downstream_id = id;
3247 c->remote_id = remote_id;
3248 c->have_remote_id = 1;
3249 if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3250 (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3251 (r = sshbuf_putb(modified, original)) != 0) {
3252 error_fr(r, "compose");
3253 channel_free(ssh, c);
3254 goto out;
3255 }
3256 break;
3257 case SSH2_MSG_GLOBAL_REQUEST:
3258 if ((original = sshbuf_from(cp, have)) == NULL) {
3259 error_f("alloc");
3260 goto out;
3261 }
3262 if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3263 error_fr(r, "parse");
3264 goto out;
3265 }
3266 if (strcmp(ctype, "tcpip-forward") != 0) {
3267 error_f("unsupported request %s", ctype);
3268 goto out;
3269 }
3270 if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3271 (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3272 (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3273 error_fr(r, "parse");
3274 goto out;
3275 }
3276 if (listen_port > 65535) {
3277 error_f("tcpip-forward for %s: bad port %u",
3278 listen_host, listen_port);
3279 goto out;
3280 }
3281 /* Record that connection to this host/port is permitted. */
3282 permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>",
3283 -1, listen_host, NULL, (int)listen_port, downstream);
3284 break;
3285 case SSH2_MSG_CHANNEL_CLOSE:
3286 if (have < 4)
3287 break;
3288 remote_id = PEEK_U32(cp);
3289 if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3290 if (c->flags & CHAN_CLOSE_RCVD)
3291 channel_free(ssh, c);
3292 else
3293 c->flags |= CHAN_CLOSE_SENT;
3294 }
3295 break;
3296 }
3297 if (modified) {
3298 if ((r = sshpkt_start(ssh, type)) != 0 ||
3299 (r = sshpkt_putb(ssh, modified)) != 0 ||
3300 (r = sshpkt_send(ssh)) != 0) {
3301 error_fr(r, "send");
3302 goto out;
3303 }
3304 } else {
3305 if ((r = sshpkt_start(ssh, type)) != 0 ||
3306 (r = sshpkt_put(ssh, cp, have)) != 0 ||
3307 (r = sshpkt_send(ssh)) != 0) {
3308 error_fr(r, "send");
3309 goto out;
3310 }
3311 }
3312 ret = 0;
3313 out:
3314 free(ctype);
3315 free(listen_host);
3316 sshbuf_free(original);
3317 sshbuf_free(modified);
3318 return ret;
3319}
3320
3321/*
3322 * receive packets from upstream server and de-multiplex packets
3323 * to correct downstream:
3324 * implemented as a helper for channel input handlers,
3325 * replaces local (proxy) channel ID with downstream channel ID.
3326 */
3327int
3328channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3329{
3330 struct sshbuf *b = NULL;
3331 Channel *downstream;
3332 const u_char *cp = NULL;
3333 size_t len;
3334 int r;
3335
3336 /*
3337 * When receiving packets from the peer we need to check whether we
3338 * need to forward the packets to the mux client. In this case we
3339 * restore the original channel id and keep track of CLOSE messages,
3340 * so we can cleanup the channel.
3341 */
3342 if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3343 return 0;
3344 if ((downstream = c->mux_ctx) == NULL)
3345 return 0;
3346 switch (type) {
3347 case SSH2_MSG_CHANNEL_CLOSE:
3348 case SSH2_MSG_CHANNEL_DATA:
3349 case SSH2_MSG_CHANNEL_EOF:
3350 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3351 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3352 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3353 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3354 case SSH2_MSG_CHANNEL_SUCCESS:
3355 case SSH2_MSG_CHANNEL_FAILURE:
3356 case SSH2_MSG_CHANNEL_REQUEST:
3357 break;
3358 default:
3359 debug2_f("channel %u: unsupported type %u", c->self, type);
3360 return 0;
3361 }
3362 if ((b = sshbuf_new()) == NULL) {
3363 error_f("alloc reply");
3364 goto out;
3365 }
3366 /* get remaining payload (after id) */
3367 cp = sshpkt_ptr(ssh, &len);
3368 if (cp == NULL) {
3369 error_f("no packet");
3370 goto out;
3371 }
3372 /* translate id and send to muxclient */
3373 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
3374 (r = sshbuf_put_u8(b, type)) != 0 ||
3375 (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3376 (r = sshbuf_put(b, cp, len)) != 0 ||
3377 (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3378 error_fr(r, "compose muxclient");
3379 goto out;
3380 }
3381 /* sshbuf_dump(b, stderr); */
3382 if (ssh_packet_log_type(type))
3383 debug3_f("channel %u: up->down: type %u", c->self, type);
3384 out:
3385 /* update state */
3386 switch (type) {
3387 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3388 /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3389 if (cp && len > 4) {
3390 c->remote_id = PEEK_U32(cp);
3391 c->have_remote_id = 1;
3392 }
3393 break;
3394 case SSH2_MSG_CHANNEL_CLOSE:
3395 if (c->flags & CHAN_CLOSE_SENT)
3396 channel_free(ssh, c);
3397 else
3398 c->flags |= CHAN_CLOSE_RCVD;
3399 break;
3400 }
3401 sshbuf_free(b);
3402 return 1;
3403}
3404
3405/* -- protocol input */
3406
3407/* Parse a channel ID from the current packet */
3408static int
3409channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3410{
3411 u_int32_t id;
3412 int r;
3413
3414 if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3415 error_r(r, "%s: parse id", where);
3416 ssh_packet_disconnect(ssh, "Invalid %s message", what);
3417 }
3418 if (id > INT_MAX) {
3419 error_r(r, "%s: bad channel id %u", where, id);
3420 ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3421 }
3422 return (int)id;
3423}
3424
3425/* Lookup a channel from an ID in the current packet */
3426static Channel *
3427channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3428{
3429 int id = channel_parse_id(ssh, where, what);
3430 Channel *c;
3431
3432 if ((c = channel_lookup(ssh, id)) == NULL) {
3433 ssh_packet_disconnect(ssh,
3434 "%s packet referred to nonexistent channel %d", what, id);
3435 }
3436 return c;
3437}
3438
3439int
3440channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3441{
3442 const u_char *data;
3443 size_t data_len, win_len;
3444 Channel *c = channel_from_packet_id(ssh, __func__, "data");
3445 int r;
3446
3447 if (channel_proxy_upstream(c, type, seq, ssh))
3448 return 0;
3449
3450 /* Ignore any data for non-open channels (might happen on close) */
3451 if (c->type != SSH_CHANNEL_OPEN &&
3452 c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3453 c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3454 c->type != SSH_CHANNEL_X11_OPEN)
3455 return 0;
3456
3457 /* Get the data. */
3458 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3459 (r = sshpkt_get_end(ssh)) != 0)
3460 fatal_fr(r, "channel %i: get data", c->self);
3461
3462 win_len = data_len;
3463 if (c->datagram)
3464 win_len += 4; /* string length header */
3465
3466 /*
3467 * The sending side reduces its window as it sends data, so we
3468 * must 'fake' consumption of the data in order to ensure that window
3469 * updates are sent back. Otherwise the connection might deadlock.
3470 */
3471 if (c->ostate != CHAN_OUTPUT_OPEN) {
3472 c->local_window -= win_len;
3473 c->local_consumed += win_len;
3474 return 0;
3475 }
3476
3477 if (win_len > c->local_maxpacket) {
3478 logit("channel %d: rcvd big packet %zu, maxpack %u",
3479 c->self, win_len, c->local_maxpacket);
3480 return 0;
3481 }
3482 if (win_len > c->local_window) {
3483 c->local_window_exceeded += win_len - c->local_window;
3484 logit("channel %d: rcvd too much data %zu, win %u/%u "
3485 "(excess %u)", c->self, win_len, c->local_window,
3486 c->local_window_max, c->local_window_exceeded);
3487 c->local_window = 0;
3488 /* Allow 10% grace before bringing the hammer down */
3489 if (c->local_window_exceeded > (c->local_window_max / 10)) {
3490 ssh_packet_disconnect(ssh, "channel %d: peer ignored "
3491 "channel window", c->self);
3492 }
3493 } else {
3494 c->local_window -= win_len;
3495 c->local_window_exceeded = 0;
3496 }
3497
3498 if (c->datagram) {
3499 if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3500 fatal_fr(r, "channel %i: append datagram", c->self);
3501 } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3502 fatal_fr(r, "channel %i: append data", c->self);
3503
3504 return 0;
3505}
3506
3507int
3508channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3509{
3510 const u_char *data;
3511 size_t data_len;
3512 u_int32_t tcode;
3513 Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3514 int r;
3515
3516 if (channel_proxy_upstream(c, type, seq, ssh))
3517 return 0;
3518 if (c->type != SSH_CHANNEL_OPEN) {
3519 logit("channel %d: ext data for non open", c->self);
3520 return 0;
3521 }
3522 if (c->flags & CHAN_EOF_RCVD) {
3523 if (ssh->compat & SSH_BUG_EXTEOF)
3524 debug("channel %d: accepting ext data after eof",
3525 c->self);
3526 else
3527 ssh_packet_disconnect(ssh, "Received extended_data "
3528 "after EOF on channel %d.", c->self);
3529 }
3530
3531 if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3532 error_fr(r, "parse tcode");
3533 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3534 }
3535 if (c->efd == -1 ||
3536 c->extended_usage != CHAN_EXTENDED_WRITE ||
3537 tcode != SSH2_EXTENDED_DATA_STDERR) {
3538 logit("channel %d: bad ext data", c->self);
3539 return 0;
3540 }
3541 if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3542 (r = sshpkt_get_end(ssh)) != 0) {
3543 error_fr(r, "parse data");
3544 ssh_packet_disconnect(ssh, "Invalid extended_data message");
3545 }
3546
3547 if (data_len > c->local_window) {
3548 logit("channel %d: rcvd too much extended_data %zu, win %u",
3549 c->self, data_len, c->local_window);
3550 return 0;
3551 }
3552 debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3553 /* XXX sshpkt_getb? */
3554 if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3555 error_fr(r, "append");
3556 c->local_window -= data_len;
3557 return 0;
3558}
3559
3560int
3561channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3562{
3563 Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3564 int r;
3565
3566 if ((r = sshpkt_get_end(ssh)) != 0) {
3567 error_fr(r, "parse data");
3568 ssh_packet_disconnect(ssh, "Invalid ieof message");
3569 }
3570
3571 if (channel_proxy_upstream(c, type, seq, ssh))
3572 return 0;
3573 chan_rcvd_ieof(ssh, c);
3574
3575 /* XXX force input close */
3576 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3577 debug("channel %d: FORCE input drain", c->self);
3578 c->istate = CHAN_INPUT_WAIT_DRAIN;
3579 if (sshbuf_len(c->input) == 0)
3580 chan_ibuf_empty(ssh, c);
3581 }
3582 return 0;
3583}
3584
3585int
3586channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3587{
3588 Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3589 int r;
3590
3591 if (channel_proxy_upstream(c, type, seq, ssh))
3592 return 0;
3593 if ((r = sshpkt_get_end(ssh)) != 0) {
3594 error_fr(r, "parse data");
3595 ssh_packet_disconnect(ssh, "Invalid oclose message");
3596 }
3597 chan_rcvd_oclose(ssh, c);
3598 return 0;
3599}
3600
3601int
3602channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3603{
3604 Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3605 u_int32_t remote_window, remote_maxpacket;
3606 int r;
3607
3608 if (channel_proxy_upstream(c, type, seq, ssh))
3609 return 0;
3610 if (c->type != SSH_CHANNEL_OPENING)
3611 ssh_packet_disconnect(ssh, "Received open confirmation for "
3612 "non-opening channel %d.", c->self);
3613 /*
3614 * Record the remote channel number and mark that the channel
3615 * is now open.
3616 */
3617 if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3618 (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3619 (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3620 (r = sshpkt_get_end(ssh)) != 0) {
3621 error_fr(r, "window/maxpacket");
3622 ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3623 }
3624
3625 c->have_remote_id = 1;
3626 c->remote_window = remote_window;
3627 c->remote_maxpacket = remote_maxpacket;
3628 c->type = SSH_CHANNEL_OPEN;
3629 if (c->open_confirm) {
3630 debug2_f("channel %d: callback start", c->self);
3631 c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3632 debug2_f("channel %d: callback done", c->self);
3633 }
3634 channel_set_used_time(ssh, c);
3635 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3636 c->remote_window, c->remote_maxpacket);
3637 return 0;
3638}
3639
3640static char *
3641reason2txt(int reason)
3642{
3643 switch (reason) {
3644 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3645 return "administratively prohibited";
3646 case SSH2_OPEN_CONNECT_FAILED:
3647 return "connect failed";
3648 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3649 return "unknown channel type";
3650 case SSH2_OPEN_RESOURCE_SHORTAGE:
3651 return "resource shortage";
3652 }
3653 return "unknown reason";
3654}
3655
3656int
3657channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3658{
3659 Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3660 u_int32_t reason;
3661 char *msg = NULL;
3662 int r;
3663
3664 if (channel_proxy_upstream(c, type, seq, ssh))
3665 return 0;
3666 if (c->type != SSH_CHANNEL_OPENING)
3667 ssh_packet_disconnect(ssh, "Received open failure for "
3668 "non-opening channel %d.", c->self);
3669 if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3670 error_fr(r, "parse reason");
3671 ssh_packet_disconnect(ssh, "Invalid open failure message");
3672 }
3673 /* skip language */
3674 if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3675 (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3676 (r = sshpkt_get_end(ssh)) != 0) {
3677 error_fr(r, "parse msg/lang");
3678 ssh_packet_disconnect(ssh, "Invalid open failure message");
3679 }
3680 logit("channel %d: open failed: %s%s%s", c->self,
3681 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3682 free(msg);
3683 if (c->open_confirm) {
3684 debug2_f("channel %d: callback start", c->self);
3685 c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3686 debug2_f("channel %d: callback done", c->self);
3687 }
3688 /* Schedule the channel for cleanup/deletion. */
3689 chan_mark_dead(ssh, c);
3690 return 0;
3691}
3692
3693int
3694channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3695{
3696 int id = channel_parse_id(ssh, __func__, "window adjust");
3697 Channel *c;
3698 u_int32_t adjust;
3699 u_int new_rwin;
3700 int r;
3701
3702 if ((c = channel_lookup(ssh, id)) == NULL) {
3703 logit("Received window adjust for non-open channel %d.", id);
3704 return 0;
3705 }
3706
3707 if (channel_proxy_upstream(c, type, seq, ssh))
3708 return 0;
3709 if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3710 (r = sshpkt_get_end(ssh)) != 0) {
3711 error_fr(r, "parse adjust");
3712 ssh_packet_disconnect(ssh, "Invalid window adjust message");
3713 }
3714 debug2("channel %d: rcvd adjust %u", c->self, adjust);
3715 if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3716 fatal("channel %d: adjust %u overflows remote window %u",
3717 c->self, adjust, c->remote_window);
3718 }
3719 c->remote_window = new_rwin;
3720 return 0;
3721}
3722
3723int
3724channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3725{
3726 int id = channel_parse_id(ssh, __func__, "status confirm");
3727 Channel *c;
3728 struct channel_confirm *cc;
3729
3730 /* Reset keepalive timeout */
3731 ssh_packet_set_alive_timeouts(ssh, 0);
3732
3733 debug2_f("type %d id %d", type, id);
3734
3735 if ((c = channel_lookup(ssh, id)) == NULL) {
3736 logit_f("%d: unknown", id);
3737 return 0;
3738 }
3739 if (channel_proxy_upstream(c, type, seq, ssh))
3740 return 0;
3741 if (sshpkt_get_end(ssh) != 0)
3742 ssh_packet_disconnect(ssh, "Invalid status confirm message");
3743 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3744 return 0;
3745 cc->cb(ssh, type, c, cc->ctx);
3746 TAILQ_REMOVE(&c->status_confirms, cc, entry);
3747 freezero(cc, sizeof(*cc));
3748 return 0;
3749}
3750
3751/* -- tcp forwarding */
3752
3753void
3754channel_set_af(struct ssh *ssh, int af)
3755{
3756 ssh->chanctxt->IPv4or6 = af;
3757}
3758
3759
3760/*
3761 * Determine whether or not a port forward listens to loopback, the
3762 * specified address or wildcard. On the client, a specified bind
3763 * address will always override gateway_ports. On the server, a
3764 * gateway_ports of 1 (``yes'') will override the client's specification
3765 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3766 * will bind to whatever address the client asked for.
3767 *
3768 * Special-case listen_addrs are:
3769 *
3770 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3771 * "" (empty string), "*" -> wildcard v4/v6
3772 * "localhost" -> loopback v4/v6
3773 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
3774 */
3775static const char *
3776channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3777 int is_client, struct ForwardOptions *fwd_opts)
3778{
3779 const char *addr = NULL;
3780 int wildcard = 0;
3781
3782 if (listen_addr == NULL) {
3783 /* No address specified: default to gateway_ports setting */
3784 if (fwd_opts->gateway_ports)
3785 wildcard = 1;
3786 } else if (fwd_opts->gateway_ports || is_client) {
3787 if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3788 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3789 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3790 (!is_client && fwd_opts->gateway_ports == 1)) {
3791 wildcard = 1;
3792 /*
3793 * Notify client if they requested a specific listen
3794 * address and it was overridden.
3795 */
3796 if (*listen_addr != '\0' &&
3797 strcmp(listen_addr, "0.0.0.0") != 0 &&
3798 strcmp(listen_addr, "*") != 0) {
3799 ssh_packet_send_debug(ssh,
3800 "Forwarding listen address "
3801 "\"%s\" overridden by server "
3802 "GatewayPorts", listen_addr);
3803 }
3804 } else if (strcmp(listen_addr, "localhost") != 0 ||
3805 strcmp(listen_addr, "127.0.0.1") == 0 ||
3806 strcmp(listen_addr, "::1") == 0) {
3807 /*
3808 * Accept explicit localhost address when
3809 * GatewayPorts=yes. The "localhost" hostname is
3810 * deliberately skipped here so it will listen on all
3811 * available local address families.
3812 */
3813 addr = listen_addr;
3814 }
3815 } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3816 strcmp(listen_addr, "::1") == 0) {
3817 /*
3818 * If a specific IPv4/IPv6 localhost address has been
3819 * requested then accept it even if gateway_ports is in
3820 * effect. This allows the client to prefer IPv4 or IPv6.
3821 */
3822 addr = listen_addr;
3823 }
3824 if (wildcardp != NULL)
3825 *wildcardp = wildcard;
3826 return addr;
3827}
3828
3829static int
3830channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3831 struct Forward *fwd, int *allocated_listen_port,
3832 struct ForwardOptions *fwd_opts)
3833{
3834 Channel *c;
3835 int sock, r, success = 0, wildcard = 0, is_client;
3836 struct addrinfo hints, *ai, *aitop;
3837 const char *host, *addr;
3838 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3839 in_port_t *lport_p;
3840
3841 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3842
3843 if (is_client && fwd->connect_path != NULL) {
3844 host = fwd->connect_path;
3845 } else {
3846 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3847 fwd->listen_host : fwd->connect_host;
3848 if (host == NULL) {
3849 error("No forward host name.");
3850 return 0;
3851 }
3852 if (strlen(host) >= NI_MAXHOST) {
3853 error("Forward host name too long.");
3854 return 0;
3855 }
3856 }
3857
3858 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3859 addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3860 is_client, fwd_opts);
3861 debug3_f("type %d wildcard %d addr %s", type, wildcard,
3862 (addr == NULL) ? "NULL" : addr);
3863
3864 /*
3865 * getaddrinfo returns a loopback address if the hostname is
3866 * set to NULL and hints.ai_flags is not AI_PASSIVE
3867 */
3868 memset(&hints, 0, sizeof(hints));
3869 hints.ai_family = ssh->chanctxt->IPv4or6;
3870 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3871 hints.ai_socktype = SOCK_STREAM;
3872 snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3873 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3874 if (addr == NULL) {
3875 /* This really shouldn't happen */
3876 ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3877 ssh_gai_strerror(r));
3878 } else {
3879 error_f("getaddrinfo(%.64s): %s", addr,
3880 ssh_gai_strerror(r));
3881 }
3882 return 0;
3883 }
3884 if (allocated_listen_port != NULL)
3885 *allocated_listen_port = 0;
3886 for (ai = aitop; ai; ai = ai->ai_next) {
3887 switch (ai->ai_family) {
3888 case AF_INET:
3889 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3890 sin_port;
3891 break;
3892 case AF_INET6:
3893 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3894 sin6_port;
3895 break;
3896 default:
3897 continue;
3898 }
3899 /*
3900 * If allocating a port for -R forwards, then use the
3901 * same port for all address families.
3902 */
3903 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3904 fwd->listen_port == 0 && allocated_listen_port != NULL &&
3905 *allocated_listen_port > 0)
3906 *lport_p = htons(*allocated_listen_port);
3907
3908 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3909 strport, sizeof(strport),
3910 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3911 error_f("getnameinfo failed");
3912 continue;
3913 }
3914 /* Create a port to listen for the host. */
3915 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3916 if (sock == -1) {
3917 /* this is no error since kernel may not support ipv6 */
3918 verbose("socket [%s]:%s: %.100s", ntop, strport,
3919 strerror(errno));
3920 continue;
3921 }
3922
3923 set_reuseaddr(sock);
3924
3925 debug("Local forwarding listening on %s port %s.",
3926 ntop, strport);
3927
3928 /* Bind the socket to the address. */
3929 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3930 /*
3931 * address can be in if use ipv6 address is
3932 * already bound
3933 */
3934 verbose("bind [%s]:%s: %.100s",
3935 ntop, strport, strerror(errno));
3936 close(sock);
3937 continue;
3938 }
3939 /* Start listening for connections on the socket. */
3940 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3941 error("listen [%s]:%s: %.100s", ntop, strport,
3942 strerror(errno));
3943 close(sock);
3944 continue;
3945 }
3946
3947 /*
3948 * fwd->listen_port == 0 requests a dynamically allocated port -
3949 * record what we got.
3950 */
3951 if (type == SSH_CHANNEL_RPORT_LISTENER &&
3952 fwd->listen_port == 0 &&
3953 allocated_listen_port != NULL &&
3954 *allocated_listen_port == 0) {
3955 *allocated_listen_port = get_local_port(sock);
3956 debug("Allocated listen port %d",
3957 *allocated_listen_port);
3958 }
3959
3960 /* Allocate a channel number for the socket. */
3961 c = channel_new(ssh, "port-listener", type, sock, sock, -1,
3962 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3963 0, "port listener", 1);
3964 c->path = xstrdup(host);
3965 c->host_port = fwd->connect_port;
3966 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3967 if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3968 !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3969 c->listening_port = *allocated_listen_port;
3970 else
3971 c->listening_port = fwd->listen_port;
3972 success = 1;
3973 }
3974 if (success == 0)
3975 error_f("cannot listen to port: %d", fwd->listen_port);
3976 freeaddrinfo(aitop);
3977 return success;
3978}
3979
3980static int
3981channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3982 struct Forward *fwd, struct ForwardOptions *fwd_opts)
3983{
3984 struct sockaddr_un sunaddr;
3985 const char *path;
3986 Channel *c;
3987 int port, sock;
3988 mode_t omask;
3989
3990 switch (type) {
3991 case SSH_CHANNEL_UNIX_LISTENER:
3992 if (fwd->connect_path != NULL) {
3993 if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3994 error("Local connecting path too long: %s",
3995 fwd->connect_path);
3996 return 0;
3997 }
3998 path = fwd->connect_path;
3999 port = PORT_STREAMLOCAL;
4000 } else {
4001 if (fwd->connect_host == NULL) {
4002 error("No forward host name.");
4003 return 0;
4004 }
4005 if (strlen(fwd->connect_host) >= NI_MAXHOST) {
4006 error("Forward host name too long.");
4007 return 0;
4008 }
4009 path = fwd->connect_host;
4010 port = fwd->connect_port;
4011 }
4012 break;
4013 case SSH_CHANNEL_RUNIX_LISTENER:
4014 path = fwd->listen_path;
4015 port = PORT_STREAMLOCAL;
4016 break;
4017 default:
4018 error_f("unexpected channel type %d", type);
4019 return 0;
4020 }
4021
4022 if (fwd->listen_path == NULL) {
4023 error("No forward path name.");
4024 return 0;
4025 }
4026 if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
4027 error("Local listening path too long: %s", fwd->listen_path);
4028 return 0;
4029 }
4030
4031 debug3_f("type %d path %s", type, fwd->listen_path);
4032
4033 /* Start a Unix domain listener. */
4034 omask = umask(fwd_opts->streamlocal_bind_mask);
4035 sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
4036 fwd_opts->streamlocal_bind_unlink);
4037 umask(omask);
4038 if (sock < 0)
4039 return 0;
4040
4041 debug("Local forwarding listening on path %s.", fwd->listen_path);
4042
4043 /* Allocate a channel number for the socket. */
4044 c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
4045 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
4046 0, "unix listener", 1);
4047 c->path = xstrdup(path);
4048 c->host_port = port;
4049 c->listening_port = PORT_STREAMLOCAL;
4050 c->listening_addr = xstrdup(fwd->listen_path);
4051 return 1;
4052}
4053
4054static int
4055channel_cancel_rport_listener_tcpip(struct ssh *ssh,
4056 const char *host, u_short port)
4057{
4058 u_int i;
4059 int found = 0;
4060
4061 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4062 Channel *c = ssh->chanctxt->channels[i];
4063 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
4064 continue;
4065 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
4066 debug2_f("close channel %d", i);
4067 channel_free(ssh, c);
4068 found = 1;
4069 }
4070 }
4071
4072 return found;
4073}
4074
4075static int
4076channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
4077{
4078 u_int i;
4079 int found = 0;
4080
4081 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4082 Channel *c = ssh->chanctxt->channels[i];
4083 if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
4084 continue;
4085 if (c->path == NULL)
4086 continue;
4087 if (strcmp(c->path, path) == 0) {
4088 debug2_f("close channel %d", i);
4089 channel_free(ssh, c);
4090 found = 1;
4091 }
4092 }
4093
4094 return found;
4095}
4096
4097int
4098channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
4099{
4100 if (fwd->listen_path != NULL) {
4101 return channel_cancel_rport_listener_streamlocal(ssh,
4102 fwd->listen_path);
4103 } else {
4104 return channel_cancel_rport_listener_tcpip(ssh,
4105 fwd->listen_host, fwd->listen_port);
4106 }
4107}
4108
4109static int
4110channel_cancel_lport_listener_tcpip(struct ssh *ssh,
4111 const char *lhost, u_short lport, int cport,
4112 struct ForwardOptions *fwd_opts)
4113{
4114 u_int i;
4115 int found = 0;
4116 const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
4117
4118 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4119 Channel *c = ssh->chanctxt->channels[i];
4120 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
4121 continue;
4122 if (c->listening_port != lport)
4123 continue;
4124 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
4125 /* skip dynamic forwardings */
4126 if (c->host_port == 0)
4127 continue;
4128 } else {
4129 if (c->host_port != cport)
4130 continue;
4131 }
4132 if ((c->listening_addr == NULL && addr != NULL) ||
4133 (c->listening_addr != NULL && addr == NULL))
4134 continue;
4135 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
4136 debug2_f("close channel %d", i);
4137 channel_free(ssh, c);
4138 found = 1;
4139 }
4140 }
4141
4142 return found;
4143}
4144
4145static int
4146channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
4147{
4148 u_int i;
4149 int found = 0;
4150
4151 if (path == NULL) {
4152 error_f("no path specified.");
4153 return 0;
4154 }
4155
4156 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4157 Channel *c = ssh->chanctxt->channels[i];
4158 if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
4159 continue;
4160 if (c->listening_addr == NULL)
4161 continue;
4162 if (strcmp(c->listening_addr, path) == 0) {
4163 debug2_f("close channel %d", i);
4164 channel_free(ssh, c);
4165 found = 1;
4166 }
4167 }
4168
4169 return found;
4170}
4171
4172int
4173channel_cancel_lport_listener(struct ssh *ssh,
4174 struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
4175{
4176 if (fwd->listen_path != NULL) {
4177 return channel_cancel_lport_listener_streamlocal(ssh,
4178 fwd->listen_path);
4179 } else {
4180 return channel_cancel_lport_listener_tcpip(ssh,
4181 fwd->listen_host, fwd->listen_port, cport, fwd_opts);
4182 }
4183}
4184
4185/* protocol local port fwd, used by ssh */
4186int
4187channel_setup_local_fwd_listener(struct ssh *ssh,
4188 struct Forward *fwd, struct ForwardOptions *fwd_opts)
4189{
4190 if (fwd->listen_path != NULL) {
4191 return channel_setup_fwd_listener_streamlocal(ssh,
4192 SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
4193 } else {
4194 return channel_setup_fwd_listener_tcpip(ssh,
4195 SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
4196 }
4197}
4198
4199/* Matches a remote forwarding permission against a requested forwarding */
4200static int
4201remote_open_match(struct permission *allowed_open, struct Forward *fwd)
4202{
4203 int ret;
4204 char *lhost;
4205
4206 /* XXX add ACLs for streamlocal */
4207 if (fwd->listen_path != NULL)
4208 return 1;
4209
4210 if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
4211 return 0;
4212
4213 if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
4214 allowed_open->listen_port != fwd->listen_port)
4215 return 0;
4216
4217 /* Match hostnames case-insensitively */
4218 lhost = xstrdup(fwd->listen_host);
4219 lowercase(lhost);
4220 ret = match_pattern(lhost, allowed_open->listen_host);
4221 free(lhost);
4222
4223 return ret;
4224}
4225
4226/* Checks whether a requested remote forwarding is permitted */
4227static int
4228check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
4229{
4230 struct ssh_channels *sc = ssh->chanctxt;
4231 struct permission_set *pset = &sc->remote_perms;
4232 u_int i, permit, permit_adm = 1;
4233 struct permission *perm;
4234
4235 /* XXX apply GatewayPorts override before checking? */
4236
4237 permit = pset->all_permitted;
4238 if (!permit) {
4239 for (i = 0; i < pset->num_permitted_user; i++) {
4240 perm = &pset->permitted_user[i];
4241 if (remote_open_match(perm, fwd)) {
4242 permit = 1;
4243 break;
4244 }
4245 }
4246 }
4247
4248 if (pset->num_permitted_admin > 0) {
4249 permit_adm = 0;
4250 for (i = 0; i < pset->num_permitted_admin; i++) {
4251 perm = &pset->permitted_admin[i];
4252 if (remote_open_match(perm, fwd)) {
4253 permit_adm = 1;
4254 break;
4255 }
4256 }
4257 }
4258
4259 return permit && permit_adm;
4260}
4261
4262/* protocol v2 remote port fwd, used by sshd */
4263int
4264channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4265 int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4266{
4267 if (!check_rfwd_permission(ssh, fwd)) {
4268 ssh_packet_send_debug(ssh, "port forwarding refused");
4269 if (fwd->listen_path != NULL)
4270 /* XXX always allowed, see remote_open_match() */
4271 logit("Received request from %.100s port %d to "
4272 "remote forward to path \"%.100s\", "
4273 "but the request was denied.",
4274 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4275 fwd->listen_path);
4276 else if(fwd->listen_host != NULL)
4277 logit("Received request from %.100s port %d to "
4278 "remote forward to host %.100s port %d, "
4279 "but the request was denied.",
4280 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4281 fwd->listen_host, fwd->listen_port );
4282 else
4283 logit("Received request from %.100s port %d to remote "
4284 "forward, but the request was denied.",
4285 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4286 return 0;
4287 }
4288 if (fwd->listen_path != NULL) {
4289 return channel_setup_fwd_listener_streamlocal(ssh,
4290 SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4291 } else {
4292 return channel_setup_fwd_listener_tcpip(ssh,
4293 SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4294 fwd_opts);
4295 }
4296}
4297
4298/*
4299 * Translate the requested rfwd listen host to something usable for
4300 * this server.
4301 */
4302static const char *
4303channel_rfwd_bind_host(const char *listen_host)
4304{
4305 if (listen_host == NULL) {
4306 return "localhost";
4307 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4308 return "";
4309 } else
4310 return listen_host;
4311}
4312
4313/*
4314 * Initiate forwarding of connections to port "port" on remote host through
4315 * the secure channel to host:port from local side.
4316 * Returns handle (index) for updating the dynamic listen port with
4317 * channel_update_permission().
4318 */
4319int
4320channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4321{
4322 int r, success = 0, idx = -1;
4323 const char *host_to_connect, *listen_host, *listen_path;
4324 int port_to_connect, listen_port;
4325
4326 /* Send the forward request to the remote side. */
4327 if (fwd->listen_path != NULL) {
4328 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4329 (r = sshpkt_put_cstring(ssh,
4330 "streamlocal-forward@openssh.com")) != 0 ||
4331 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4332 (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4333 (r = sshpkt_send(ssh)) != 0 ||
4334 (r = ssh_packet_write_wait(ssh)) != 0)
4335 fatal_fr(r, "request streamlocal");
4336 } else {
4337 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4338 (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4339 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4340 (r = sshpkt_put_cstring(ssh,
4341 channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4342 (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4343 (r = sshpkt_send(ssh)) != 0 ||
4344 (r = ssh_packet_write_wait(ssh)) != 0)
4345 fatal_fr(r, "request tcpip-forward");
4346 }
4347 /* Assume that server accepts the request */
4348 success = 1;
4349 if (success) {
4350 /* Record that connection to this host/port is permitted. */
4351 host_to_connect = listen_host = listen_path = NULL;
4352 port_to_connect = listen_port = 0;
4353 if (fwd->connect_path != NULL) {
4354 host_to_connect = fwd->connect_path;
4355 port_to_connect = PORT_STREAMLOCAL;
4356 } else {
4357 host_to_connect = fwd->connect_host;
4358 port_to_connect = fwd->connect_port;
4359 }
4360 if (fwd->listen_path != NULL) {
4361 listen_path = fwd->listen_path;
4362 listen_port = PORT_STREAMLOCAL;
4363 } else {
4364 listen_host = fwd->listen_host;
4365 listen_port = fwd->listen_port;
4366 }
4367 idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4368 host_to_connect, port_to_connect,
4369 listen_host, listen_path, listen_port, NULL);
4370 }
4371 return idx;
4372}
4373
4374static int
4375open_match(struct permission *allowed_open, const char *requestedhost,
4376 int requestedport)
4377{
4378 if (allowed_open->host_to_connect == NULL)
4379 return 0;
4380 if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4381 allowed_open->port_to_connect != requestedport)
4382 return 0;
4383 if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4384 strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4385 return 0;
4386 return 1;
4387}
4388
4389/*
4390 * Note that in the listen host/port case
4391 * we don't support FWD_PERMIT_ANY_PORT and
4392 * need to translate between the configured-host (listen_host)
4393 * and what we've sent to the remote server (channel_rfwd_bind_host)
4394 */
4395static int
4396open_listen_match_tcpip(struct permission *allowed_open,
4397 const char *requestedhost, u_short requestedport, int translate)
4398{
4399 const char *allowed_host;
4400
4401 if (allowed_open->host_to_connect == NULL)
4402 return 0;
4403 if (allowed_open->listen_port != requestedport)
4404 return 0;
4405 if (!translate && allowed_open->listen_host == NULL &&
4406 requestedhost == NULL)
4407 return 1;
4408 allowed_host = translate ?
4409 channel_rfwd_bind_host(allowed_open->listen_host) :
4410 allowed_open->listen_host;
4411 if (allowed_host == NULL || requestedhost == NULL ||
4412 strcmp(allowed_host, requestedhost) != 0)
4413 return 0;
4414 return 1;
4415}
4416
4417static int
4418open_listen_match_streamlocal(struct permission *allowed_open,
4419 const char *requestedpath)
4420{
4421 if (allowed_open->host_to_connect == NULL)
4422 return 0;
4423 if (allowed_open->listen_port != PORT_STREAMLOCAL)
4424 return 0;
4425 if (allowed_open->listen_path == NULL ||
4426 strcmp(allowed_open->listen_path, requestedpath) != 0)
4427 return 0;
4428 return 1;
4429}
4430
4431/*
4432 * Request cancellation of remote forwarding of connection host:port from
4433 * local side.
4434 */
4435static int
4436channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4437 const char *host, u_short port)
4438{
4439 struct ssh_channels *sc = ssh->chanctxt;
4440 struct permission_set *pset = &sc->local_perms;
4441 int r;
4442 u_int i;
4443 struct permission *perm = NULL;
4444
4445 for (i = 0; i < pset->num_permitted_user; i++) {
4446 perm = &pset->permitted_user[i];
4447 if (open_listen_match_tcpip(perm, host, port, 0))
4448 break;
4449 perm = NULL;
4450 }
4451 if (perm == NULL) {
4452 debug_f("requested forward not found");
4453 return -1;
4454 }
4455 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4456 (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4457 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4458 (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4459 (r = sshpkt_put_u32(ssh, port)) != 0 ||
4460 (r = sshpkt_send(ssh)) != 0)
4461 fatal_fr(r, "send cancel");
4462
4463 fwd_perm_clear(perm); /* unregister */
4464
4465 return 0;
4466}
4467
4468/*
4469 * Request cancellation of remote forwarding of Unix domain socket
4470 * path from local side.
4471 */
4472static int
4473channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4474{
4475 struct ssh_channels *sc = ssh->chanctxt;
4476 struct permission_set *pset = &sc->local_perms;
4477 int r;
4478 u_int i;
4479 struct permission *perm = NULL;
4480
4481 for (i = 0; i < pset->num_permitted_user; i++) {
4482 perm = &pset->permitted_user[i];
4483 if (open_listen_match_streamlocal(perm, path))
4484 break;
4485 perm = NULL;
4486 }
4487 if (perm == NULL) {
4488 debug_f("requested forward not found");
4489 return -1;
4490 }
4491 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4492 (r = sshpkt_put_cstring(ssh,
4493 "cancel-streamlocal-forward@openssh.com")) != 0 ||
4494 (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4495 (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4496 (r = sshpkt_send(ssh)) != 0)
4497 fatal_fr(r, "send cancel");
4498
4499 fwd_perm_clear(perm); /* unregister */
4500
4501 return 0;
4502}
4503
4504/*
4505 * Request cancellation of remote forwarding of a connection from local side.
4506 */
4507int
4508channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4509{
4510 if (fwd->listen_path != NULL) {
4511 return channel_request_rforward_cancel_streamlocal(ssh,
4512 fwd->listen_path);
4513 } else {
4514 return channel_request_rforward_cancel_tcpip(ssh,
4515 fwd->listen_host,
4516 fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4517 }
4518}
4519
4520/*
4521 * Permits opening to any host/port if permitted_user[] is empty. This is
4522 * usually called by the server, because the user could connect to any port
4523 * anyway, and the server has no way to know but to trust the client anyway.
4524 */
4525void
4526channel_permit_all(struct ssh *ssh, int where)
4527{
4528 struct permission_set *pset = permission_set_get(ssh, where);
4529
4530 if (pset->num_permitted_user == 0)
4531 pset->all_permitted = 1;
4532}
4533
4534/*
4535 * Permit the specified host/port for forwarding.
4536 */
4537void
4538channel_add_permission(struct ssh *ssh, int who, int where,
4539 char *host, int port)
4540{
4541 int local = where == FORWARD_LOCAL;
4542 struct permission_set *pset = permission_set_get(ssh, where);
4543
4544 debug("allow %s forwarding to host %s port %d",
4545 fwd_ident(who, where), host, port);
4546 /*
4547 * Remote forwards set listen_host/port, local forwards set
4548 * host/port_to_connect.
4549 */
4550 permission_set_add(ssh, who, where,
4551 local ? host : NULL, local ? port : 0,
4552 local ? NULL : host, NULL, local ? 0 : port, NULL);
4553 pset->all_permitted = 0;
4554}
4555
4556/*
4557 * Administratively disable forwarding.
4558 */
4559void
4560channel_disable_admin(struct ssh *ssh, int where)
4561{
4562 channel_clear_permission(ssh, FORWARD_ADM, where);
4563 permission_set_add(ssh, FORWARD_ADM, where,
4564 NULL, 0, NULL, NULL, 0, NULL);
4565}
4566
4567/*
4568 * Clear a list of permitted opens.
4569 */
4570void
4571channel_clear_permission(struct ssh *ssh, int who, int where)
4572{
4573 struct permission **permp;
4574 u_int i, *npermp;
4575
4576 permission_set_get_array(ssh, who, where, &permp, &npermp);
4577 for (i = 0; i < *npermp; i++)
4578 fwd_perm_clear((*permp) + i);
4579 free(*permp);
4580 *permp = NULL;
4581 *npermp = 0;
4582}
4583
4584/*
4585 * Update the listen port for a dynamic remote forward, after
4586 * the actual 'newport' has been allocated. If 'newport' < 0 is
4587 * passed then they entry will be invalidated.
4588 */
4589void
4590channel_update_permission(struct ssh *ssh, int idx, int newport)
4591{
4592 struct permission_set *pset = &ssh->chanctxt->local_perms;
4593
4594 if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4595 debug_f("index out of range: %d num_permitted_user %d",
4596 idx, pset->num_permitted_user);
4597 return;
4598 }
4599 debug("%s allowed port %d for forwarding to host %s port %d",
4600 newport > 0 ? "Updating" : "Removing",
4601 newport,
4602 pset->permitted_user[idx].host_to_connect,
4603 pset->permitted_user[idx].port_to_connect);
4604 if (newport <= 0)
4605 fwd_perm_clear(&pset->permitted_user[idx]);
4606 else {
4607 pset->permitted_user[idx].listen_port =
4608 (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4609 }
4610}
4611
4612/* Try to start non-blocking connect to next host in cctx list */
4613static int
4614connect_next(struct channel_connect *cctx)
4615{
4616 int sock, saved_errno;
4617 struct sockaddr_un *sunaddr;
4618 char ntop[NI_MAXHOST];
4619 char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4620
4621 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4622 switch (cctx->ai->ai_family) {
4623 case AF_UNIX:
4624 /* unix:pathname instead of host:port */
4625 sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4626 strlcpy(ntop, "unix", sizeof(ntop));
4627 strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4628 break;
4629 case AF_INET:
4630 case AF_INET6:
4631 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4632 ntop, sizeof(ntop), strport, sizeof(strport),
4633 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4634 error_f("getnameinfo failed");
4635 continue;
4636 }
4637 break;
4638 default:
4639 continue;
4640 }
4641 debug_f("start for host %.100s ([%.100s]:%s)",
4642 cctx->host, ntop, strport);
4643 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4644 cctx->ai->ai_protocol)) == -1) {
4645 if (cctx->ai->ai_next == NULL)
4646 error("socket: %.100s", strerror(errno));
4647 else
4648 verbose("socket: %.100s", strerror(errno));
4649 continue;
4650 }
4651 if (set_nonblock(sock) == -1)
4652 fatal_f("set_nonblock(%d)", sock);
4653 if (connect(sock, cctx->ai->ai_addr,
4654 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4655 debug_f("host %.100s ([%.100s]:%s): %.100s",
4656 cctx->host, ntop, strport, strerror(errno));
4657 saved_errno = errno;
4658 close(sock);
4659 errno = saved_errno;
4660 continue; /* fail -- try next */
4661 }
4662 if (cctx->ai->ai_family != AF_UNIX)
4663 set_nodelay(sock);
4664 debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
4665 cctx->host, ntop, strport, sock);
4666 cctx->ai = cctx->ai->ai_next;
4667 return sock;
4668 }
4669 return -1;
4670}
4671
4672static void
4673channel_connect_ctx_free(struct channel_connect *cctx)
4674{
4675 free(cctx->host);
4676 if (cctx->aitop) {
4677 if (cctx->aitop->ai_family == AF_UNIX)
4678 free(cctx->aitop);
4679 else
4680 freeaddrinfo(cctx->aitop);
4681 }
4682 memset(cctx, 0, sizeof(*cctx));
4683}
4684
4685/*
4686 * Return connecting socket to remote host:port or local socket path,
4687 * passing back the failure reason if appropriate.
4688 */
4689static int
4690connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4691 char *ctype, char *rname, struct channel_connect *cctx,
4692 int *reason, const char **errmsg)
4693{
4694 struct addrinfo hints;
4695 int gaierr;
4696 int sock = -1;
4697 char strport[NI_MAXSERV];
4698
4699 if (port == PORT_STREAMLOCAL) {
4700 struct sockaddr_un *sunaddr;
4701 struct addrinfo *ai;
4702
4703 if (strlen(name) > sizeof(sunaddr->sun_path)) {
4704 error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4705 return -1;
4706 }
4707
4708 /*
4709 * Fake up a struct addrinfo for AF_UNIX connections.
4710 * channel_connect_ctx_free() must check ai_family
4711 * and use free() not freeaddrinfo() for AF_UNIX.
4712 */
4713 ai = xcalloc(1, sizeof(*ai) + sizeof(*sunaddr));
4714 ai->ai_addr = (struct sockaddr *)(ai + 1);
4715 ai->ai_addrlen = sizeof(*sunaddr);
4716 ai->ai_family = AF_UNIX;
4717 ai->ai_socktype = socktype;
4718 ai->ai_protocol = PF_UNSPEC;
4719 sunaddr = (struct sockaddr_un *)ai->ai_addr;
4720 sunaddr->sun_family = AF_UNIX;
4721 strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4722 cctx->aitop = ai;
4723 } else {
4724 memset(&hints, 0, sizeof(hints));
4725 hints.ai_family = ssh->chanctxt->IPv4or6;
4726 hints.ai_socktype = socktype;
4727 snprintf(strport, sizeof strport, "%d", port);
4728 if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4729 != 0) {
4730 if (errmsg != NULL)
4731 *errmsg = ssh_gai_strerror(gaierr);
4732 if (reason != NULL)
4733 *reason = SSH2_OPEN_CONNECT_FAILED;
4734 error("connect_to %.100s: unknown host (%s)", name,
4735 ssh_gai_strerror(gaierr));
4736 return -1;
4737 }
4738 }
4739
4740 cctx->host = xstrdup(name);
4741 cctx->port = port;
4742 cctx->ai = cctx->aitop;
4743
4744 if ((sock = connect_next(cctx)) == -1) {
4745 error("connect to %.100s port %d failed: %s",
4746 name, port, strerror(errno));
4747 return -1;
4748 }
4749
4750 return sock;
4751}
4752
4753/* Return CONNECTING channel to remote host:port or local socket path */
4754static Channel *
4755connect_to(struct ssh *ssh, const char *host, int port,
4756 char *ctype, char *rname)
4757{
4758 struct channel_connect cctx;
4759 Channel *c;
4760 int sock;
4761
4762 memset(&cctx, 0, sizeof(cctx));
4763 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4764 &cctx, NULL, NULL);
4765 if (sock == -1) {
4766 channel_connect_ctx_free(&cctx);
4767 return NULL;
4768 }
4769 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4770 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4771 c->host_port = port;
4772 c->path = xstrdup(host);
4773 c->connect_ctx = cctx;
4774
4775 return c;
4776}
4777
4778/*
4779 * returns either the newly connected channel or the downstream channel
4780 * that needs to deal with this connection.
4781 */
4782Channel *
4783channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4784 u_short listen_port, char *ctype, char *rname)
4785{
4786 struct ssh_channels *sc = ssh->chanctxt;
4787 struct permission_set *pset = &sc->local_perms;
4788 u_int i;
4789 struct permission *perm;
4790
4791 for (i = 0; i < pset->num_permitted_user; i++) {
4792 perm = &pset->permitted_user[i];
4793 if (open_listen_match_tcpip(perm,
4794 listen_host, listen_port, 1)) {
4795 if (perm->downstream)
4796 return perm->downstream;
4797 if (perm->port_to_connect == 0)
4798 return rdynamic_connect_prepare(ssh,
4799 ctype, rname);
4800 return connect_to(ssh,
4801 perm->host_to_connect, perm->port_to_connect,
4802 ctype, rname);
4803 }
4804 }
4805 error("WARNING: Server requests forwarding for unknown listen_port %d",
4806 listen_port);
4807 return NULL;
4808}
4809
4810Channel *
4811channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4812 char *ctype, char *rname)
4813{
4814 struct ssh_channels *sc = ssh->chanctxt;
4815 struct permission_set *pset = &sc->local_perms;
4816 u_int i;
4817 struct permission *perm;
4818
4819 for (i = 0; i < pset->num_permitted_user; i++) {
4820 perm = &pset->permitted_user[i];
4821 if (open_listen_match_streamlocal(perm, path)) {
4822 return connect_to(ssh,
4823 perm->host_to_connect, perm->port_to_connect,
4824 ctype, rname);
4825 }
4826 }
4827 error("WARNING: Server requests forwarding for unknown path %.100s",
4828 path);
4829 return NULL;
4830}
4831
4832/* Check if connecting to that port is permitted and connect. */
4833Channel *
4834channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4835 char *ctype, char *rname, int *reason, const char **errmsg)
4836{
4837 struct ssh_channels *sc = ssh->chanctxt;
4838 struct permission_set *pset = &sc->local_perms;
4839 struct channel_connect cctx;
4840 Channel *c;
4841 u_int i, permit, permit_adm = 1;
4842 int sock;
4843 struct permission *perm;
4844
4845 permit = pset->all_permitted;
4846 if (!permit) {
4847 for (i = 0; i < pset->num_permitted_user; i++) {
4848 perm = &pset->permitted_user[i];
4849 if (open_match(perm, host, port)) {
4850 permit = 1;
4851 break;
4852 }
4853 }
4854 }
4855
4856 if (pset->num_permitted_admin > 0) {
4857 permit_adm = 0;
4858 for (i = 0; i < pset->num_permitted_admin; i++) {
4859 perm = &pset->permitted_admin[i];
4860 if (open_match(perm, host, port)) {
4861 permit_adm = 1;
4862 break;
4863 }
4864 }
4865 }
4866
4867 if (!permit || !permit_adm) {
4868 logit("Received request from %.100s port %d to connect to "
4869 "host %.100s port %d, but the request was denied.",
4870 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4871 if (reason != NULL)
4872 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4873 return NULL;
4874 }
4875
4876 memset(&cctx, 0, sizeof(cctx));
4877 sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4878 &cctx, reason, errmsg);
4879 if (sock == -1) {
4880 channel_connect_ctx_free(&cctx);
4881 return NULL;
4882 }
4883
4884 c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4885 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4886 c->host_port = port;
4887 c->path = xstrdup(host);
4888 c->connect_ctx = cctx;
4889
4890 return c;
4891}
4892
4893/* Check if connecting to that path is permitted and connect. */
4894Channel *
4895channel_connect_to_path(struct ssh *ssh, const char *path,
4896 char *ctype, char *rname)
4897{
4898 struct ssh_channels *sc = ssh->chanctxt;
4899 struct permission_set *pset = &sc->local_perms;
4900 u_int i, permit, permit_adm = 1;
4901 struct permission *perm;
4902
4903 permit = pset->all_permitted;
4904 if (!permit) {
4905 for (i = 0; i < pset->num_permitted_user; i++) {
4906 perm = &pset->permitted_user[i];
4907 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4908 permit = 1;
4909 break;
4910 }
4911 }
4912 }
4913
4914 if (pset->num_permitted_admin > 0) {
4915 permit_adm = 0;
4916 for (i = 0; i < pset->num_permitted_admin; i++) {
4917 perm = &pset->permitted_admin[i];
4918 if (open_match(perm, path, PORT_STREAMLOCAL)) {
4919 permit_adm = 1;
4920 break;
4921 }
4922 }
4923 }
4924
4925 if (!permit || !permit_adm) {
4926 logit("Received request to connect to path %.100s, "
4927 "but the request was denied.", path);
4928 return NULL;
4929 }
4930 return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4931}
4932
4933void
4934channel_send_window_changes(struct ssh *ssh)
4935{
4936 struct ssh_channels *sc = ssh->chanctxt;
4937 struct winsize ws;
4938 int r;
4939 u_int i;
4940
4941 for (i = 0; i < sc->channels_alloc; i++) {
4942 if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4943 sc->channels[i]->type != SSH_CHANNEL_OPEN)
4944 continue;
4945 if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4946 continue;
4947 channel_request_start(ssh, i, "window-change", 0);
4948 if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4949 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4950 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4951 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4952 (r = sshpkt_send(ssh)) != 0)
4953 fatal_fr(r, "channel %u; send window-change", i);
4954 }
4955}
4956
4957/* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4958static Channel *
4959rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4960{
4961 Channel *c;
4962 int r;
4963
4964 c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4965 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4966 c->host_port = 0;
4967 c->path = NULL;
4968
4969 /*
4970 * We need to open the channel before we have a FD,
4971 * so that we can get SOCKS header from peer.
4972 */
4973 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4974 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4975 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4976 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4977 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4978 fatal_fr(r, "channel %i; confirm", c->self);
4979 return c;
4980}
4981
4982/* Return CONNECTING socket to remote host:port or local socket path */
4983static int
4984rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4985{
4986 struct ssh_channels *sc = ssh->chanctxt;
4987 struct permission_set *pset = &sc->local_perms;
4988 struct permission *perm;
4989 struct channel_connect cctx;
4990 u_int i, permit_adm = 1;
4991 int sock;
4992
4993 if (pset->num_permitted_admin > 0) {
4994 permit_adm = 0;
4995 for (i = 0; i < pset->num_permitted_admin; i++) {
4996 perm = &pset->permitted_admin[i];
4997 if (open_match(perm, c->path, c->host_port)) {
4998 permit_adm = 1;
4999 break;
5000 }
5001 }
5002 }
5003 if (!permit_adm) {
5004 debug_f("requested forward not permitted");
5005 return -1;
5006 }
5007
5008 memset(&cctx, 0, sizeof(cctx));
5009 sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
5010 NULL, &cctx, NULL, NULL);
5011 if (sock == -1)
5012 channel_connect_ctx_free(&cctx);
5013 else {
5014 /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
5015 c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
5016 c->connect_ctx = cctx;
5017 channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
5018 }
5019 return sock;
5020}
5021
5022/* -- X11 forwarding */
5023
5024/*
5025 * Creates an internet domain socket for listening for X11 connections.
5026 * Returns 0 and a suitable display number for the DISPLAY variable
5027 * stored in display_numberp , or -1 if an error occurs.
5028 */
5029int
5030x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
5031 int x11_use_localhost, int single_connection,
5032 u_int *display_numberp, int **chanids)
5033{
5034 Channel *nc = NULL;
5035 int display_number, sock, port;
5036 struct addrinfo hints, *ai, *aitop;
5037 char strport[NI_MAXSERV];
5038 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
5039
5040 if (chanids == NULL || x11_display_offset < 0 ||
5041 x11_display_offset > UINT16_MAX - X11_BASE_PORT - MAX_DISPLAYS)
5042 return -1;
5043
5044 for (display_number = x11_display_offset;
5045 display_number < x11_display_offset + MAX_DISPLAYS;
5046 display_number++) {
5047 port = X11_BASE_PORT + display_number;
5048 memset(&hints, 0, sizeof(hints));
5049 hints.ai_family = ssh->chanctxt->IPv4or6;
5050 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
5051 hints.ai_socktype = SOCK_STREAM;
5052 snprintf(strport, sizeof strport, "%d", port);
5053 if ((gaierr = getaddrinfo(NULL, strport,
5054 &hints, &aitop)) != 0) {
5055 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
5056 return -1;
5057 }
5058 for (ai = aitop; ai; ai = ai->ai_next) {
5059 if (ai->ai_family != AF_INET &&
5060 ai->ai_family != AF_INET6)
5061 continue;
5062 sock = socket(ai->ai_family, ai->ai_socktype,
5063 ai->ai_protocol);
5064 if (sock == -1) {
5065 error("socket: %.100s", strerror(errno));
5066 freeaddrinfo(aitop);
5067 return -1;
5068 }
5069 set_reuseaddr(sock);
5070 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5071 debug2_f("bind port %d: %.100s", port,
5072 strerror(errno));
5073 close(sock);
5074 for (n = 0; n < num_socks; n++)
5075 close(socks[n]);
5076 num_socks = 0;
5077 break;
5078 }
5079 socks[num_socks++] = sock;
5080 if (num_socks == NUM_SOCKS)
5081 break;
5082 }
5083 freeaddrinfo(aitop);
5084 if (num_socks > 0)
5085 break;
5086 }
5087 if (display_number >= x11_display_offset + MAX_DISPLAYS) {
5088 error("Failed to allocate internet-domain X11 display socket.");
5089 return -1;
5090 }
5091 /* Start listening for connections on the socket. */
5092 for (n = 0; n < num_socks; n++) {
5093 sock = socks[n];
5094 if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
5095 error("listen: %.100s", strerror(errno));
5096 close(sock);
5097 return -1;
5098 }
5099 }
5100
5101 /* Allocate a channel for each socket. */
5102 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
5103 for (n = 0; n < num_socks; n++) {
5104 sock = socks[n];
5105 nc = channel_new(ssh, "x11-listener",
5106 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
5107 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
5108 0, "X11 inet listener", 1);
5109 nc->single_connection = single_connection;
5110 (*chanids)[n] = nc->self;
5111 }
5112 (*chanids)[n] = -1;
5113
5114 /* Return the display number for the DISPLAY environment variable. */
5115 *display_numberp = display_number;
5116 return 0;
5117}
5118
5119static int
5120connect_local_xsocket(u_int dnr)
5121{
5122 int sock;
5123 struct sockaddr_un addr;
5124
5125 sock = socket(AF_UNIX, SOCK_STREAM, 0);
5126 if (sock == -1)
5127 error("socket: %.100s", strerror(errno));
5128 memset(&addr, 0, sizeof(addr));
5129 addr.sun_family = AF_UNIX;
5130 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
5131 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
5132 return sock;
5133 close(sock);
5134 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
5135 return -1;
5136}
5137
5138int
5139x11_connect_display(struct ssh *ssh)
5140{
5141 u_int display_number;
5142 const char *display;
5143 char buf[1024], *cp;
5144 struct addrinfo hints, *ai, *aitop;
5145 char strport[NI_MAXSERV];
5146 int gaierr, sock = 0;
5147
5148 /* Try to open a socket for the local X server. */
5149 display = getenv("DISPLAY");
5150 if (!display) {
5151 error("DISPLAY not set.");
5152 return -1;
5153 }
5154 /*
5155 * Now we decode the value of the DISPLAY variable and make a
5156 * connection to the real X server.
5157 */
5158
5159 /*
5160 * Check if it is a unix domain socket. Unix domain displays are in
5161 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
5162 */
5163 if (strncmp(display, "unix:", 5) == 0 ||
5164 display[0] == ':') {
5165 /* Connect to the unix domain socket. */
5166 if (sscanf(strrchr(display, ':') + 1, "%u",
5167 &display_number) != 1) {
5168 error("Could not parse display number from DISPLAY: "
5169 "%.100s", display);
5170 return -1;
5171 }
5172 /* Create a socket. */
5173 sock = connect_local_xsocket(display_number);
5174 if (sock < 0)
5175 return -1;
5176
5177 /* OK, we now have a connection to the display. */
5178 return sock;
5179 }
5180 /*
5181 * Connect to an inet socket. The DISPLAY value is supposedly
5182 * hostname:d[.s], where hostname may also be numeric IP address.
5183 */
5184 strlcpy(buf, display, sizeof(buf));
5185 cp = strchr(buf, ':');
5186 if (!cp) {
5187 error("Could not find ':' in DISPLAY: %.100s", display);
5188 return -1;
5189 }
5190 *cp = 0;
5191 /*
5192 * buf now contains the host name. But first we parse the
5193 * display number.
5194 */
5195 if (sscanf(cp + 1, "%u", &display_number) != 1 ||
5196 display_number > UINT16_MAX - X11_BASE_PORT) {
5197 error("Could not parse display number from DISPLAY: %.100s",
5198 display);
5199 return -1;
5200 }
5201
5202 /* Look up the host address */
5203 memset(&hints, 0, sizeof(hints));
5204 hints.ai_family = ssh->chanctxt->IPv4or6;
5205 hints.ai_socktype = SOCK_STREAM;
5206 snprintf(strport, sizeof strport, "%u", X11_BASE_PORT + display_number);
5207 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5208 error("%.100s: unknown host. (%s)", buf,
5209 ssh_gai_strerror(gaierr));
5210 return -1;
5211 }
5212 for (ai = aitop; ai; ai = ai->ai_next) {
5213 /* Create a socket. */
5214 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5215 if (sock == -1) {
5216 debug2("socket: %.100s", strerror(errno));
5217 continue;
5218 }
5219 /* Connect it to the display. */
5220 if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5221 debug2("connect %.100s port %u: %.100s", buf,
5222 X11_BASE_PORT + display_number, strerror(errno));
5223 close(sock);
5224 continue;
5225 }
5226 /* Success */
5227 break;
5228 }
5229 freeaddrinfo(aitop);
5230 if (!ai) {
5231 error("connect %.100s port %u: %.100s", buf,
5232 X11_BASE_PORT + display_number, strerror(errno));
5233 return -1;
5234 }
5235 set_nodelay(sock);
5236 return sock;
5237}
5238
5239/*
5240 * Requests forwarding of X11 connections, generates fake authentication
5241 * data, and enables authentication spoofing.
5242 * This should be called in the client only.
5243 */
5244void
5245x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5246 const char *disp, const char *proto, const char *data, int want_reply)
5247{
5248 struct ssh_channels *sc = ssh->chanctxt;
5249 u_int data_len = (u_int) strlen(data) / 2;
5250 u_int i, value;
5251 const char *cp;
5252 char *new_data;
5253 int r, screen_number;
5254
5255 if (sc->x11_saved_display == NULL)
5256 sc->x11_saved_display = xstrdup(disp);
5257 else if (strcmp(disp, sc->x11_saved_display) != 0) {
5258 error("x11_request_forwarding_with_spoofing: different "
5259 "$DISPLAY already forwarded");
5260 return;
5261 }
5262
5263 cp = strchr(disp, ':');
5264 if (cp)
5265 cp = strchr(cp, '.');
5266 if (cp)
5267 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5268 else
5269 screen_number = 0;
5270
5271 if (sc->x11_saved_proto == NULL) {
5272 /* Save protocol name. */
5273 sc->x11_saved_proto = xstrdup(proto);
5274
5275 /* Extract real authentication data. */
5276 sc->x11_saved_data = xmalloc(data_len);
5277 for (i = 0; i < data_len; i++) {
5278 if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5279 fatal("x11_request_forwarding: bad "
5280 "authentication data: %.100s", data);
5281 }
5282 sc->x11_saved_data[i] = value;
5283 }
5284 sc->x11_saved_data_len = data_len;
5285
5286 /* Generate fake data of the same length. */
5287 sc->x11_fake_data = xmalloc(data_len);
5288 arc4random_buf(sc->x11_fake_data, data_len);
5289 sc->x11_fake_data_len = data_len;
5290 }
5291
5292 /* Convert the fake data into hex. */
5293 new_data = tohex(sc->x11_fake_data, data_len);
5294
5295 /* Send the request packet. */
5296 channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5297 if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5298 (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5299 (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5300 (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5301 (r = sshpkt_send(ssh)) != 0 ||
5302 (r = ssh_packet_write_wait(ssh)) != 0)
5303 fatal_fr(r, "send x11-req");
5304 free(new_data);
5305}
5306
5307/*
5308 * Returns whether an x11 channel was used recently (less than a second ago)
5309 */
5310int
5311x11_channel_used_recently(struct ssh *ssh) {
5312 u_int i;
5313 Channel *c;
5314 time_t lastused = 0;
5315
5316 for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
5317 c = ssh->chanctxt->channels[i];
5318 if (c == NULL || c->ctype == NULL || c->lastused == 0 ||
5319 strcmp(c->ctype, "x11-connection") != 0)
5320 continue;
5321 if (c->lastused > lastused)
5322 lastused = c->lastused;
5323 }
5324 return lastused != 0 && monotime() <= lastused + 1;
5325}