What is causing paramiko.SSHException: Invalid packet blocking? - python

When I attempt to connect to one of our internal servers using paramiko (inside of fabric, for what it's worth) I get this error:
Retrieving packages from server p-websvr-004
[p-websvr-004] run: /usr/sbin/pkg_info -aD|grep "Information for"
starting thread (client mode): 0x179f090L
Banner: ----------------------------------------------------------------------
Banner: Welcome to Mycompany, Inc. Unauthorized access, is strictly prohibited
Connected (version 2.0, client OpenSSH_4.5p1)
Exception: Invalid packet blocking
Traceback (most recent call last):
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/transport.py", line 1491, in run
ptype, m = self.packetizer.read_message()
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/packet.py", line 344, in read_message
raise SSHException('Invalid packet blocking')
Every other host we have works, as far as I can tell. What's causing this to happen, and how can I fix it?

First obvious question, how is this host different than the rest?
By the looks of it, it could be a bug in the SSH server. Does openssh on the command line work, and is it using a different cipher?

Related

Is there a way of setting TLS Version using the redshift-connector driver in Python?

We're currently using the redshift-connector driver in Python to connect to a a Redshift database.
This is working locally however when deploying to a server with limited internet connectivity we're seeing SSL handshake errors.
When observing this on Wireshark we see locally the handshake uses TLSv1.2, however on the server we see TLSv1 and no response which we believe is the culprit. Is there a way of specifying the TLS version on a connection made with the redshift-connector?
Code:
import redshift_connector
connection = redshift_connector.connect(
host='hostip',
database='db',
user=’username’,
password=’password’,
timeout=120
)
Error:
Traceback (most recent call last):
File "redshift.py", line 9, in <module>
timeout=20
File "C:\Python37\lib\site-packages\redshift_connector\__init__.py", line 334, in connect
credentials_provider=info.credentials_provider,
File "C:\Python37\lib\site-packages\redshift_connector\core.py", line 587, in __init__
raise InterfaceError("communication error", e)
redshift_connector.error.InterfaceError: ('communication error', timeout('_ssl.c:1074: The handshake operation timed out'))
We've verified the port is open via telnet so this isn't a firewall issue. Additionally we used ssl=false and can connect without any problems but would prefer this to be enabled
Many thanks for any help!

Sending UDP requests through Tor (SOCKS5) with Python

So I have a python script that needs to send a packet to my server 'x.x.x.x'. I've been able to successfully initialise Tor through Python by setting up the SOCKS5 proxy, but upon trying to send a packet to my server I get the error:
Traceback (most recent call last):
File "test.py", line 18, in <module>
sock.sendto(bytes, ("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 338, in sendto
self.bind(("", 0))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 325, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 494, in _SOCKS5_request
raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS5Error: 0x07: Command not supported, or protocol error
From what I've seen, socket/SOCKS5 doesn't support connectionless UDP, so I attempted connecting to the port and then sending the packet once connected. I still get the same error as seen above, output can be seen below.
Traceback (most recent call last):
File "test.py", line 18, in <module>
sock.connect(("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 698, in connect
self.bind(("", 0))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 325, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 494, in _SOCKS5_request
raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS5Error: 0x07: Command not supported, or protocol error
Seeing as a UDP connection does not work either, I would prefer to stay connectionless as this makes my intended use simpler as the port is not necessarily active/open at any given time. The script I'm using to attempt to send the packet can be seen below. I've added but commented out the connectionless and connection methods I was using. Ignore all the extra imports at the top, these are for use later in the script development.
import socks
import socket
import requests
from TorCtl import TorCtl
import urllib2
import random
import math
import time
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
socket.socket = socks.socksocket
print requests.get("http://icanhazip.com").text
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
bytes=random._urandom(1024)
# UDP CONNECTION METHOD
#sock.connect(("x.x.x.x", 6000))
#sock.send(bytes)
# UDP CONNECTIONLESS METHOD
#sock.sendto(bytes, ("x.x.x.x", 6000))
Which brings me to my question - is there any way to send UDP packets via a connectionless method through a SOCKS5 proxy in python?
UPDATE
I originally had SocksiPy installed instead of PySocks, so I've replaced the modules and removed the monkeypatch in the original script. But now, I'm instead getting 'Broken Pipe' errors, as seen below.
Traceback (most recent call last):
File "test.py", line 19, in <module>
s.sendto(bytes, ("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 336, in sendto
return _BaseSocket.sendto(self, bytes, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 223, in <lambda>
return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
socket.error: [Errno 32] Broken pipe
I've double checked to make sure Tor is actually working and the proxy is up, which it is as I can receive HTTP requests and responses through the Tor proxy - the responses to sites like http://icanhazip.com/ return a different IP that my actual IP, which suggests that Tor is indeed functioning. I also figured that removing the monkeypatch might make it work with better compatibility, seeing as with the new PySocks module on the OLD script it still fails with the original errors seen above.
The new script:
import socks
import socket
import random
import math
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "localhost", 9050)
bytes=random._urandom(1024)
# UDP CONNECTION METHOD
#sock.connect(("x.x.x.x", 6000))
#sock.send(bytes)
# UDP CONNECTIONLESS METHOD
#s.sendto(bytes, ("x.x.x.x", 6000))
The errors I'm describing above are with the connectionless method - using the connection method seems to possibly work, however it hangs when connecting to the port (which is the be expected, as the port isn't open).
As #gwyn pointed out, Tor only supports TCP streams, as specified on their website. Using UDP over Tor will not work, only TCP connections.

What is the correct way to use source_address

I have come across a corner in socket in Python3.5. When running the code below something is wrong and an error is thrown.
import socket
print(socket.create_connection(('www.baidu.com', 80), source_address=('127.0.0.1', 8998)))
Error:
Traceback (most recent call last):
File "demo.py", line 4, in <module>
print(socket.create_connection(('www.baidu.com', 80), source_address=('127.0.0.1', 8998)))
File "/usr/local/lib/python3.5/socket.py", line 707, in create_connection
raise err
File "/usr/local/lib/python3.5/socket.py", line 698, in create_connection
sock.connect(sa)
OSError: [Errno 22] Invalid argument
Short answer is don't!
You can't play with low level Python sockets not knowing how BSD TCP stack is working and how to use BSD sockets.
The source_address is - as it clearly states - source address and port for you connection. You MUST NOT make connection from loopback interface address to the address in the outside world.
So, the invalid argument error is correct.
Do you really need to set source_address? Why don't let that to the operating system?
You can't use the source address 127.0.0.1. The server can't reach you on this address, its just locally on your computer. This is your local loopback address. You have to use your public IP address.
So best is let the system set the source address like the other answer says.
socket.create_connection(('www.baidu.com', 80))

Catching bottle server errors

I am trying to get my bottle server so that when one person in a game logs out, everyone can immediately see it. As I am using long polling, there is a request open with all the users.
The bit I am having trouble with is catching the exception that is thrown when the user leaves the page from the long polling that can no longer connect to the page. The error message is here.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 438, in handle_one_response
self.run_application()
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 425, in run_application
self.process_result()
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 416, in process_result
self.write(data)
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 373, in write
self.socket.sendall(msg)
File "/usr/lib/python2.7/dist-packages/gevent/socket.py", line 509, in sendall
data_sent += self.send(_get_memory(data, data_sent), flags)
File "/usr/lib/python2.7/dist-packages/gevent/socket.py", line 483, in send
return sock.send(data, flags)
error: [Errno 32] Broken pipe
<WSGIServer fileno=3 address=0.0.0.0:8080>: Failed to handle request:
request = GET /refreshlobby/1 HTTP/1.1 from ('127.0.0.1', 53331)
application = <bottle.Bottle object at 0x7f9c05672750>
127.0.0.1 - - [2013-07-07 10:59:30] "GET /refreshlobby/1 HTTP/1.1" 200 160 6.038377
The function to handle that page is this.
#route('/refreshlobby/<id>')
def refreshlobby(id):
while True:
yield lobby.refresh()
gevent.sleep(1)
I tried catching the exception within the function, and in a decorator which I put to wrap #route, neither of which worked. I tried making an #error(500) decorator, but that didn't trigger, either. It seems that this is to do with the internals of bottle.
Edit: I know now that I need to be catching socket.error, but I don't know whereabouts in my code
The WSGI runner
Look closely at the traceback: this in not happening in your function, but in the WSGI runner.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 438, in handle_one_response
self.run_application()
The way the WSGI runner works, in your case, is:
Receives a request
Gets a partial response from your code
Sends it to the client (this is where the exception is raised)
Repeats steps 2-3
You can't catch this exception
This error is not raised in your code.
It happens when you try to send a response to a client that closed the connection.
You'll therefore not be able to catch this error from within your code.
Alternate solutions
Unfortunately, it's not possible to tell from within the generator (your code) when it stops being consumed.
It's also not a good idea to rely on your generator being garbage collected.
You have a couple other solutions.
"Last seen"
Another way to know when an user disconnects would probably be to record a "last seen", after your yield statement.
You'll be able to identify clients that disconnected if their last seen is far in the past.
Other runner
Another, non-WSGI runner, will be more appropriate for a realtime application. You could give tornado a try.

Paramiko bug: SSHClient.connect() method hangs when the peer is unreachable even if I set the 'timeout'

Here is a python code snippet that uses paramiko:
import paramiko
sshClient = paramiko.SSHClient()
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy)
sshClient.connect(_peerIp, username=_username, password=_password, timeout=3.0)
As soon as I run the script, I also unplug _peerIp's network cable. And connect() method hangs. Even though the timeout is 3.0, it has been 10 minutes and it still hangs.
(I think the TCP connection was established in a split second and I unplugged the cable during the ssh establishment)
So, do you know any workaround for this? My script will run at a manufacturing factory and it must not hang in such a scenario and handle it properly.
EDIT:
It just gave an exception:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 438, in _auth
self._transport.auth_publickey(username, key)
File "/usr/lib/pymodules/python2.6/paramiko/transport.py", line 1234, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/pymodules/python2.6/paramiko/auth_handler.py", line 163, in wait_for_response
raise e
socket.error: [Errno 113] No route to host
Ok, at least it eventually raised an exception but I believe this is not the expected behaviour. If the timeout is 3.0, connect() method should return something after timeout expires.

Categories

Resources