History log of /openbsd-current/usr.bin/ssh/channels.h
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.156 23-May-2024 jsg

remove unused struct fwd_perm_list, no decl with complete type
ok djm@


# 1.155 17-May-2024 jsg

remove prototypes with no matching function; ok djm@


Revision tags: OPENBSD_7_5_BASE
# 1.154 18-Dec-2023 djm

stricter handling of channel window limits

This makes ssh/sshd more strict in handling non-compliant peers that
send more data than the advertised channel window allows. Previously
the additional data would be silently discarded. This change will
cause ssh/sshd to terminate the connection if the channel window is
exceeded by more than a small grace allowance.

ok markus@


# 1.153 15-Nov-2023 djm

when deciding whether to enable keystroke timing obfuscation,
only consider enabling it when a channel with a tty is open.

Avoids turning on the obfucation when X11 forwarding only is in use,
which slows it right down. Reported by Roger Marsh


Revision tags: OPENBSD_7_4_BASE
# 1.152 04-Sep-2023 djm

make channel_output_poll() return a flag indicating whether channel
data was enqueued. Will be used to improve keystroke timing
obfuscation. Problem spotted by / tested by naddy@


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.155 17-May-2024 jsg

remove prototypes with no matching function; ok djm@


Revision tags: OPENBSD_7_5_BASE
# 1.154 18-Dec-2023 djm

stricter handling of channel window limits

This makes ssh/sshd more strict in handling non-compliant peers that
send more data than the advertised channel window allows. Previously
the additional data would be silently discarded. This change will
cause ssh/sshd to terminate the connection if the channel window is
exceeded by more than a small grace allowance.

ok markus@


# 1.153 15-Nov-2023 djm

when deciding whether to enable keystroke timing obfuscation,
only consider enabling it when a channel with a tty is open.

Avoids turning on the obfucation when X11 forwarding only is in use,
which slows it right down. Reported by Roger Marsh


Revision tags: OPENBSD_7_4_BASE
# 1.152 04-Sep-2023 djm

make channel_output_poll() return a flag indicating whether channel
data was enqueued. Will be used to improve keystroke timing
obfuscation. Problem spotted by / tested by naddy@


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.154 18-Dec-2023 djm

stricter handling of channel window limits

This makes ssh/sshd more strict in handling non-compliant peers that
send more data than the advertised channel window allows. Previously
the additional data would be silently discarded. This change will
cause ssh/sshd to terminate the connection if the channel window is
exceeded by more than a small grace allowance.

ok markus@


# 1.153 15-Nov-2023 djm

when deciding whether to enable keystroke timing obfuscation,
only consider enabling it when a channel with a tty is open.

Avoids turning on the obfucation when X11 forwarding only is in use,
which slows it right down. Reported by Roger Marsh


Revision tags: OPENBSD_7_4_BASE
# 1.152 04-Sep-2023 djm

make channel_output_poll() return a flag indicating whether channel
data was enqueued. Will be used to improve keystroke timing
obfuscation. Problem spotted by / tested by naddy@


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.153 15-Nov-2023 djm

when deciding whether to enable keystroke timing obfuscation,
only consider enabling it when a channel with a tty is open.

Avoids turning on the obfucation when X11 forwarding only is in use,
which slows it right down. Reported by Roger Marsh


Revision tags: OPENBSD_7_4_BASE
# 1.152 04-Sep-2023 djm

make channel_output_poll() return a flag indicating whether channel
data was enqueued. Will be used to improve keystroke timing
obfuscation. Problem spotted by / tested by naddy@


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.152 04-Sep-2023 djm

make channel_output_poll() return a flag indicating whether channel
data was enqueued. Will be used to improve keystroke timing
obfuscation. Problem spotted by / tested by naddy@


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.151 04-Jul-2023 dlg

add support for unix domain sockets to ssh -W

ok djm@ dtucker@


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.150 05-Jun-2023 millert

Store timeouts as int, not u_int as they are limited to INT_MAX.
Fixes sign compare warnings systems with 32-bit time_t due to type
promotion. OK djm@


Revision tags: OPENBSD_7_3_BASE
# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.149 04-Mar-2023 dtucker

Use time_t instead of u_int for remaining x11 timeout checks for 64bit
time_t safety. From Coverity CIDs 405197 and 405028, ok djm@


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.148 18-Jan-2023 djm

