Skip to content

Key-exchange timeout over session channels, but not sftp #822

Open

Description

@mathrick

We're running into the key-exchange timeout exception when talking to OpenSSH, but it only happens when using a "session" channel. SFTP transfers proceed just fine, and we see successful key exchange in the logs.

This gist demonstrates the issue:

$ ssh quicksilver "base64 /dev/urandom | head -c 200000 > /tmp/file.txt"
$ python test_paramiko.py quicksilver -u mkatafiasz /tmp/file.txt --sftp
REKEY_BYTES: 102400
REKEY_PACKETS: 536870912
Using SFTPClient, which should succeed in rekeying
Read file 1 times
Read file 2 times
Read file 3 times
Read file 4 times
Read file 5 times
^C
KeyboardInterrupt

$ python test_paramiko.py quicksilver -u mkatafiasz /tmp/file.txt
REKEY_BYTES: 102400
REKEY_PACKETS: 536870912
Using SSHClient, which should fail in rekeying
Need rekey
Read file 1 times
Read file 2 times
Traceback (most recent call last):
No handlers could be found for logger "paramiko.transport"
  File "test_paramiko.py", line 45, in <module>
    for line in stdout:
  File "/usr/lib/python2.7/dist-packages/paramiko/file.py", line 106, in next
    line = self.readline()
  File "/usr/lib/python2.7/dist-packages/paramiko/file.py", line 214, in readline
    new_data = self._read(n)
  File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 1253, in _read
    return self.channel.recv(size)
  File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 628, in recv
    self.transport._send_user_message(m)
  File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1442, in _send_user_message
    raise SSHException('Key-exchange timed out waiting for key negotiation')
paramiko.SSHException: Key-exchange timed out waiting for key negotiation

The remote side is running OpenSSH (tried with 6.6 and 6.7), and setting LogLevel DEBUG yields the following output:

  • SFTP (successfully rekeys)
Sep 27 17:48:42 myhost sshd[20158]: debug1: SSH2_MSG_KEXINIT received
Sep 27 17:48:42 myhost sshd[20158]: debug1: SSH2_MSG_KEXINIT sent
Sep 27 17:48:42 myhost sshd[20158]: debug1: kex: client->server aes128-ctr hmac-sha2-256 none
Sep 27 17:48:42 myhost sshd[20158]: debug1: kex: server->client aes128-ctr hmac-sha2-256 none
Sep 27 17:48:42 myhost sshd[20158]: debug1: expecting SSH2_MSG_KEXDH_INIT
Sep 27 17:48:42 myhost sshd[20158]: debug1: set_newkeys: rekeying
Sep 27 17:48:42 myhost sshd[20158]: debug1: SSH2_MSG_NEWKEYS sent
Sep 27 17:48:42 myhost sshd[20158]: debug1: expecting SSH2_MSG_NEWKEYS
Sep 27 17:48:42 myhost sshd[20158]: debug1: set_newkeys: rekeying
Sep 27 17:48:42 myhost sshd[20158]: debug1: SSH2_MSG_NEWKEYS received
  • SSH session (fails)
Sep 27 17:44:14 myhost sshd[19591]: debug1: SSH2_MSG_KEXINIT received
Sep 27 17:44:14 myhost sshd[19591]: debug1: SSH2_MSG_KEXINIT sent
Sep 27 17:44:14 myhost sshd[19591]: debug1: kex: client->server aes128-ctr hmac-sha2-256 none
Sep 27 17:44:14 myhost sshd[19591]: debug1: kex: server->client aes128-ctr hmac-sha2-256 none
Sep 27 17:44:14 myhost sshd[19591]: debug1: expecting SSH2_MSG_KEXDH_INIT
Sep 27 17:44:44 myhost sshd[19591]: fatal: Read from socket failed: Connection reset by peer

Given these logs, the issue makes me think of one I believe was fixed earlier, related to OpenSSH server not liking intervening traffic after a rekey request was sent, though I can't find the issue number right now.

