Tor proxy UDP sendto() function, python - 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

Related

Sending UDP data through socks5 proxy in 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).

How to send BluetoothRFCommSocket with Scapy?

I set up a BluetoothRFCommSocket with this code:
from scapy.layers.bluetooth import *
from scapy.all import *
bt = BluetoothRFCommSocket('68:A0:3E:CC:24:06',2)
And the error is:
Traceback (most recent call last):
File "test.py", line 3, in <module>
bt = BluetoothRFCommSocket('68:A0:3E:CC:24:06',2)
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3rc1.dev120-py2.7.egg/scapy/layers/bluetooth.py", line 1229, in __init__
s.connect((bt_address, port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
What is the correct way to set up BluetoothRFCommSocket and send it?
I also get this error.
From scapy source code:
class BluetoothRFCommSocket(BluetoothL2CAPSocket):
"""read/write packets on a connected RFCOMM socket"""
def __init__(self, bt_address, port=0):
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW,
socket.BTPROTO_RFCOMM)
s.connect((bt_address, port))
self.ins = self.outs = s
Scapy uses SOCK_RAW to create the socket, but it seems like RFCOMM does not support this.(I have also tried to use c_types and libc, but the error still occured)
Replace SOCK_RAW with SOCK_STREAM will eliminate the error.This is the way PyBluez use.
(L2CAP support SOCK_RAW)

Python P2P sockets error "This operation would block forever"

Hello I'm trying to create a P2P program to distribute messages throgh the clients.
My server.py:
import requests
from flask import Flask, jsonify, request
import logging
from daemon import Daemon
import time
import argparse
import sys
from transaction import Transaction
import settings
import socket
import threading
bind_ip = '139.59.26.12'
bind_port = 9998
my_node_addr = str(bind_ip) + ":" + str(bind_port)
clients = [("0.0.0.0", 9999), ("0.0.0.0", 9998)]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5) # max backlog of connections
print('Listening on {}:{}'.format(bind_ip, bind_port))
numbers = []
def broadcast_info(info):
for n in clients:
node_str_addr = str(n[0]) + ":" + str(n[1])
print("Selected: " + node_str_addr)
if node_str_addr != my_node_addr:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((n[0], n[1]))
client.send(info)
response = client.recv(4096)
def handle_client_connection(client_socket):
request = client_socket.recv(1024)
request_str = request.decode()
if request_str == 'print':
client_socket.send(str(numbers).encode('utf-8'))
print(numbers)
else:
client_socket.send('Added!'.encode('utf-8'))
client_socket.close()
num_rec = int(request.decode())
if num_rec not in numbers:
numbers.append(num_rec)
#broadcast_info(request)
while True:
client_sock, address = server.accept()
print('Accepted connection from {}:{}'.format(address[0], address[1]))
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
# without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
)
client_handler.start()
And my client:
import socket
hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
target = '{}.{}.{}'.format(hostname, sld, tld)
# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
# client.connect((target, port))
client.connect(('139.59.76.32', 9998))
# send some data (in this case a HTTP GET request)
client.send("2".encode('utf-8')) # Number or "print"
# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)
print (response)
client.close()
Sometimes it works well. But then after a few tries this error appears:
Exception in thread Thread-11:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 43, in handle_client_connection
request = client_socket.recv(1024)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 336, in recv
self._wait(self._read_event)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 156, in _wait
self.hub.wait(watcher)
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 651, in wait
result = waiter.get()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 898, in get
return self.hub.switch()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 630, in switch
return RawGreenlet.switch(self)
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7fdf21aa2af8 epoll pending=0 ref=0 fileno=9>)
I tried everything. In my local machine works fine. But when I try to do it on my Digitalocean VPS, then this happens. I've search about this error over the Internet but I can't find anything that helps me.
Do you know what can be the cause of this error?
Thanks

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']

socket server on a thread not releasing the port after the process terminates

The following code runs a socket server on a thread. The client socket sends 'client: hello' to the server, and the server socket receives and replies 'server: world'.
import socket
import threading
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 12345))
sock.listen(1)
req, addr = sock.accept()
print req.recv(1024)
req.sendall('server: world')
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 12345))
sock.sendall('client: hello')
print sock.recv(1024)
def main():
t = threading.Thread(target=server)
t.start()
client()
if __name__ == '__main__':
main()
It runs ok as expected the first time, but from the second time, if you do not wait for a good few seconds for the server to release the socket, and if you try this on a Linux machine or Mac (Windows do not get it somehow) you will run into this error:
Traceback (most recent call last):
File "socket_send_receive.py", line 24, in <module>
main()
File "socket_send_receive.py", line 21, in main
client()
File "socket_send_receive.py", line 14, in client
sock.connect(('127.0.0.1', 12345))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "socket_send_receive.py", line 6, in server
sock.bind(('127.0.0.1', 12345))
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
I am looking for some insight into why this is happening and if it is possible to be genuinely resolved or what best practice should be adopted.
I know already using this option can be a workaround thanks to the other posts here on stackoverflow.
socket.SO_REUSEADDR
When a socket is closed, it ends up in a state called STATE_WAIT (see this diagram). While the socket is in this state, no one else can use the same address (ip-number/port pair) unless the SO_REUSEADDR option is set on the socket.
See e.g. the Wikipedia article on TCP for more information about how TCP works and the different states.

Categories

Resources