when restoring non-blocking mode to stdio fds, restore exactly
the flags that ssh started with and don't just clobber them with
zero, as this could also remove the append flag from the set;

bz3523; ok dtucker@


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.147 06-Jan-2023 djm

Implement channel inactivity timeouts

This adds a sshd_config ChannelTimeouts directive that allows channels that
have not seen traffic in a configurable interval to be automatically closed.
Different timeouts may be applied to session, X11, agent and TCP forwarding
channels.

Note: this only affects channels over an opened SSH connection and not
the connection itself. Most clients close the connection when their channels
go away, with a notable exception being ssh(1) in multiplexing mode.

ok markus dtucker


# 1.146 06-Jan-2023 djm

Add channel_set_xtype()

This sets an "extended" channel type after channel creation (e.g.
"session:subsystem:sftp") that will be used for setting channel inactivity
timeouts.

ok markus dtucker


# 1.145 06-Jan-2023 djm

Add channel_force_close()

This will forcibly close an open channel by simulating read/write errors,
draining the IO buffers and calling the detach function.

Previously the detach function was only ever called during channel garbage
collection, but there was no way to signal the user of a channel (e.g.
session.c) that its channel was being closed deliberately (vs. by the
usual state-machine logic). So this adds an extra "force" argument to the
channel cleanup callback to indicate this condition.

ok markus dtucker


# 1.144 06-Jan-2023 djm

replace manual poll/ppoll timeout math with ptimeout API

feedback markus / ok markus dtucker


Revision tags: OPENBSD_7_2_BASE
# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.143 05-May-2022 djm

channel_new no longer frees remote_name. So update the comment
accordingly. As remote_name is not modified, it can be const
as well. From Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.142 30-Mar-2022 djm

fix poll() spin when a channel's output fd closes without data in the
channel buffer. Introduce more exact packing of channel fds into the
pollfd array. fixes bz3405 and bz3411; ok deraadt@ markus@


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.141 22-Jan-2022 djm

add a ssh_packet_process_read() function that reads from a fd
directly into the transport input buffer.

Use this in the client and server mainloops to avoid unnecessary
copying. It also lets us use a more greedy read size without penalty.

Yields a 2-3% performance gain on cipher-speed.sh (in a fairly
unscientific test tbf)

feedback dtucker@ ok markus@


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.140 06-Jan-2022 djm

convert ssh, sshd mainloops from select() to poll();
feedback & ok deraadt@ and markus@
has been in snaps for a few months


# 1.139 06-Jan-2022 djm

prepare for conversion of ssh, sshd mainloop from select() to poll()
by moving FD_SET construction out of channel handlers into separate
functions. ok markus


Revision tags: OPENBSD_7_0_BASE
# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.138 19-May-2021 djm

restore blocking status on stdio fds before close

ssh(1) needs to set file descriptors to non-blocking mode to operate
but it was not restoring the original state on exit. This could cause
problems with fds shared with other programs via the shell, e.g.

> $ cat > test.sh << _EOF
> #!/bin/sh
> {
> ssh -Fnone -oLogLevel=verbose ::1 hostname
> cat /usr/share/dict/words
> } | sleep 10
> _EOF
> $ ./test.sh
> Authenticated to ::1 ([::1]:22).
> Transferred: sent 2352, received 2928 bytes, in 0.1 seconds
> Bytes per second: sent 44338.9, received 55197.4
> cat: stdout: Resource temporarily unavailable

This restores the blocking status for fds 0,1,2 (stdio) before ssh(1)
abandons/closes them.

This was reported as bz3280 and GHPR246; ok dtucker@


Revision tags: OPENBSD_6_9_BASE
# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.137 03-Apr-2021 djm

highly polished whitespace, mostly fixing spaces-for-tab and bad
indentation on continuation lines. Prompted by GHPR#185


# 1.136 03-Apr-2021 djm

whitespace (tab after space)


Revision tags: OPENBSD_6_8_BASE
# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.135 20-Sep-2020 djm

cap channel input buffer size at 16MB; avoids high memory use when
peer advertises a large window but is slow to consume the data we
send (e.g. because of a slow network)

reported by Pierre-Yves David

fix with & ok markus@


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.134 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.133 25-Jan-2020 djm

add a comment describing the ranges of channel IDs that we use;
requested by markus@


Revision tags: OPENBSD_6_4_BASE OPENBSD_6_5_BASE OPENBSD_6_6_BASE
# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.132 04-Oct-2018 djm