Activity

  1. tsellers-r7 commented on Oct 24, 2016

    @tsellers-r7

    I've seen this bug as well, pretty consistently. I've verified that the code that @mathrick reliably reproduces the issue when run from a Mac OS machine communicating with Ubuntu 16.04.01.

    Relevant information:
    Client:
    Python 2.7.12
    paramiko 2.0.2
    cryptography 1.5
    pyasn1 0.1.9
    pyOpenSSL==16.1.0

    Server:
    sshd = OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
    OpenSSL 1.0.2g 1 Mar 2016

    I've also seen it when the client is running Ubuntu 14.04, Python 2.7.6, paramiko 1.17.2. We originally saw it in paramiko 1.15.x.

  2. tsellers-r7 commented on Oct 24, 2016

    @tsellers-r7

    FYI @bitprophet
    I think that this is caused by a situation that occurs when a channel close for channel 0 is sent from the server after the key exchange process has started. The code can't send the final EOF and close the channel because its blocked waiting on the key exchange process to finish.

    Sequence of events:

    The key exchange process (transport.._send_kex_init()) is triggered due to self.packetizer.need_rekey being true.

    Transport._send_kex_init clears the clear_to_send flag, preventing traffic

    The loop reads messages from the server

    Before the MSG_KEXINIT message is sent from the server, a MSG_CHANNEL_CLOSE (type 97 ) message is sent, which is handled by the _channel_handler_table

    The above calls channel._handle_close

    channel._handle_close generates an EOF message and attempts to send it to the server via transport._send_user_message

    Transport._send_user_message loops while waiting on, among other things, the clear_to_send flag.

    Since the server has closed the channel, it will never finish the key exchange / negotiations and so the transport.run loop will continue until _send_user_message times out and returns Key-exchange timed out waiting for key negotiation

  3. tsellers-r7 commented on Oct 25, 2016

    @tsellers-r7

    FYI, while testing this I was saw that the server (in debug mode sudo /usr/sbin/sshd -p22 -D -d -e) saw the client's SSH_MSG_KEXINIT, sent a SSH2_MSG_KEXINIT response, and was waiting on SSH2_MSG_KEXDH_INIT. I had the client code printing the message codes for the message that it saw from the server and it never printed the server response despite doing so in other iterations of the loop where the KEX worked properly.

  4. added this to the milestone on Oct 25, 2016
  5. bitprophet commented on Dec 6, 2016

    @bitprophet
    Member

    (moved from the PR to keep discussion in the milestone'd ticket...)

    First, thanks @tsellers-r7 for the detailed descriptions & PR, greatly appreciated!

    I can trivially (as in, 2nd time every time) repro with the info from #822 (once I decided to read very carefully and not skip the part where you generate the dummy data file...sigh...there's no problem or exception if you don't!)

    Unfortunately, with this patch in place, the error simply transmutes into the following:

    Using SSHClient, which should fail in rekeying
    DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
    DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
    DEBUG:paramiko.transport:Secsh channel 0 opened.
    DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
    DEBUG:paramiko.transport:Rekeying (hit 19 packets, 115888 bytes received)
    Need rekey
    DEBUG:paramiko.transport:[chan 0] EOF received (0)
    Read file 1 times
    DEBUG:paramiko.transport:[chan 0] EOF sent (0)
    DEBUG:paramiko.transport:kex algos:[u'[email protected]', u'ecdh-sha2-nistp521', u'ecdh-sha2-nistp384', u'ecdh-sha2-nistp256', u'diffie-hellman
    -group-exchange-sha256'] server key:[u'ssh-ed25519', u'ssh-rsa', u'ecdsa-sha2-nistp256'] client encrypt:[u'[email protected]', u'aes256-gcm@op
    enssh.com', u'[email protected]', u'aes256-ctr', u'aes192-ctr', u'aes128-ctr'] server encrypt:[u'[email protected]', u'aes256-gcm@openssh
    .com', u'[email protected]', u'aes256-ctr', u'aes192-ctr', u'aes128-ctr'] client mac:[u'[email protected]', u'[email protected]
    om', u'[email protected]', u'hmac-sha2-512', u'hmac-sha2-256', u'[email protected]'] server mac:[u'[email protected]', u'hmac-sha2-2
    [email protected]', u'[email protected]', u'hmac-sha2-512', u'hmac-sha2-256', u'[email protected]'] client compress:[u'none', u'[email protected]
    m'] server compress:[u'none', u'[email protected]'] client lang:[u''] server lang:[u''] kex follows?False
    DEBUG:paramiko.transport:Kex agreed: diffie-hellman-group-exchange-sha256
    DEBUG:paramiko.transport:Cipher agreed: aes128-ctr
    DEBUG:paramiko.transport:MAC agreed: hmac-sha2-256
    DEBUG:paramiko.transport:Compression agreed: none
    DEBUG:paramiko.transport:EOF in transport thread
    Traceback (most recent call last):
      File "wut.py", line 41, in <module>
        stdin, stdout, stderr = client.exec_command('cat {}'.format(DATAFILE))
      File "/Users/jforcier/Code/oss/paramiko/paramiko/client.py", line 420, in exec_command
        chan = self._transport.open_session(timeout=timeout)
      File "/Users/jforcier/Code/oss/paramiko/paramiko/transport.py", line 705, in open_session
        timeout=timeout)
      File "/Users/jforcier/Code/oss/paramiko/paramiko/transport.py", line 789, in open_channel
        raise SSHException('SSH session not active')
    paramiko.ssh_exception.SSHException: SSH session not active
    

    Very occasionally, it croaks on the 3rd connection (i.e. 2 successes are printed), but most of the time, it's on the 2nd.

    OS X 10.11 client (running Paramiko 1.17 w/ this patch on top; also tested master, no difference) and a Debian (OpenSSH 6.7) server.

    I don't have time right now to do my own analysis of why it's not looping for ages as it was for you (trying to just get a lot of low hanging fruit tickets out the door so I'm blocking fewer users) but happy to continue a dialogue / try permutations locally / etc.

    The first thing I'd probably do is see if this is somehow due to the other tickets I merged since this ticket was created, though the only one that seemed obvious (timeout-related) only kicks in after that SSHException is raised - something else is setting the transport inactive first.

  6. modified the milestones: 1.17.3 et al, on Dec 9, 2016
  7. source-ram commented on Aug 31, 2017

    @source-ram

    Any one with the fix ?

  8. acechef commented on Aug 21, 2018

    @acechef

    Is it fixed?

  9. sashas-lb commented on Nov 12, 2018

    @sashas-lb

    We are expiriencing same issue, easily reproducable with the following script:

    import paramiko
    import subprocess
    import logging
    import sys
    
    def configure_logging(use_color=True, level=logging.INFO):
        logger = logging.getLogger()
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(level)
        logger.addHandler(ch)
        return logger
    def _read_output(stdout, output_timeout):
        output_array = []
        try:
            while True:
                segment = stdout.read().decode('utf-8')
                if segment == "":
                    break
                output_array.append(segment)
        except socket.timeout:
            output = "".join(output_array)
            e = socket.timeout(
                "Timeout executing, no input for timeout of '%s'. Partial output was\n:%s" % (
                    output_timeout, output))
            e.output = output
            raise e
        return "".join(output_array)
    
    def execute(ssh_client, command, output_timeout=20 * 60):
        transport = ssh_client.get_transport()
        chan = transport.open_session()
        try:
            chan.exec_command(command)
            chan.settimeout(output_timeout)
            stdin = chan.makefile('wb', -1)
            stdout = chan.makefile('rb', -1)
            stderr = chan.makefile_stderr('rb', -1)
            stdin.close()
            output = _read_output(stdout, output_timeout)
            status = chan.recv_exit_status()
            error = stderr.read().decode('utf-8')
            completed_process = subprocess.CompletedProcess(command, status)
            completed_process.stderr = error
            completed_process.stdout = output
            stdout.close()
            stderr.close()
            if status != 0:
                raise Exception()
            return completed_process
        finally:
            chan.close()
    
    configure_logging(level=logging.DEBUG)
    logging.getLogger('paramiko').setLevel(logging.DEBUG)
    
    client = paramiko.SSHClient()
    client.known_hosts = None
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname="<ip address>", port=22, username="root", password="root",
            look_for_keys=False, allow_agent=False)
    
    trans = client.get_transport() 
    # Note this is set to 1024 to cause key exchange after every message 
    trans.packetizer.REKEY_BYTES = 1024
    bla = execute(client, "head -c 1024 /dev/zero")
    
    while True:
        bla = execute(client, "head -c 1024 /dev/zero")

    paramiko version: paramiko (2.4.2)
    openssh version: OpenSSH_7.2p2 Ubuntu-4ubuntu2.6, OpenSSL 1.0.2g 1 Mar 2016

  10. agraubert commented on Nov 22, 2019

    @agraubert

    Are there any updates? This is still occurring in 2.6.0

  11. piskvorky commented on Jan 26, 2020

    @piskvorky

    Also bitten by this. paramiko==2.6.0

  12. theburge commented on Mar 4, 2020

    @theburge

    I've also run into this bug consistently, and agree with the analysis about by @tsellers-r7: handling a remote channel close during re-keying (when clear_to_send is unset) is the initiator for the problem, causing the Transport thread to self-livelock in _send_user_message (called by Channel._handle_close(), in turn called from the Transport.run() loop in response to the server's channel close).

    The following notes are from my analysis, and only added in case they're helpful in analysing and solving the bug. :) I'm sorry that I don't have time to work any of this into actual code right now (but perhaps in the next little while).


    So the Transport.run() loop is unable to complete the rekeying conversation, because it's trying to send its responses to the channel close (that was received just after it decided to rekey). Instead, Channel._handle_close() blocks Transport.run()'s message pump: it's awaiting Transport().clear_to_send becoming unset , but only allow Transport.run() to pump additional messages could do that!

    For reference, debug logs from Paramiko (as well as the top-level error logs from my application) demonstrating that the remote EOF occurs just after the re-keying begins. This turned out to be the key to reproducing it reliably (once I was convinced of that, I just binary chopped the value of paramiko.packet.Packetizer.REKEY_BYTES until it made the problem occur):

    2020-02-28 16:37:04,538: [DEBUG] [chan 39] Max packet in: 32768 bytes
    2020-02-28 16:37:04,540: [DEBUG] [chan 39] Max packet out: 32768 bytes
    2020-02-28 16:37:04,540: [DEBUG] Secsh channel 39 opened.
    2020-02-28 16:37:04,544: [DEBUG] [chan 39] Sesch channel 39 request ok
    2020-02-28 16:37:04,544: [DEBUG] [chan 39] EOF sent (39)
    2020-02-28 16:37:06,744: [DEBUG] Rekeying (hit 32501 packets, 536871296 bytes received)
    2020-02-28 16:37:06,755: [DEBUG] [chan 39] EOF received (39)
    2020-02-28 16:37:36,819: [ERROR] Exception: Key-exchange timed out waiting for key negotiation
    2020-02-28 16:37:36,819: [ERROR] Traceback (most recent call last):
    2020-02-28 16:37:36,819: [ERROR]   File "/opt/rebal2-cli/venv_1.2.0_2.7.15/lib/python2.7/site-packages/paramiko/transport.py", line 1769, in run
    2020-02-28 16:37:36,820: [ERROR]     self._channel_handler_table[ptype](chan, m)
    2020-02-28 16:37:36,820: [ERROR]   File "/opt/rebal2-cli/venv_1.2.0_2.7.15/lib/python2.7/site-packages/paramiko/channel.py", line 1123, in _handle_close
    2020-02-28 16:37:36,820: [ERROR]     self.transport._send_user_message(m)
    2020-02-28 16:37:36,820: [ERROR]   File "/opt/rebal2-cli/venv_1.2.0_2.7.15/lib/python2.7/site-packages/paramiko/transport.py", line 1599, in _send_user_message
    2020-02-28 16:37:36,820: [ERROR]     raise SSHException('Key-exchange timed out waiting for key negotiation')
    2020-02-28 16:37:36,820: [ERROR] SSHException: Key-exchange timed out waiting for key negotiation
    2020-02-28 16:37:36,820: [ERROR]
    

    (And as in the original report, my OpenSSH server gets as far as debug1: expecting SSH2_MSG_KEXDH_INIT -- so it has sent its SSH_MSG_KEXINIT -- and then 30s later -- i.e., after the clear_to_send_timeout expires -- sshd notes its peer reset the connection.)

    I also added a little bit of descriptive logging in Channel._handle_close to demonstrate the problem:

        def _handle_close(self, m):
            self.lock.acquire()
            try:
                msgs = self._close_internal()
                self.transport._unlink_channel(self.chanid)
            finally:
                self.lock.release()
            self._log(DEBUG, 'close received (%s); transport unlinked', self._name)
            for m in msgs:
                if m is not None:
                    self.transport._send_user_message(m)
            self._log(DEBUG, 'close received (%s); messages sent', self._name)
    

    and here's the output in a reproducer case:

    2020-03-04 10:36:48,301: [DEBUG] Rekeying (hit 1195 packets, 37760976 bytes received)
    2020-03-04 10:36:48,309: [DEBUG] [chan 3] EOF received (3)
    2020-03-04 10:36:48,310: [DEBUG] [chan 3] close received (3); transport unlinked
    2020-03-04 10:37:18,321: [ERROR] Exception: Key-exchange timed out waiting for key negotiation
    

    demonstrating that the channel is unable to send the messages associated with Channel._close_internal.

    I was a bit dubious about the patch in #833 initially, since it seems to violate this part of RFC 4253:

    Once a party has sent a SSH_MSG_KEXINIT message for key exchange or re-exchange, until it has sent a SSH_MSG_NEWKEYS message (Section 7.3), it MUST NOT send any messages other than:

    o Transport layer generic messages (1 to 19) (but
    SSH_MSG_SERVICE_REQUEST and SSH_MSG_SERVICE_ACCEPT MUST NOT be
    sent);

    o Algorithm negotiation messages (20 to 29) (but further
    SSH_MSG_KEXINIT messages MUST NOT be sent);

    o Specific key exchange method messages (30 to 49).

    But actually I think it is fine because of a slightly later provision:

    Note, however, that during a key re-exchange, after sending a SSH_MSG_KEXINIT message, each party MUST be prepared to process an arbitrary number of messages that may be in-flight before receiving a SSH_MSG_KEXINIT message from the other party.

    In practice, I found the patch in #833, worked flawlessly (in my test case) in terms of client behaviour, but it results in some slightly weird server-side behaviour:

    debug1: expecting SSH2_MSG_KEXDH_INIT
    debug3: receive packet: type 97
    debug2: channel 0: rcvd close
    debug2: channel 0: is dead
    debug2: channel 0: gc: notify user
    

    ... which is fine (due to that provision about in-flight messages), but later the sshd log shows this:

    debug1: SSH2_MSG_NEWKEYS received
    debug2: set_newkeys: mode 0
    debug1: ssh_set_newkeys: rekeying after 457 input blocks (8856 bytes total)
    debug1: rekey after 4294967296 blocks
    channel_by_id: 0: bad id: channel free
    Received window adjust for non-open channel 0.
    

    ... so it seems that the Transport is actually sending an unwelcome channel message after the channel has been reaped on the server.

    I'm not sure if this matters a great deal though.

    My original thought on how to solve it was a bit more elaborate than the patch in #833: it seems to me that either:

    1. the responses sent my Channel._handle_close should either be queued (which is quite a big change),
    2. it should not be possible for Transport.run() to call Transport._send_user_message, since that can block the message pump

    That second idea seems more interesting: perhaps the protocol callbacks should use Transport._send_message instead? That avoids causing unpredictable performance/livelocks/deadlocks in the Transport due to both the waiting for Transport.clear_to_send and any unfortunate contention on Channel.lock too. Therefore, I think that exploring this angle might lead to a safer codebase, from a threading perspective.

  13. theburge commented on Mar 4, 2020

    @theburge

    To add to the above, I also did some analysis on whether the remote end initiating rekeying could cause the same race condition in Paramiko, and it seems to me that it can't. (FTR, I only analysed Paramiko in client mode, but the flow seems ~identical. I have a fuller analysis if it's interesting, but it's not directly related to this ticket.)

    Anyway, I think that means that there's a simple reasonable workaround -- but only if you have a well-behaved peer (e.g., an appropriately configured OpenSSH server that you control or otherwise trust): set paramiko.packet.Packetizer.REKEY_BYTES to a ludicrously high value early in your program, and rely on the other side to initiate rekeying when it considers it necessary.

  14. maretodoric commented on Jan 2, 2025

    @maretodoric

    This also appears to be happening in paramiko 3.5.0 with python 3.12.8.
    Happened two times in a row, now.

    Happening when I'm trying to read large stdout buffers.
    Here's what I'm trying to do. I have a class that would emulate file-like object and I'm using it to pass it onto the s3.upload_object in order for the file to be backed up to S3 bucket.

    s3.upload_object will periodically call read with buffer size to read and will upload it to bucket, and that's when the issue happens.

    Minimal code repro:

    import boto3
    import paramiko
    
    IP = 192.168.0.1
    SSH_USER = 'root'
    SSH_PRIVATE_KEY = '/root/.ssh/id_rsa'
    
    s3 = boto3.client('s3')
    
    class RemoteFile:
        def __init__(self, file: str, ssh: paramiko.SSHClient, file_is_cmd = False):
            self.file = file
            self.ssh = ssh
    
            if file_is_cmd:
                _in, self.out, err = self.ssh.exec_command(file)
            else:
                _in, self.out, err = self.ssh.exec_command(f'sudo cat {self.file}')
    
        def read(self, n: int = None):
            return self.out.read(n) # <-- 'paramiko.ssh_exception.SSHException: Key-exchange timed out waiting for key negotiation' occurs here.
        
        def close(self):
            self.out.close()
    
    with paramiko.SSHClient() as ssh:
        ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy)
        ssh.connect(hostname=IP, port=22, username=SSH_USER, key_filename=str(SSH_PRIVATE_KEY))
        
        # Get a list of files to backup:
        _in, out, err = ssh.exec_command('sudo ls /dir/with/lots/of/files')
        out.channel.recv_exit_status()
        files = ' '.join(out.read().decode().strip().split())
        
        s3.upload_fileobj(RemoteFile(f'sudo tar -zcf - -C /dir/with/lots/of/files {files}', ssh, file_is_cmd=True), 'bucket-name', f'backup.tar.gz')
    

    What's weird is, I've managed to replicate this two times in a row by running this script inside Docker container with base image: python:3.12-bookworm.
    That container runs on ec2 instance and script is trying to connect to private ip address of another ec2 instance running on same VPC.

    However, when I'm running from my local machine, it worked like a charm. Meaning, it doesn't always happen.

    Any idea for a reasonable workaround? theburge mentioned to set paramiko.packet.Packetizer.REKEY_BYTES to a ludicrously high value, which value would that be? Current value is 536870912, meaning something above 500megs, which already seems high enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions