Sending UDP data through socks5 proxy in python - python

I can't afford to send UDP packets through SOCKS5 proxy. I'm using PySocks. Here is my code :
import socks
proxyIP = "whatever.proxy"
proxyPort = 8080
s = socks.socksocket(socket.AF_INET, socket.SOCK_DGRAM)
s.set_proxy(socks.SOCKS5, proxyIP, proxyPort)
a = s.sendto(b"GET / HTTP/1.1", ("example.com",80))
In my test, the destination is my nginx web server. The proxy is not mine, I only know it's a socks5 proxy.
Here is the error I get :
Traceback (most recent call last):
File "test.py", line 35, in <module>
a = s.sendto(b"GET / HTTP/1.1", ("example.com",80))
File "C:\Python38\lib\site-packages\socks.py", line 367, in sendto
self.bind(("", 0))
File "C:\Python38\lib\site-packages\socks.py", line 353, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "C:\Python38\lib\site-packages\socks.py", line 524, in _SOCKS5_request
resp = self._readall(reader, 3)
File "C:\Python38\lib\site-packages\socks.py", line 278, in _readall
raise GeneralProxyError("Connection closed unexpectedly")
socks.GeneralProxyError: Connection closed unexpectedly
I also tested with s.connect/s.sendall and I have exactly the same error.
Finally, I must say it works perfectly with TCP (SOCK_STREAM).

Related

Tor proxy UDP sendto() function, python

I want send data using UDP through Tor proxy service, I try this way:
from socket import AF_INET, SOCK_DGRAM
import socket
import socks
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9150)
socket.socket = socks.socksocket
s = socket.socket(AF_INET, SOCK_DGRAM)
s.sendto(data, TARGET)
But I obtain these errors:
Traceback (most recent call last):
File "test.py" in <module> s.sendto(data, TARGET)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 396, in sendto
self.bind(("", 0))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 382, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 552, in _SOCKS5_request
raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS5Error: 0x07: Command not supported, or protocol error

Python websockets error gaierror

I'm trying to write a websocket that connects to a service running on localhost but it's throwing an error
>>> from websocket import create_connection
>>> ws = create_connection("ws://127.0.0.1", http_proxy_port="2974", http_proxy_host="quividicontent")
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
ws = create_connection("ws://127.0.0.1", http_proxy_port="2974", http_proxy_host="quividicontent")
File "C:\Python27\lib\websocket\_core.py", line 487, in create_connection
websock.connect(url, **options)
File "C:\Python27\lib\websocket\_core.py", line 211, in connect
options.pop('socket', None))
File "C:\Python27\lib\websocket\_http.py", line 64, in connect
hostname, port, is_secure, proxy)
File "C:\Python27\lib\websocket\_http.py", line 97, in _get_addrinfo_list
addrinfo_list = socket.getaddrinfo(phost, pport, 0, 0, socket.SOL_TCP)
gaierror: [Errno 11001] getaddrinfo failed
>>> ws = create_connection("ws://127.0.0.1", http_proxy_port="2974")
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
ws = create_connection("ws://127.0.0.1", http_proxy_port="2974")
File "C:\Python27\lib\websocket\_core.py", line 487, in create_connection
websock.connect(url, **options)
File "C:\Python27\lib\websocket\_core.py", line 214, in connect
self.handshake_response = handshake(self.sock, *addrs, **options)
File "C:\Python27\lib\websocket\_handshake.py", line 65, in handshake
status, resp = _get_resp_headers(sock)
File "C:\Python27\lib\websocket\_handshake.py", line 122, in _get_resp_headers
raise WebSocketBadStatusException("Handshake status %d", status)
WebSocketBadStatusException: Handshake status 200
>>> import socket
>>> socket.getaddrinfo('localhost', 2974)
[(23, 0, 0, '', ('::1', 2974, 0, 0)), (2, 0, 0, '', ('127.0.0.1', 2974))]
I'm sure the port is open and listening, used sockets and a more complex example with the onOpen onMessage function works.
Your issue occurs because you need to specify a protocol for the handshake with the websocket.
From wikipedia :
To establish a WebSocket connection, the client sends a WebSocket
handshake request, for which the server returns a WebSocket handshake
response, as shown in the example below.
During this handshake, the server and the client discuss about what protocols should be used and if there is no protocol specified, this could lead to an error (not always).
From the python-websocket doc, specify a protocol can be done with
:
ws = websocket.create_connection("ws://exapmle.com/websocket", subprotocols=["binary", "base64"])
In your particular case, subprotocols should be ['quividicontent']

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.

Using a Python script to establish FTP connection behind FTP proxy

Im trying to connect to an ftp server that is behind ftp proxy.
The proxy server does not require username and password, the ftp server does.
I have searched through several posts:
Proxies in python
How to use urllib2 to access ftp/http server using proxy with authentification
How to connect to ftp server via proxy using ftplib
How to specify an authenticated proxy for a python http connection?
Here is the last version of my code. So far I've figured out that to open the ftp server behind an ftp proxy, the notation ftp://username:password#server can be used. I'm using the urllib2 library to define the proxy server.
import urllib2
proxy_host = '101.11.44.84:8021' # only host name, no scheme (http/ftp)
proxy_handler = urllib2.ProxyHandler({'ftp': proxy_host})
auth = urllib2.FTPHandler()
try:
opener_thru_proxy = urllib2.build_opener(proxy_handler, auth)
except:
logger.exception('build_opener error')
raise
print opener_thru_proxy
try:
conn = opener_thru_proxy.open('ftp://user:password#100.159.66.113')
except:
logger.exception('opener thru proxy error')
raise
print conn.read()
conn.close()
The output of this code yields:
2016-05-23 16:15:28,286 - root - ERROR - opener thru proxy error
Traceback (most recent call last):
File "<string>", line 293, in <module>
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 431, in open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 449, in _open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 409, in _call_chain
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1412, in ftp_open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1434, in connect_ftp
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 875, in __init__
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 884, in init
File "C:\_Studna\Python\python-2.7.10.amd64\lib\ftplib.py", line 135, in connect
File "C:\_Studna\Python\python-2.7.10.amd64\lib\socket.py", line 575, in create_connection
URLError: <urlopen error ftp error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
It seems that I'm unable to establish the ftp connection with the ftp server.
However, when I use the same set of connection data and use it in Total Commander, the connection works correctly. See the image enclosed Total Commander ftp connection window.

Network is unreachable if running script on webhosting

The next script runs fine on my mac. When I try to run it on my WebHosting (bluehost) I'm getting socket.error: [Errno 101] Network is unreachable. Any idea how can I fix it?
#!/usr/bin/python
# Required header that tells the browser how to render the text.
print "Content-type: text/html\r\n\r\n";
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('user#gmail.com', 'password')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
print mail.list()
Traceback (most recent call last):
File "test2.py", line 6, in <module>
mail = imaplib.IMAP4_SSL('imap.gmail.com')
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1148, in __init__
IMAP4.__init__(self, host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 163, in __init__
self.open(host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1159, in open
self.sock = socket.create_connection((host, port))
File "/home4/user/python27/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 101] Network is unreachable
Their support isn't helpful at all.
Can it be port related or maybe SSL?
On bluehosts help pages they mention that outgoing connnections are restricted, so ther problem isn't with your program. The only way of getting outbound connections to be allowed seems to pay for it.

Categories

Resources