include a little more information about the status and disposition of
channel's extended (stderr) fd; makes debugging some things a bit easier.
No behaviour change.


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


# 1.131 06-Jun-2018 djm

Add a PermitListen directive to control which server-side addresses
may be listened on when the client requests remote forwarding (ssh -R).

This is the converse of the existing PermitOpen directive and this
includes some refactoring to share much of its implementation.

feedback and ok markus@


Revision tags: OPENBSD_6_2_BASE OPENBSD_6_3_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3


Revision tags: OPENBSD_6_2_BASE
# 1.130 21-Sep-2017 markus

Add 'reverse' dynamic forwarding which combines dynamic forwarding
(-D) with remote forwarding (-R) where the remote-forwarded port
expects SOCKS-requests.

The SSH server code is unchanged and the parsing happens at the SSH
clients side. Thus the full SOCKS-request is sent over the forwarded
channel and the client parses c->output. Parsing happens in
channel_before_prepare_select(), _before_ the select bitmask is
computed in the pre[] handlers, but after network input processing
in the post[] handlers.

help and ok djm@


# 1.129 12-Sep-2017 djm

Make remote channel ID a u_int

Previously we tracked the remote channel IDs in an int, but this is
strictly incorrect: the wire protocol uses uint32 and there is nothing
in-principle stopping a SSH implementation from sending, say, 0xffff0000.

In practice everyone numbers their channels sequentially, so this has
never been a problem.

ok markus@


# 1.128 12-Sep-2017 djm

refactor channels.c

Move static state to a "struct ssh_channels" that is allocated at
runtime and tracked as a member of struct ssh.

Explicitly pass "struct ssh" to all channels functions.

Replace use of the legacy packet APIs in channels.c.

Rework sshd_config PermitOpen handling: previously the configuration
parser would call directly into the channels layer. After the refactor
this is not possible, as the channels structures are allocated at
connection time and aren't available when the configuration is parsed.
The server config parser now tracks PermitOpen itself and explicitly
configures the channels code later.

ok markus@


# 1.127 30-Aug-2017 djm

pass packet state down to some of the channels function (more
to come...); ok markus@


# 1.126 30-May-2017 markus

protocol handlers all get struct ssh passed; ok djm@


# 1.125 26-May-2017 markus

remove SSH_CHANNEL_XXX_DRAINING (ssh1 only); ok djm@


# 1.124 26-May-2017 markus

remove channel_input_close_confirmation (ssh1 only); ok djm@


# 1.123 30-Apr-2017 djm

obliterate ssh1.h and some dead code that used it

ok markus@


# 1.122 30-Apr-2017 djm

remove compat20/compat13/compat15 variables

ok markus@


Revision tags: OPENBSD_6_1_BASE
# 1.121 01-Feb-2017 dtucker

Return true reason for port forwarding failures where feasible rather
than always "administratively prohibited". bz#2674, ok djm@


# 1.120 18-Oct-2016 dtucker

Remove channel_input_port_forward_request(); the only caller was the
recently-removed SSH1 server code so it's now dead code. ok markus@


# 1.119 30-Sep-2016 markus

ssh proxy mux mode (-O proxy; idea from Simon Tatham):
- mux client speaks the ssh-packet protocol directly over unix-domain socket.
- mux server acts as a proxy, translates channel IDs and relays to the server.
- no filedescriptor passing necessary.
- combined with unix-domain forwarding it's even possible to run mux client
and server on different machines.
feedback & ok djm@


Revision tags: OPENBSD_5_8_BASE OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.118 01-Jul-2015 djm

better refuse ForwardX11Trusted=no connections attempted after
ForwardX11Timeout expires; reported by Jann Horn


# 1.117 08-May-2015 djm

moar whitespace at eol


Revision tags: OPENBSD_5_7_BASE
# 1.116 19-Jan-2015 markus

move dispatch to struct ssh; ok djm@


Revision tags: OPENBSD_5_6_BASE
# 1.115 15-Jul-2014 millert

Add support for Unix domain socket forwarding. A remote TCP port
may be forwarded to a local Unix domain socket and vice versa or
both ends may be a Unix domain socket. This is a reimplementation
of the streamlocal patches by William Ahern from:
http://www.25thandclement.com/~william/projects/streamlocal.html
OK djm@ markus@


# 1.114 27-Jun-2014 markus

fix remote fwding with same listen port but different listen address
with gerhard@, ok djm@


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.113 07-Jun-2013 dtucker

Add an "ABANDONED" channel state and use for mux sessions that are
disconnected via the ~. escape sequence. Channels in this state will
be able to close if the server responds, but do not count as active channels.
This means that if you ~. all of the mux clients when using ControlPersist
on a broken network, the backgrounded mux master will exit when the
Control Persist time expires rather than hanging around indefinitely.
bz#1917, also reported and tested by tedu@. ok djm@ markus@.


# 1.112 02-Jun-2013 dtucker

typo in comment


Revision tags: OPENBSD_5_2_BASE OPENBSD_5_3_BASE
# 1.111 11-Apr-2012 djm

don't spin in accept() when out of fds (ENFILE/ENFILE) - back off for a
while; ok deraadt@ markus@


# 1.110 29-Mar-2012 dtucker

Add PermitOpen none option based on patch from Loganaden Velvindron
(bz #1949). ok djm@


Revision tags: OPENBSD_5_1_BASE
# 1.109 23-Sep-2011 markus

unbreak remote portforwarding with dynamic allocated listen ports:
1) send the actual listen port in the open message (instead of 0).
this allows multiple forwardings with a dynamic listen port
2) update the matching permit-open entry, so we can identify where
to connect to
report: den at skbkontur.ru and P. Szczygielski
feedback and ok djm@


# 1.108 23-Sep-2011 dtucker

Add wildcard support to PermitOpen, allowing things like "PermitOpen
localhost:*". bz #1857, ok djm markus.


# 1.107 10-Sep-2011 markus

support cancellation of local/dynamic forwardings from ~C commandline;
ok & feedback djm@


# 1.106 09-Sep-2011 djm

support for cancelling local and remote port forwards via the multiplex
socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host" to request
the cancellation of the specified forwardings; ok markus@


Revision tags: OPENBSD_5_0_BASE
# 1.105 22-Jun-2011 djm

hook up a channel confirm callback to warn the user then requested X11
forwarding was refused by the server; ok markus@


Revision tags: OPENBSD_4_8_BASE OPENBSD_4_9_BASE
# 1.104 14-May-2010 djm

Pause the mux channel while waiting for reply from aynch callbacks.
Prevents misordering of replies if new requests arrive while waiting.

Extend channel open confirm callback to allow signalling failure
conditions as well as success. Use this to 1) fix a memory leak, 2)
start using the above pause mechanism and 3) delay sending a success/
failure message on mux slave session open until we receive a reply from
the server.

motivated by and with feedback from markus@


Revision tags: OPENBSD_4_7_BASE
# 1.103 26-Jan-2010 djm

rewrite ssh(1) multiplexing code to a more sensible protocol.

The new multiplexing code uses channels for the listener and
accepted control sockets to make the mux master non-blocking, so
no stalls when processing messages from a slave.

avoid use of fatal() in mux master protocol parsing so an errant slave
process cannot take down a running master.

implement requesting of port-forwards over multiplexed sessions. Any
port forwards requested by the slave are added to those the master has
established.

add support for stdio forwarding ("ssh -W host:port ...") in mux slaves.

document master/slave mux protocol so that other tools can use it to
control a running ssh(1). Note: there are no guarantees that this
protocol won't be incompatibly changed (though it is versioned).

feedback Salvador Fandino, dtucker@
channel changes ok markus@


# 1.102 11-Jan-2010 dtucker

Add a 'netcat mode' (ssh -W). This connects stdio on the client to a single
port forward on the server. This allows, for example, using ssh as
a ProxyCommand to route connections via intermediate servers.
bz #1618, man page help from jmc@, ok markus@


# 1.101 09-Jan-2010 dtucker

Remove RoutingDomain from ssh since it's now not needed. It can be replaced
with "route exec" or "nc -V" as a proxycommand. "route exec" also ensures
that trafic such as DNS lookups stays withing the specified routingdomain.

For example (from reyk):
# route -T 2 exec /usr/sbin/sshd
or inherited from the parent process
$ route -T 2 exec sh
$ ssh 10.1.2.3

ok deraadt@ markus@ stevesk@ reyk@


# 1.100 11-Nov-2009 markus

fix race condition in x11/agent channel allocation: don't read after
the end of the select read/write fdset and make sure a reused FD
is not touched before the pre-handlers are called.
with and ok djm@


