History log of /openbsd-current/usr.bin/ssh/mux.c
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.101 23-Nov-2023 dtucker

Include existing mux path in debug message.


Revision tags: OPENBSD_7_4_BASE
# 1.100 18-Aug-2023 djm

fix regression in OpenSSH 9.4 (mux.c r1.99) that caused multiplexed
sessions to ignore SIGINT under some circumstances. Reported by /
feedback naddy@, ok dtucker@


# 1.99 04-Aug-2023 dtucker

Apply ConnectTimeout to multiplexing local socket connections. If the
multiplex socket exists but the connection times out, ssh will fall back
to a direct connection the same way it would if the socket did not exist
at all. ok djm@


# 1.98 26-Jul-2023 djm

make ssh -f (fork after authentication) work properly in multiplexed
cases (inc. ControlPersist). bz3589 bz3589
Based on patches by Peter Chubb; ok dtucker@


# 1.97 20-Jun-2023 djm

prepare for support for connecting to unix domain sockets using ssh -W
by explicitly decoding PORT_STREAMLOCAL (a negative number) from the u32
that's passed over the multiplexing socket; previously code would just
cast, which is UB.


Revision tags: OPENBSD_7_3_BASE
# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.100 18-Aug-2023 djm

fix regression in OpenSSH 9.4 (mux.c r1.99) that caused multiplexed
sessions to ignore SIGINT under some circumstances. Reported by /
feedback naddy@, ok dtucker@


# 1.99 04-Aug-2023 dtucker

Apply ConnectTimeout to multiplexing local socket connections. If the
multiplex socket exists but the connection times out, ssh will fall back
to a direct connection the same way it would if the socket did not exist
at all. ok djm@


# 1.98 26-Jul-2023 djm

make ssh -f (fork after authentication) work properly in multiplexed
cases (inc. ControlPersist). bz3589 bz3589
Based on patches by Peter Chubb; ok dtucker@


# 1.97 20-Jun-2023 djm

prepare for support for connecting to unix domain sockets using ssh -W
by explicitly decoding PORT_STREAMLOCAL (a negative number) from the u32
that's passed over the multiplexing socket; previously code would just
cast, which is UB.


Revision tags: OPENBSD_7_3_BASE
# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.99 04-Aug-2023 dtucker

Apply ConnectTimeout to multiplexing local socket connections. If the
multiplex socket exists but the connection times out, ssh will fall back
to a direct connection the same way it would if the socket did not exist
at all. ok djm@


# 1.98 26-Jul-2023 djm

make ssh -f (fork after authentication) work properly in multiplexed
cases (inc. ControlPersist). bz3589 bz3589
Based on patches by Peter Chubb; ok dtucker@


# 1.97 20-Jun-2023 djm

prepare for support for connecting to unix domain sockets using ssh -W
by explicitly decoding PORT_STREAMLOCAL (a negative number) from the u32
that's passed over the multiplexing socket; previously code would just
cast, which is UB.


Revision tags: OPENBSD_7_3_BASE
# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.98 26-Jul-2023 djm

make ssh -f (fork after authentication) work properly in multiplexed
cases (inc. ControlPersist). bz3589 bz3589
Based on patches by Peter Chubb; ok dtucker@


# 1.97 20-Jun-2023 djm

prepare for support for connecting to unix domain sockets using ssh -W
by explicitly decoding PORT_STREAMLOCAL (a negative number) from the u32
that's passed over the multiplexing socket; previously code would just
cast, which is UB.


Revision tags: OPENBSD_7_3_BASE
# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.97 20-Jun-2023 djm

prepare for support for connecting to unix domain sockets using ssh -W
by explicitly decoding PORT_STREAMLOCAL (a negative number) from the u32
that's passed over the multiplexing socket; previously code would just
cast, which is UB.


Revision tags: OPENBSD_7_3_BASE
# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.96 08-Mar-2023 guenther

Delete obsolete /* ARGSUSED */ lint comments.

ok miod@ millert@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.95 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


