Repository navigation
Open
Labels
Milestone
Description
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.
Reacted by Radim Řehůřek
Activity
tsellers-r7 commentedon Oct 24, 2016
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.
tsellers-r7 commentedon Oct 24, 2016
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 toself.packetizer.need_rekeybeing true.paramiko/paramiko/transport.py
Line 1753 in 833d9f7
Transport._send_kex_initclears theclear_to_sendflag, preventing trafficparamiko/paramiko/transport.py
Line 1920 in 833d9f7
The loop reads messages from the server
paramiko/paramiko/transport.py
Line 1756 in 833d9f7
Before the
MSG_KEXINITmessage is sent from the server, aMSG_CHANNEL_CLOSE(type 97 ) message is sent, which is handled by the_channel_handler_tableparamiko/paramiko/transport.py
Line 1779 in 833d9f7
The above calls
channel._handle_closeparamiko/paramiko/transport.py
Line 2379 in 833d9f7
channel._handle_closegenerates anEOFmessage and attempts to send it to the server viatransport._send_user_messageTransport._send_user_messageloops while waiting on, among other things, theclear_to_sendflag.paramiko/paramiko/transport.py
Line 1585 in 833d9f7
Since the server has closed the channel, it will never finish the key exchange / negotiations and so the
transport.runloop will continue until_send_user_messagetimes out and returnsKey-exchange timed out waiting for key negotiationparamiko/paramiko/transport.py
Line 1600 in 833d9f7
tsellers-r7 commentedon Oct 25, 2016
FYI, while testing this I was saw that the server (in debug mode
sudo /usr/sbin/sshd -p22 -D -d -e) saw the client'sSSH_MSG_KEXINIT, sent aSSH2_MSG_KEXINITresponse, and was waiting onSSH2_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.bitprophet commentedon Dec 6, 2016
(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:
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
SSHExceptionis raised - something else is setting the transport inactive first.source-ram commentedon Aug 31, 2017
Any one with the fix ?
acechef commentedon Aug 21, 2018
Is it fixed?
sashas-lb commentedon Nov 12, 2018
We are expiriencing same issue, easily reproducable with the following script:
paramiko version: paramiko (2.4.2)
openssh version: OpenSSH_7.2p2 Ubuntu-4ubuntu2.6, OpenSSL 1.0.2g 1 Mar 2016
agraubert commentedon Nov 22, 2019
Are there any updates? This is still occurring in 2.6.0
piskvorky commentedon Jan 26, 2020
Also bitten by this.
paramiko==2.6.0theburge commentedon Mar 4, 2020
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_sendis unset) is the initiator for the problem, causing the Transport thread to self-livelock in_send_user_message(called byChannel._handle_close(), in turn called from theTransport.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()blocksTransport.run()'s message pump: it's awaitingTransport().clear_to_sendbecoming unset , but only allowTransport.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_BYTESuntil it made the problem occur):(And as in the original report, my OpenSSH server gets as far as
debug1: expecting SSH2_MSG_KEXDH_INIT-- so it has sent itsSSH_MSG_KEXINIT-- and then 30s later -- i.e., after theclear_to_send_timeoutexpires --sshdnotes its peer reset the connection.)I also added a little bit of descriptive logging in
Channel._handle_closeto demonstrate the problem:and here's the output in a reproducer case:
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:
But actually I think it is fine because of a slightly later provision:
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:
... which is fine (due to that provision about in-flight messages), but later the
sshdlog shows this:... 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:
Channel._handle_closeshould either be queued (which is quite a big change),Transport.run()to callTransport._send_user_message, since that can block the message pumpThat second idea seems more interesting: perhaps the protocol callbacks should use
Transport._send_messageinstead? That avoids causing unpredictable performance/livelocks/deadlocks in theTransportdue to both the waiting forTransport.clear_to_sendand any unfortunate contention onChannel.locktoo. Therefore, I think that exploring this angle might lead to a safer codebase, from a threading perspective.theburge commentedon Mar 4, 2020
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_BYTESto a ludicrously high value early in your program, and rely on the other side to initiate rekeying when it considers it necessary.maretodoric commentedon Jan 2, 2025
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_objectin order for the file to be backed up to S3 bucket.s3.upload_objectwill periodically call read with buffer size to read and will upload it to bucket, and that's when the issue happens.Minimal code repro:
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_BYTESto a ludicrously high value, which value would that be? Current value is 536870912, meaning something above 500megs, which already seems high enough.