# 1.99 28-Oct-2009 reyk

Allow to set the rdomain in ssh/sftp/scp/sshd and ssh-keyscan.

ok markus@


Revision tags: OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.98 12-Feb-2009 djm

support remote port forwarding with a zero listen port (-R0:...) to
dyamically allocate a listen port at runtime (this is actually
specified in rfc4254); bz#1003 ok markus@


# 1.97 22-Jan-2009 djm

make Channel->path an allocated string, saving a few bytes here and
there and fixing bz#1380 in the process; ok markus@


Revision tags: OPENBSD_4_4_BASE
# 1.96 15-Jun-2008 djm

don't call isatty() on a pty master, instead pass a flag down to
channel_set_fds() indicating that te fds refer to a tty. Fixes a
hang on exit on Solaris (bz#1463) in portable but is actually
a generic bug; ok dtucker deraadt markus


# 1.95 12-Jun-2008 djm

The multiplexing escape char handler commit last night introduced a
small memory leak per session; plug it.


# 1.94 12-Jun-2008 djm

Enable ~ escapes for multiplex slave sessions; give each channel
its own escape state and hook the escape filters up to muxed
channels. bz #1331

Mux slaves do not currently support the ~^Z and ~& escapes.

NB. this change cranks the mux protocol version, so a new ssh
mux client will not be able to connect to a running old ssh
mux master.

ok dtucker@


# 1.93 10-Jun-2008 dtucker

Add extended test mode (-T) and connection parameters for test mode (-C).
-T causes sshd to write its effective configuration to stdout and exit.
-C causes any relevant Match rules to be applied before output. The
combination allows tesing of the parser and config files. ok deraadt djm


# 1.92 09-May-2008 markus

unbreak
ssh -2 localhost od /bin/ls | true
ignoring SIGPIPE by adding a new channel message (EOW) that signals
the peer that we're not interested in any data it might send.
fixes bz #85; discussion, debugging and ok djm@


# 1.91 09-May-2008 djm

Try additional addresses when connecting to a port forward destination
whose DNS name resolves to more than one address. The previous behaviour
was to try the first address and give up.

Reported by stig AT venaas.com in bz#343

great feedback and ok markus@


# 1.90 08-May-2008 djm

Implement a channel success/failure status confirmation callback
mechanism. Each channel maintains a queue of callbacks, which will
be drained in order (RFC4253 guarantees confirm messages are not
reordered within an channel).

Also includes a abandonment callback to clean up if a channel is
closed without sending confirmation messages. This probably
shouldn't happen in compliant implementations, but it could be
abused to leak memory.

ok markus@ (as part of a larger diff)


Revision tags: OPENBSD_4_2_BASE OPENBSD_4_3_BASE
# 1.89 11-Jun-2007 markus

increase default channel windows; ok djm


Revision tags: OPENBSD_4_0_BASE OPENBSD_4_1_BASE
# 1.88 03-Aug-2006 deraadt

almost entirely get rid of the culture of ".h files that include .h files"
ok djm, sort of ok stevesk
makes the pain stop in one easy step


# 1.87 21-Jul-2006 dtucker

Make PermitOpen take a list of permitted ports and act more like most other
keywords (ie the first match is the effective setting). This also makes it
easier to override a previously set PermitOpen. ok djm@


# 1.86 17-Jul-2006 dtucker

Add PermitOpen directive to sshd_config which is equivalent to the
"permitopen" key option. Allows server admin to allow TCP port forwarding
only two specific host/port pairs. Useful when combined with Match.

If permitopen is used in both sshd_config and a key option, both must allow
a given connection before it will be permitted.

Note that users can still use external forwarders such as netcat, so to be
those must be controlled too for the limits to be effective.

Feedback & ok djm@, man page corrections & ok jmc@.


# 1.85 11-Jul-2006 markus

add ExitOnForwardFailure: terminate the connection if ssh(1)
cannot set up all requested dynamic, local, and remote port
forwardings. ok djm, dtucker, stevesk, jmc


# 1.84 25-Mar-2006 djm

standardise spacing in $OpenBSD$ tags; requested by deraadt@


Revision tags: OPENBSD_3_9_BASE
# 1.83 30-Dec-2005 reyk

branches: 1.83.2;
add channel output filter interface.

ok djm@, suggested by markus@


# 1.82 12-Dec-2005 markus

make sure protocol messages for internal channels are ignored.
allow adjust messages for non-open channels; with and ok djm@


# 1.81 06-Dec-2005 reyk

Add support for tun(4) forwarding over OpenSSH, based on an idea and
initial channel code bits by markus@. This is a simple and easy way to
use OpenSSH for ad hoc virtual private network connections, e.g.
administrative tunnels or secure wireless access. It's based on a new
ssh channel and works similar to the existing TCP forwarding support,
except that it depends on the tun(4) network interface on both ends of
the connection for layer 2 or layer 3 tunneling. This diff also adds
support for LocalCommand in the ssh(1) client.

ok djm@, markus@, jmc@ (manpages), tested and discussed with others


# 1.80 10-Oct-2005 djm

fix regression I introduced in 4.2: X11 forwardings initiated after
a session has exited (e.g. "(sleep 5; xterm) &") would not start.
bz #1086 reported by t8m AT centrum.cz; ok markus@ dtucker@


Revision tags: OPENBSD_3_8_BASE
# 1.79 17-Jul-2005 djm

branches: 1.79.2;
Fix a number of X11 forwarding channel leaks:
1. Refuse multiple X11 forwarding requests on the same session
2. Clean up all listeners after a single_connection X11 forward, not just
the one that made the single connection
3. Destroy X11 listeners when the session owning them goes away
testing and ok dtucker@


# 1.78 08-Jul-2005 markus

race when efd gets closed while there is still buffered data:
change CHANNEL_EFD_OUTPUT_ACTIVE()
1) c->efd must always be valid AND
2a) no EOF has been seen OR
2b) there is buffered data
report, initial fix and testing Chuck Cranor


# 1.77 16-Jun-2005 djm

move x11_get_proto from ssh.c to clientloop.c, to make muliplexed xfwd easier
later; ok deraadt@


Revision tags: OPENBSD_3_7_BASE
# 1.76 01-Mar-2005 djm

branches: 1.76.2;
bz#413: allow optional specification of bind address for port forwardings.
Patch originally by Dan Astorian, but worked on by several people
Adds GatewayPorts=clientspecified option on server to allow remote forwards
to bind to client-specified ports.

ok markus@


# 1.75 29-Oct-2004 djm

fix some window size change bugs for multiplexed connections: windows sizes
were not being updated if they had changed after ~^Z suspends and SIGWINCH
was not being processed unless the first connection had requested a tty;
ok markus


Revision tags: OPENBSD_3_6_BASE
# 1.74 11-Aug-2004 avsm

branches: 1.74.2;
some signed/unsigned int comparison cleanups; markus@ ok


# 1.73 13-Jun-2004 djm

implement session multiplexing in the client (the server has supported this
since 2.0); ok markus@


# 1.72 21-May-2004 djm

bz #756: add support for the cancel-tcpip-forward request for the server and
the client (through the ~C commandline). reported by z3p AT twistedmatrix.com;
ok markus@


Revision tags: OPENBSD_3_5_BASE
# 1.71 23-Sep-2003 markus

branches: 1.71.2;
move client only agent code to clientloop.c


Revision tags: OPENBSD_3_2_BASE OPENBSD_3_3_BASE OPENBSD_3_4_BASE
# 1.70 24-Jun-2002 markus

branches: 1.70.4; 1.70.6;
move channel counter to u_int


# 1.69 23-Jun-2002 deraadt

display, screen, row, col, xpixel, ypixel are u_int; markus ok


# 1.68 10-Jun-2002 markus

move creation of agent socket to session.c; no need for uidswapping
in channel.c.


Revision tags: OPENBSD_3_1_BASE
# 1.67 26-Mar-2002 markus

branches: 1.67.2;
CHANNEL_EFD_OUTPUT_ACTIVE is false for CHAN_CLOSE_RCVD, too


# 1.66 25-Mar-2002 markus

don't send stderr data after EOF, accept this from older known (broken)
sshd servers only, fixes http://bugzilla.mindrot.org/show_bug.cgi?id=179


# 1.65 04-Mar-2002 stevesk

$OpenBSD$ and RCSID() cleanup: don't use RCSID() in .h files; add
missing RCSID() to .c files and remove dup /*$OpenBSD$*/ from .c
files. ok markus@


# 1.64 14-Feb-2002 markus

increase the SSH v2 window size to 4 packets. comsumes a little
bit more memory for slow receivers but increases througput.


# 1.63 05-Feb-2002 markus

merge channel_request() into channel_request_start()


# 1.62 03-Feb-2002 markus

generic callbacks are not really used, remove and
add a callback for msg of type SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
ok djm@


# 1.61 03-Feb-2002 markus

remove unused channel_input_channel_request


# 1.60 16-Jan-2002 markus

wrapper for channel_setup_fwd_listener


# 1.59 14-Jan-2002 markus

(c) 2002


# 1.58 14-Jan-2002 markus

remove function pointers for events, remove chan_init*; ok provos@


# 1.57 13-Jan-2002 markus

add chan_set_[io]state(), order states, state is now an u_int,
simplifies debugging messages; ok provos@


# 1.56 28-Dec-2001 markus

remove plen from the dispatch fn. it's no longer used.


# 1.55 20-Dec-2001 djm

Conformance fix: we should send failing packet sequence number when
responding with a SSH_MSG_UNIMPLEMENTED message. Spotted by
yakk@yakk.dot.net; ok markus@


# 1.54 20-Dec-2001 markus

setup x11 listen socket for just one connect if the client requests so.
(v2 only, but the openssh client does not support this feature).


# 1.53 29-Nov-2001 stevesk

sshd X11 fake server will now listen on localhost by default:
$ echo $DISPLAY
localhost:12.0
$ netstat -an|grep 6012
tcp 0 0 127.0.0.1.6012 *.* LISTEN
tcp6 0 0 ::1.6012 *.* LISTEN
sshd_config gatewayports=yes can be used to revert back to the old
behavior. will control this with another option later. ok markus@


# 1.52 29-Nov-2001 stevesk

remove dead function prototype; ok markus@


# 1.51 07-Nov-2001 markus

crank c->path to 256 so they can hold a full hostname; dwd@bell-labs.com


Revision tags: OPENBSD_3_0_BASE
# 1.50 10-Oct-2001 markus

branches: 1.50.2;
try to keep channels open until an exit-status message is sent.
don't kill the login shells if the shells stdin/out/err is closed.
this should now work:
ssh -2n localhost 'exec > /dev/null 2>&1; sleep 10; exit 5'; echo ?


# 1.49 09-Oct-2001 markus

simplify session close: no more delayed session_close, no more blocking wait() calls.


# 1.48 07-Oct-2001 markus

avoid possible FD_ISSET overflow for channels established
during channnel_after_select() (used for dynamic channels).


# 1.47 01-Oct-2001 markus

remove ugliness; vp@drexel.edu via angelos


# 1.46 17-Sep-2001 markus

try to fix agent-forwarding-backconnection-bug, as seen on HPUX, for example;
with Lutz.Jaenicke@aet.TU-Cottbus.DE,


# 1.45 17-Jul-2001 markus

keep track of both maxfd and the size of the malloc'ed fdsets.
update maxfd if maxfd gets closed.


# 1.44 02-Jul-2001 markus

improve cleanup/exit logic in ssh2:
stop listening to channels, detach channel users (e.g. sessions).
wait for children (i.e. dying sessions), send exit messages,
cleanup all channels.


# 1.43 30-Jun-2001 stevesk

adress -> address; ok markus@


# 1.42 26-Jun-2001 markus

remove comments from .h, since they are cut&paste from the .c files
and out of sync


# 1.41 26-Jun-2001 itojun

prototype pedant. not very creative...
- () -> (void)
- no variable names


# 1.40 25-Jun-2001 markus

update copyright for 2001


# 1.39 20-Jun-2001 markus

move from channel_stop_listening to channel_free_all,
call channel_free_all before calling waitpid() in serverloop.
fixes the utmp handling; report from Lutz.Jaenicke@aet.TU-Cottbus.DE


# 1.38 16-Jun-2001 markus

bad //-style comment; thx to stevev@darkwing.uoregon.edu


# 1.37 04-Jun-2001 markus

switch uid when cleaning up tmp files and sockets; reported by zen-parse@gmx.net on bugtraq


# 1.36 03-Jun-2001 markus

use fatal_register_cleanup instead of atexit, sync with x11 authdir handling


# 1.35 31-May-2001 markus

undo the .c file split, just merge the header and keep the cvs history


# 1.34 30-May-2001 markus

channel layer cleanup: merge header files and split .c files


# 1.33 28-May-2001 markus