Revision tags: OPENBSD_7_2_BASE
# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.94 03-Jun-2022 djm

Make SetEnv directives first-match-wins in both sshd_config and
sshd_config; previously if the same name was reused then the last
would win (which is the opposite to how the config is supposed to
work).

While there, make the ssh_config parsing more like sshd_config.

bz3438, ok dtucker


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.93 05-May-2022 djm

mux.c: mark argument as const; from Martin Vahlensieck


Revision tags: OPENBSD_7_1_BASE
# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.92 11-Jan-2022 djm

suppress "Connection to xxx closed" messages at LogLevel >= error
bz3378; ok dtucker@


Revision tags: OPENBSD_7_0_BASE
# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.91 23-Jul-2021 djm

Add a StdinNull directive to ssh_config(5) that allows the config
file to do the same thing as -n does on the ssh(1) commandline.
Patch from Volker Diels-Grabsch via GHPR231; ok dtucker


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.90 13-Jul-2021 djm

add a SessionType directive to ssh_config, allowing the configuration
file to offer equivalent control to the -N (no session) and -s
(subsystem) command-line flags.

Part of GHPR#231 by Volker Diels-Grabsch with some minor tweaks;
feedback and ok dtucker@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.89 04-Jun-2021 djm

allow ssh_config SetEnv to override $TERM, which is otherwise handled
specially by the protocol. Useful in ~/.ssh/config to set TERM to
something generic (e.g. "xterm" instead of "xterm-256color") for
destinations that lack terminfo entries. feedback and ok dtucker@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.88 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.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.87 03-Apr-2021 djm

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


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.86 29-Oct-2020 djm

whitespace; no code change


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.85 18-Oct-2020 djm

use the new variant log macros instead of prepending __func__ and
appending ssh_err(r) manually; ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.84 03-Oct-2020 djm

There are lots of place where we want to redirect stdin, stdout
and/or stderr to /dev/null. Factor all these out to a single
stdfd_devnull() function that allows selection of which of these
to redirect. ok markus@


Revision tags: OPENBSD_6_8_BASE
# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.83 05-Jul-2020 djm

some language improvements; ok markus


Revision tags: OPENBSD_6_7_BASE
# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.82 30-Apr-2020 markus

bring back debug() removed in rev 1.74; noted by pradeep kumar


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.81 23-Jan-2020 dtucker

Replace all calls to signal(2) with a wrapper around sigaction(2).
This wrapper blocks all other signals during the handler preventing
races between handlers, and sets SA_RESTART which should reduce the
potential for short read/write operations.


Revision tags: OPENBSD_6_6_BASE
# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.80 28-Jun-2019 deraadt

When system calls indicate an error they return -1, not some arbitrary
value < 0. errno is only updated in this case. Change all (most?)
callers of syscalls to follow this better, and let's see if this strictness
helps us in the future.


Revision tags: OPENBSD_6_5_BASE
# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.79 19-Jan-2019 djm

convert mux.c to new packet API

with & ok markus@


# 1.78 19-Jan-2019 djm

begin landing remaining refactoring of packet parsing API, started
almost exactly six years ago.

This change stops including the old packet_* API by default and makes
each file that requires the old API include it explicitly. We will
commit file-by-file refactoring to remove the old API in consistent
steps.

with & ok markus@


Revision tags: OPENBSD_6_4_BASE
# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.77 26-Sep-2018 djm

remove big ugly TODO comment from start of file. Some of the mentioned
tasks are obsolete and, of the remainder, most are already captured in
PROTOCOL.mux where they better belong


# 1.76 26-Sep-2018 djm

s/process_mux_master/mux_master_process/ in mux master function names,

Gives better symmetry with the existing mux_client_*() names and makes
it more obvious when a message comes from the master vs client (they
are interleved in ControlMaster=auto mode).

no functional change beyond prefixing a could of log messages with
__func__ where they were previously lacking.


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.75 31-Jul-2018 djm