undo broken channel fix and try a different one. there
should be still some select errors...


# 1.32 04-May-2001 markus

move to Channel **channels (instead of Channel *channels), fixes realloc problems.
channel_new now returns a Channel *, favour Channel * over channel id.
remove old channel_allocate interface.


Revision tags: OPENBSD_2_9_BASE
# 1.31 13-Apr-2001 beck

branches: 1.31.2;
Add options ClientAliveInterval and ClientAliveCountMax to sshd.
This gives the ability to do a "keepalive" via the encrypted channel
which can't be spoofed (unlike TCP keepalives). Useful for when you want
to use ssh connections to authenticate people for something, and know
relatively quickly when they are no longer authenticated. Disabled
by default (of course). ok markus@


# 1.30 07-Apr-2001 markus

allow the ssh client act as a SOCKS4 proxy (dynamic local portforwarding).
work by Dan Kaminsky <dankamin@cisco.com> and me. thanks to Dan for this
great patch: use 'ssh -D 1080 host' and make netscape use localhost:1080 as
a socks proxy.


# 1.29 04-Apr-2001 markus

more robust rekeying
don't send channel data after rekeying is started.


# 1.28 16-Mar-2001 markus

implement "permitopen" key option, restricts -L style forwarding to
to specified host:port pairs. based on work by harlan@genua.de


# 1.27 15-Feb-2001 markus

genericize password padding function for SSH1 and SSH2.
add stylized echo to 2, too.


# 1.26 31-Jan-2001 markus

do not disconnect if local port forwarding fails, e.g. if port is already in use


# 1.25 29-Jan-2001 markus

fix select overflow; ok deraadt@ and stevesk@


# 1.24 05-Dec-2000 markus

async connects for -R/-L; ok deraadt@


# 1.23 06-Nov-2000 markus

agent forwarding and -R for ssh2, based on work from jhuuskon@messi.uku.fi


Revision tags: OPENBSD_2_8_BASE
# 1.22 27-Oct-2000 markus

branches: 1.22.2;
deny agent/x11 forwarding unless requested; thanks to jwl@pobox.com


# 1.21 27-Oct-2000 markus

enable non-blocking IO on channels, and tty's (except for the client ttys).


# 1.20 21-Sep-2000 markus

add context to dispatch_run


# 1.19 07-Sep-2000 markus

some more Copyright fixes


# 1.18 07-Sep-2000 markus

cleanup window and packet sizes for ssh2 flow control; ok niels


# 1.17 07-Sep-2000 deraadt

cleanup copyright notices on all files. I have attempted to be accurate with
the details. everything is now under Tatu's licence (which I copied from his
readme), and/or the core-sdi bsd-ish thing for deattack, or various openbsd
developers under a 2-term bsd licence. We're not changing any rules, just
being accurate.


# 1.16 19-Aug-2000 markus

more ~ support for ssh2


# 1.15 19-Aug-2000 markus

support for ~. in ssh2


# 1.14 20-Jun-2000 markus

OpenBSD tag


# 1.13 30-May-2000 markus

don't panic if mkdtemp fails for authfwd; jkb@yahoo-inc.com via kris@FreeBSD.org


Revision tags: OPENBSD_2_7_BASE
# 1.12 03-May-2000 markus

branches: 1.12.2;
GatewayPorts for sshd, ok deraadt@


# 1.11 02-May-2000 markus

use c-style comments


# 1.10 28-Apr-2000 markus

support for x11-fwding, client+server


# 1.9 14-Apr-2000 markus

whitespace cleanup


# 1.8 03-Apr-2000 markus

channel layer support for ssh2


# 1.7 28-Mar-2000 markus

replace big switch() with function tables (prepare for ssh2)


# 1.6 24-Nov-1999 markus

KNF, final part 3


# 1.5 24-Nov-1999 deraadt

much more KNF


# 1.4 28-Oct-1999 markus

remove broken x11 fix and document istate/ostate


Revision tags: OPENBSD_2_6_BASE
# 1.3 17-Oct-1999 markus

re-implement the proto-1.5 channel close protocol, see nchan.ms.


# 1.2 16-Oct-1999 markus

add CVS tags, fix comments and whitespace


# 1.1 16-Oct-1999 markus

support for SSH protocol 1.5 which is poorly documented, the RFC.troff lies.
interops (x11,agent,etc) with 1.2.27 and protocol 1.3