fix some memory leaks spotted by Coverity via Jakub Jelen in bz#2366
feedback and ok dtucker@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.74 11-Jul-2018 markus

remove legacy key emulation layer; ok djm@


# 1.73 09-Jul-2018 markus

client: switch mux to sshbuf API; with & ok djm@


# 1.72 09-Jul-2018 markus

client: switch to sshbuf API; ok djm@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


# 1.71 09-Jun-2018 djm

add a SetEnv directive to ssh_config that allows setting environment
variables for the remote session (subject to the server accepting them)

refactor SendEnv to remove the arbitrary limit of variable names.

ok markus@


# 1.70 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.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@


Revision tags: OPENBSD_6_2_BASE
# 1.69 20-Sep-2017 dtucker

Use strsignal in debug message instead of casting for the benefit of
portable where sig_atomic_t might not be int. "much nicer" deraadt@


# 1.68 18-Sep-2017 dtucker

Prevent type mismatch warning in debug on platforms where sig_atomic_t
!= int. ok djm@


# 1.67 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.66 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.65 09-Jun-2017 djm

return failure rather than fatal() for more cases during mux
negotiations. Causes the session to fall back to a non-mux connection
if they occur. bz#2707 ok dtucker@


Revision tags: OPENBSD_6_1_BASE
# 1.64 21-Jan-2017 guenther

The POSIX APIs that that sockaddrs all ignore the s*_len field in the
incoming socket, so userspace doesn't need to set it unless it has its
own reasons for tracking the size along with the sockaddr.

ok phessler@ deraadt@ florian@


# 1.63 19-Oct-2016 dtucker

When tearing down ControlMaster connecctions, don't pollute stderr when
LogLevel=quiet. Patch from Tim Kuijsten via tech@.


# 1.62 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@


# 1.61 08-Aug-2016 dtucker

Improve error message for overlong ControlPath. ok markus@ djm@


Revision tags: OPENBSD_6_0_BASE
# 1.60 03-Jun-2016 dtucker

Move the host and port used by ssh -W into the Options struct.
This will make future changes a bit easier. ok djm@


# 1.59 01-Apr-2016 djm

whitespace at EOL


Revision tags: OPENBSD_5_9_BASE
# 1.58 13-Jan-2016 djm

eliminate fallback from untrusted X11 forwarding to trusted
forwarding when the X server disables the SECURITY extension;
Reported by Thomas Hoger; ok deraadt@


# 1.57 26-Dec-2015 semarie

adjust pledge promises for ControlMaster: when using "ask" or "autoask", the process will use ssh-askpass for asking confirmation.

problem found by halex@

ok halex@


# 1.56 03-Dec-2015 semarie

pledges ssh client:
- mux client: which is used when ControlMaster is in use.
will end with "stdio proc tty" (proc is to permit sending SIGWINCH to mux master on window resize)

- client loop: several levels of pledging depending of your used options

ok deraadt@


# 1.55 15-Oct-2015 djm

fix some signed/unsigned integer type mismatches in format
strings; reported by Nicholas Lemonias


# 1.54 19-Aug-2015 djm

fix free() of uninitialised pointer reported by Mateusz Kocielski;
ok markus@


Revision tags: OPENBSD_5_8_BASE
# 1.53 01-May-2015 djm

branches: 1.53.2;
remove failed remote forwards established by muliplexing from the
list of active forwards; bz#2363, patch mostly by Yoann Ricordel;
ok dtucker@


# 1.52 01-May-2015 djm

reduce stderr spam when using ssh -S /path/mux -O forward -R 0:...
ok dtucker@


# 1.51 24-Apr-2015 deraadt

rename xrealloc() to xreallocarray() since it follows that form.
ok djm


Revision tags: OPENBSD_5_7_BASE
# 1.50 20-Jan-2015 deraadt

branches: 1.50.2;
Reduce use of <sys/param.h> and transition to <limits.h> throughout.
ok djm markus


# 1.49 22-Dec-2014 djm

fix passing of wildcard forward bind addresses when connection
multiplexing is in use; patch from Sami Hartikainen via bz#2324;
ok dtucker@


Revision tags: OPENBSD_5_6_BASE
# 1.48 17-Jul-2014 djm

reflect stdio-forward ("ssh -W host:port ...") failures in exit status.
previously we were always returning 0. bz#2255 reported by Brendan
Germain; ok dtucker


# 1.47 17-Jul-2014 djm

preserve errno across syscall


# 1.46 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.45 28-Apr-2014 djm

buffer_get_string_ptr's return should be const to remind
callers that futzing with it will futz with the actual buffer
contents


Revision tags: OPENBSD_5_4_BASE OPENBSD_5_5_BASE
# 1.44 12-Jul-2013 djm

fix pointer-signedness warnings from clang/llvm-3.3; "seems nice" deraadt@


# 1.43 05-Jun-2013 dtucker

fix leaks in mux error paths, from Zhenbo Xu, found by Melton. bz#1967, ok djm


# 1.42 02-Jun-2013 dtucker

No need for the mux cleanup callback to be visible so restore it to static
and call it through the detach_user function pointer. ok djm@


# 1.41 17-May-2013 djm

bye, bye xfree(); ok markus@


# 1.40 22-Apr-2013 dtucker

typo in debug output: evitval->exitval


# 1.39 05-Apr-2013 djm

cleanup mux-created channels that are in SSH_CHANNEL_OPENING state too
(in addition to ones already in OPEN); bz#2079, ok dtucker@


Revision tags: OPENBSD_5_3_BASE
# 1.38 02-Jan-2013 djm

channel_setup_local_fwd_listener() returns 0 on failure, not -ve
bz#2055 reported by mathieu.lacage AT gmail.com


# 1.37 17-Aug-2012 dtucker

Force a clean shutdown of ControlMaster client sessions when the ~. escape
sequence is used. This means that ~. should now work in mux clients even
if the server is no longer responding. Found by tedu, ok djm.


Revision tags: OPENBSD_5_2_BASE
# 1.36 06-Jul-2012 djm

fix memory leak of passed-in environment variables and connection
context when new session message is malformed; bz#2003 from Bert.Wesarg
AT googlemail.com


# 1.35 01-Jun-2012 djm

fix memory leak when mux socket creation fails; bz#2002 from bert.wesarg
AT googlemail.com


Revision tags: OPENBSD_5_1_BASE
# 1.34 07-Jan-2012 djm

fix double-free in new session handler


# 1.33 04-Dec-2011 djm

revert:

> revision 1.32
> date: 2011/12/02 00:41:56; author: djm; state: Exp; lines: +4 -1
> fix bz#1948: ssh -f doesn't fork for multiplexed connection.
> ok dtucker@

it interacts badly with ControlPersist


# 1.32 02-Dec-2011 djm

fix bz#1948: ssh -f doesn't fork for multiplexed connection.
ok dtucker@


# 1.31 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.30 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.29 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@


# 1.28 08-May-2011 djm

improve our behaviour when TTY allocation fails: if we are in
RequestTTY=auto mode (the default), then do not treat at TTY
allocation error as fatal but rather just restore the local TTY
to cooked mode and continue. This is more graceful on devices that
never allocate TTYs.

If RequestTTY is set to "yes" or "force", then failure to allocate
a TTY is fatal.

ok markus@


# 1.27 06-May-2011 djm

Add a RequestTTY ssh_config option to allow configuration-based
control over tty allocation (like -t/-T); ok markus@


# 1.26 05-May-2011 djm

gracefully fall back when ControlPath is too large for a
sockaddr_un. ok markus@ as part of a larger diff


# 1.25 17-Apr-2011 djm

allow graceful shutdown of multiplexing: request that a mux server removes
its listener socket and refuse future multiplexing requests; ok markus@


Revision tags: OPENBSD_4_9_BASE
# 1.24 13-Jan-2011 djm

correct error messages; patch from bert.wesarg AT googlemail.com


# 1.23 12-Oct-2010 dtucker

Typo in confirmation message. bz#1827, patch from imorgan at nas nasa gov


# 1.22 20-Sep-2010 djm

"atomically" create the listening mux socket by binding it on a temorary
name and then linking it into position after listen() has succeeded.

this allows the mux clients to determine that the server socket is
either ready or stale without races. stale server sockets are now
automatically removed

ok deraadt


Revision tags: OPENBSD_4_8_BASE
# 1.21 25-Jun-2010 djm

Add X11ForwardTimeout option to specify timeout for untrusted X11
authentication cookies to avoid fallback in X11 code to fully-trusted
implicit authentication using SO_PEERCRED described at:
http://lists.x.org/archives/xorg-devel/2010-May/008636.html

After the X11ForwardTimeout has expired the client will now refuse
incoming X11 channel opens.

based on patch from Tavis Ormandy; "nice" markus@


# 1.20 25-Jun-2010 djm

bz#1327: remove hardcoded limit of 100 permitopen clauses and port
forwards per direction; ok markus@ stevesk@


# 1.19 17-Jun-2010 djm

Correct sizing of object to be allocated by calloc(), replacing
sizeof(state) with sizeof(*state). This worked by accident since
the struct contained a single int at present, but could have broken
in the future. patch from hyc AT symas.com


# 1.18 16-May-2010 markus

mux support for remote forwarding with dynamic port allocation,
use with
LPORT=`ssh -S muxsocket -R0:localhost:25 -O forward somehost`
feedback and ok djm@


# 1.17 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@


# 1.16 23-Apr-2010 djm

set "detach_close" flag when registering channel cleanup callbacks.
This causes the channel to close normally when its fds close and
hangs when terminating a mux slave using ~. bz#1758; ok markus@


# 1.15 10-Apr-2010 djm

fix NULL dereference; from matthew.haub AT alumni.adelaide.edu.au


Revision tags: OPENBSD_4_7_BASE
# 1.14 30-Jan-2010 djm

don't mark channel as read failed if it is already closing; suppresses
harmless error messages when connecting to SSH.COM Tectia server
report by imorgan AT nas.nasa.gov


# 1.13 29-Jan-2010 djm

kill correct channel (was killing already-dead mux channel, not
its session channel)


# 1.12 27-Jan-2010 djm

fix bug introduced in mux rewrite:

In a mux master, when a socket to a mux slave closes before its server
session (as may occur when the slave has been signalled), gracefully
close the server session rather than deleting its channel immediately.
A server may have more messages on that channel to send (e.g. an exit
message) that will fatal() the client if they are sent to a channel that
has been prematurely deleted.

spotted by imorgan AT nas.nasa.gov


# 1.11 26-Jan-2010 djm

-Wuninitialized and remove a // comment; from portable


# 1.10 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.9 09-Jan-2010 djm

quell tc[gs]etattr warnings when forcing a tty (ssh -tt), since we
usually don't actually have a tty to read/set; bz#1686 ok dtucker@


# 1.8 20-Aug-2009 dtucker

subsystem_flag is defined in ssh.c so it's extern; ok djm


Revision tags: OPENBSD_4_4_BASE OPENBSD_4_5_BASE OPENBSD_4_6_BASE
# 1.7 13-Jun-2008 dtucker

Friendlier error messages for mux fallback. ok djm@


# 1.6 13-Jun-2008 dtucker

upcast size_t to u_long to match format arg; ok djm@


# 1.5 13-Jun-2008 djm

fall back to creating a new TCP connection on most multiplexing errors
(socket connect fail, invalid version, refused permittion, corrupted
messages, etc.); bz #1329 ok dtucker@


# 1.4 12-Jun-2008 djm

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


# 1.3 12-Jun-2008 djm

some more TODO for me


# 1.2 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.1 09-May-2008 djm

tidy up session multiplexing code, moving it into its own file and
making the function names more consistent - making ssh.c and
clientloop.c a fair bit more readable.

ok markus@