caterpillar/server.py

562 lines
21 KiB
Python
Raw Permalink Normal View History

2024-02-28 06:11:49 +00:00
#!/usr/bin/python3
2024-02-28 06:33:04 +00:00
#
2024-02-28 06:11:49 +00:00
# server.py
2024-02-28 06:33:04 +00:00
#
2024-02-19 05:13:35 +00:00
# Caterpillar - The simple and parasitic web proxy with spam filter
2024-02-17 08:44:19 +00:00
# Namyheon Go (Catswords Research) <gnh1201@gmail.com>
2024-02-19 04:45:40 +00:00
# https://github.com/gnh1201/caterpillar
# Created at: 2022-10-06
2024-03-04 09:38:54 +00:00
# Updated at: 2024-03-04
2024-02-28 06:33:04 +00:00
#
2022-10-05 17:19:38 +00:00
import argparse
import socket
import sys
2022-11-24 09:02:32 +00:00
import os
2022-10-05 17:19:38 +00:00
from _thread import *
2024-02-28 07:40:08 +00:00
from subprocess import PIPE, Popen
2022-10-05 17:19:38 +00:00
import base64
2022-10-08 04:03:15 +00:00
import json
2022-11-24 09:02:32 +00:00
import ssl
2022-11-25 08:12:58 +00:00
import time
2024-02-18 22:58:44 +00:00
import hashlib
2024-02-22 08:16:07 +00:00
import traceback
2024-02-23 06:02:14 +00:00
import textwrap
2024-02-28 06:12:24 +00:00
import importlib
2022-10-05 17:19:38 +00:00
from datetime import datetime
2022-10-06 12:09:34 +00:00
from platform import python_version
2022-10-05 17:19:38 +00:00
2024-02-28 08:04:06 +00:00
import re
2022-10-06 12:09:34 +00:00
import requests
2024-02-28 07:10:16 +00:00
from requests.auth import HTTPBasicAuth
2022-10-05 17:19:38 +00:00
from decouple import config
2024-02-28 07:25:02 +00:00
def extract_credentials(url):
pattern = re.compile(r'(?P<scheme>\w+://)?(?P<username>[^:/]+):(?P<password>[^@]+)@(?P<url>.+)')
match = pattern.match(url)
if match:
scheme = match.group('scheme') if match.group('scheme') else 'https://'
username = match.group('username')
password = match.group('password')
url = match.group('url')
return username, password, scheme + url
else:
return None, None, url
2024-02-28 07:10:16 +00:00
2024-02-26 08:04:44 +00:00
def jsonrpc2_create_id(data):
2024-02-26 13:07:45 +00:00
return hashlib.sha1(json.dumps(data).encode(client_encoding)).hexdigest()
2024-02-26 08:04:44 +00:00
2024-02-26 13:07:45 +00:00
def jsonrpc2_encode(method, params = None):
2024-02-25 17:37:11 +00:00
data = {
"jsonrpc": "2.0",
"method": method,
"params": params
}
2024-02-26 08:06:58 +00:00
id = jsonrpc2_create_id(data)
data['id'] = id
return (id, json.dumps(data))
2024-02-25 17:37:11 +00:00
2024-02-26 13:07:45 +00:00
def jsonrpc2_result_encode(result, id = ''):
data = {
"jsonrpc": "2.0",
"result": result,
"id": id
}
return json.dumps(data)
2024-02-23 03:53:44 +00:00
def parse_first_data(data):
2024-02-23 05:40:15 +00:00
parsed_data = (b'', b'', b'', b'', b'')
2024-02-23 03:53:44 +00:00
2022-11-25 10:32:17 +00:00
try:
first_line = data.split(b'\n')[0]
method, url = first_line.split()[0:2]
http_pos = url.find(b'://') #Finding the position of ://
scheme = b'http' # check http/https or other protocol
if http_pos == -1:
temp = url
else:
temp = url[(http_pos+3):]
scheme = url[0:http_pos]
port_pos = temp.find(b':')
webserver_pos = temp.find(b'/')
if webserver_pos == -1:
webserver_pos = len(temp)
2024-02-17 19:04:02 +00:00
webserver = b''
2022-11-25 10:32:17 +00:00
port = -1
if port_pos == -1 or webserver_pos < port_pos:
port = 80
webserver = temp[:webserver_pos]
else:
port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])
webserver = temp[:port_pos]
if port == 443:
scheme = b'https'
2024-02-23 03:53:44 +00:00
parsed_data = (webserver, port, scheme, method, url)
2022-11-25 10:32:17 +00:00
except Exception as e:
2024-02-26 13:07:45 +00:00
print("[*] Exception on parsing the header. Cause: %s" % (str(e)))
2024-02-23 03:53:44 +00:00
return parsed_data
def conn_string(conn, data, addr):
2024-02-26 07:40:45 +00:00
# check is it JSON-RPC 2.0 request
if data.find(b'{') == 0:
2024-03-04 09:37:44 +00:00
jsondata = json.loads(data.decode(client_encoding, errors='ignore'))
if jsondata['jsonrpc'] == "2.0":
jsonrpc2_server(conn, jsondata['id'], jsondata['method'], jsondata['params'])
return
2024-02-26 07:40:45 +00:00
2024-02-23 05:40:15 +00:00
# parse first data (header)
2024-02-23 03:53:44 +00:00
webserver, port, scheme, method, url = parse_first_data(data)
2022-11-25 08:12:58 +00:00
2024-02-17 19:04:02 +00:00
# if it is reverse proxy
2024-02-18 01:13:58 +00:00
if local_domain != '':
localserver = local_domain.encode(client_encoding)
if webserver == localserver or data.find(b'\nHost: ' + localserver) > -1:
2024-02-22 08:16:07 +00:00
print ("[*] Detected the reverse proxy request: %s" % (local_domain))
2024-02-18 01:13:58 +00:00
scheme, _webserver, _port = proxy_pass.encode(client_encoding).split(b':')
webserver = _webserver[2:]
port = int(_port.decode(client_encoding))
2024-02-17 19:04:02 +00:00
2022-11-25 08:12:58 +00:00
proxy_server(webserver, port, scheme, method, url, conn, addr, data)
2024-03-04 09:37:44 +00:00
def jsonrpc2_server(conn, id, method, params):
if method == "relay_accept":
accepted_relay[id] = conn
connection_speed = params['connection_speed']
print ("[*] connection speed: %s miliseconds" % (str(connection_speed)))
while conn.fileno() > -1:
time.sleep(1)
del accepted_relay[id]
print ("[*] relay destroyed: %s" % (id))
else:
rpcmethod = Extension.get_rpcmethod(method)
2024-03-04 09:38:54 +00:00
if rpcmethod:
2024-03-04 14:00:58 +00:00
rpcmethod.dispatch("call", id, params, conn)
2024-03-02 07:01:03 +00:00
2022-11-25 08:12:58 +00:00
def proxy_connect(webserver, conn):
2022-11-25 12:35:02 +00:00
hostname = webserver.decode(client_encoding)
2022-11-25 08:12:58 +00:00
certpath = "%s/%s.crt" % (certdir.rstrip('/'), hostname)
2022-11-25 10:32:17 +00:00
# https://stackoverflow.com/questions/24055036/handle-https-request-in-proxy-server-by-c-sharp-connect-tunnel
conn.send(b'HTTP/1.1 200 Connection Established\r\n\r\n')
2022-11-25 08:12:58 +00:00
2022-11-25 10:32:17 +00:00
# https://github.com/inaz2/proxy2/blob/master/proxy2.py
2022-10-05 17:19:38 +00:00
try:
2022-11-25 08:12:58 +00:00
if not os.path.isfile(certpath):
epoch = "%d" % (time.time() * 1000)
2022-11-25 12:54:25 +00:00
p1 = Popen([openssl_binpath, "req", "-new", "-key", certkey, "-subj", "/CN=%s" % hostname], stdout=PIPE)
p2 = Popen([openssl_binpath, "x509", "-req", "-days", "3650", "-CA", cacert, "-CAkey", cakey, "-set_serial", epoch, "-out", certpath], stdin=p1.stdout, stderr=PIPE)
2022-11-25 08:12:58 +00:00
p2.communicate()
2022-10-06 02:24:19 +00:00
except Exception as e:
2024-02-18 18:26:46 +00:00
print("[*] Skipped generating the certificate. Cause: %s" % (str(e)))
2022-11-25 08:12:58 +00:00
2022-11-25 10:32:17 +00:00
# https://stackoverflow.com/questions/11255530/python-simple-ssl-socket-server
# https://docs.python.org/3/library/ssl.html
2022-11-25 08:12:58 +00:00
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certpath, certkey)
2022-11-25 10:32:17 +00:00
# https://stackoverflow.com/questions/11255530/python-simple-ssl-socket-server
2022-11-25 08:12:58 +00:00
conn = context.wrap_socket(conn, server_side=True)
2022-11-25 10:32:17 +00:00
data = conn.recv(buffer_size)
2022-10-05 17:19:38 +00:00
2022-11-25 10:32:17 +00:00
return (conn, data)
2022-11-24 09:02:32 +00:00
2024-02-17 19:19:54 +00:00
def proxy_check_filtered(data, webserver, port, scheme, method, url):
2024-02-17 12:50:36 +00:00
filtered = False
2024-02-17 12:21:24 +00:00
2024-03-01 15:38:48 +00:00
filters = Extension.get_filters()
2024-02-28 06:41:52 +00:00
print ("[*] Checking data with %s filters..." % (str(len(filters))))
for f in filters:
2024-02-28 06:33:04 +00:00
filtered = f.test(filtered, data, webserver, port, scheme, method, url)
2024-02-18 08:54:28 +00:00
2024-02-17 08:44:19 +00:00
return filtered
2024-02-17 05:40:33 +00:00
2022-11-24 09:02:32 +00:00
def proxy_server(webserver, port, scheme, method, url, conn, addr, data):
2022-10-05 17:19:38 +00:00
try:
2024-02-17 05:26:27 +00:00
print("[*] Started the request. %s" % (str(addr[0])))
2022-10-08 04:23:40 +00:00
2024-02-18 03:59:24 +00:00
# SSL negotiation
2024-02-22 08:16:07 +00:00
is_ssl = scheme in [b'https', b'tls', b'ssl']
if is_ssl and method == b'CONNECT':
2024-02-18 03:59:24 +00:00
while True:
try:
conn, data = proxy_connect(webserver, conn)
break # success
2024-02-18 04:43:59 +00:00
#except OSError as e:
# print ("[*] Retrying SSL negotiation... (%s:%s) %s" % (webserver.decode(client_encoding), str(port), str(e)))
2024-02-18 03:59:24 +00:00
except Exception as e:
raise Exception("SSL negotiation failed. (%s:%s) %s" % (webserver.decode(client_encoding), str(port), str(e)))
2022-11-24 09:02:32 +00:00
2024-02-23 04:15:49 +00:00
# override data
2024-02-23 03:59:22 +00:00
if is_ssl:
2024-02-23 06:02:14 +00:00
_, _, _, method, url = parse_first_data(data)
2024-02-23 03:59:22 +00:00
2024-02-22 08:16:07 +00:00
# https://stackoverflow.com/questions/44343739/python-sockets-ssl-eof-occurred-in-violation-of-protocol
def sock_close(sock, is_ssl = False):
#if is_ssl:
# sock = sock.unwrap()
#sock.shutdown(socket.SHUT_RDWR)
sock.close()
2024-02-17 21:23:58 +00:00
# Wait to see if there is more data to transmit
2024-02-18 17:16:25 +00:00
def sendall(sock, conn, data):
2024-02-18 17:10:13 +00:00
# send first chuck
2024-02-18 17:37:37 +00:00
if proxy_check_filtered(data, webserver, port, scheme, method, url):
2024-02-18 18:24:22 +00:00
sock.close()
2024-02-18 17:37:37 +00:00
raise Exception("Filtered request")
2024-02-18 17:10:13 +00:00
sock.send(data)
2024-02-18 17:05:28 +00:00
if len(data) < buffer_size:
return
2024-02-18 17:10:13 +00:00
# send following chunks
2024-02-18 17:05:28 +00:00
buffered = b''
2024-02-17 22:41:17 +00:00
conn.settimeout(1)
2024-02-17 21:23:58 +00:00
while True:
try:
chunk = conn.recv(buffer_size)
if not chunk:
break
2024-02-18 17:05:28 +00:00
buffered += chunk
if proxy_check_filtered(buffered, webserver, port, scheme, method, url):
2024-02-22 08:16:07 +00:00
sock_close(sock, is_ssl)
2024-02-18 17:05:28 +00:00
raise Exception("Filtered request")
2024-02-18 17:10:13 +00:00
sock.send(chunk)
2024-02-18 17:26:04 +00:00
if len(buffered) > buffer_size*2:
2024-02-20 02:03:25 +00:00
buffered = buffered[-buffer_size*2:]
2024-02-17 21:23:58 +00:00
except:
break
2024-02-18 16:50:43 +00:00
# do response
2024-02-17 05:23:51 +00:00
if server_url == "localhost":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2024-02-17 05:40:33 +00:00
2024-02-22 08:16:07 +00:00
if is_ssl:
2024-02-17 08:44:19 +00:00
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
2024-02-17 05:40:33 +00:00
2024-02-17 08:44:19 +00:00
sock = context.wrap_socket(sock, server_hostname=webserver.decode(client_encoding))
sock.connect((webserver, port))
2024-02-18 17:05:28 +00:00
#sock.sendall(data)
2024-02-18 17:16:25 +00:00
sendall(sock, conn, data)
2024-02-17 08:44:19 +00:00
else:
sock.connect((webserver, port))
2024-02-18 17:05:28 +00:00
#sock.sendall(data)
2024-02-18 17:16:25 +00:00
sendall(sock, conn, data)
2024-02-17 05:23:51 +00:00
2024-02-17 05:26:27 +00:00
i = 0
2024-02-22 08:16:07 +00:00
is_http_403 = False
2024-02-18 16:48:15 +00:00
buffered = b''
2024-02-17 05:23:51 +00:00
while True:
2024-02-17 08:44:19 +00:00
chunk = sock.recv(buffer_size)
2024-02-17 05:26:27 +00:00
if not chunk:
2024-02-17 05:23:51 +00:00
break
2024-02-23 03:53:44 +00:00
if i == 0 and chunk.find(b'HTTP/1.1 403') == 0:
is_http_403 = True
break
2024-02-18 16:48:15 +00:00
buffered += chunk
if proxy_check_filtered(buffered, webserver, port, scheme, method, url):
2024-02-22 08:16:07 +00:00
sock_close(sock, is_ssl)
2024-02-18 16:50:43 +00:00
add_filtered_host(webserver.decode(client_encoding), '127.0.0.1')
2024-02-18 17:05:28 +00:00
raise Exception("Filtered response")
2024-02-18 16:48:15 +00:00
conn.send(chunk)
2024-02-18 17:26:04 +00:00
if len(buffered) > buffer_size*2:
2024-02-20 02:03:25 +00:00
buffered = buffered[-buffer_size*2:]
2024-02-17 05:40:33 +00:00
i += 1
2024-02-17 05:26:27 +00:00
2024-02-22 08:16:07 +00:00
# when blocked
if is_http_403:
print ("[*] Blocked the request by remote server: %s" % (webserver.decode(client_encoding)))
2024-02-23 05:06:01 +00:00
def bypass_callback(response, *args, **kwargs):
if response.status_code != 200:
conn.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n{\"status\":403}")
return
# https://stackoverflow.com/questions/20658572/python-requests-print-entire-http-request-raw
format_headers = lambda d: '\r\n'.join(f'{k}: {v}' for k, v in d.items())
2024-02-23 06:02:14 +00:00
first_data = textwrap.dedent('HTTP/1.1 {res.status_code} {res.reason}\r\n{reshdrs}\r\n\r\n').format(
2024-02-23 05:06:01 +00:00
res=response,
reshdrs=format_headers(response.headers),
).encode(client_encoding)
conn.send(first_data)
for chunk in response.iter_content(chunk_size=buffer_size):
conn.send(chunk)
if is_ssl and method == b'GET':
print ("[*] Trying to bypass blocked request...")
2024-02-23 06:02:14 +00:00
remote_url = "%s://%s%s" % (scheme.decode(client_encoding), webserver.decode(client_encoding), url.decode(client_encoding))
2024-03-04 09:37:44 +00:00
requests.get(remote_url, stream=True, verify=False, hooks={'response': bypass_callback})
2024-02-23 05:06:01 +00:00
else:
conn.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n{\"status\":403}")
2024-02-22 08:16:07 +00:00
sock_close(sock, is_ssl)
2024-02-17 12:08:02 +00:00
print("[*] Received %s chunks. (%s bytes per chunk)" % (str(i), str(buffer_size)))
2024-02-17 08:44:19 +00:00
2024-02-26 13:07:45 +00:00
# stateful mode
2024-02-26 08:35:58 +00:00
elif server_connection_type == "stateful":
2024-02-26 13:07:45 +00:00
2024-02-26 08:28:10 +00:00
proxy_data = {
'headers': {
2024-03-04 09:37:44 +00:00
"User-Agent": "php-httpproxy/0.1.5 (Client; Python " + python_version() + "; abuse@catswords.net)",
2024-02-26 08:28:10 +00:00
},
'data': {
"buffer_size": str(buffer_size),
"client_address": str(addr[0]),
"client_port": str(listening_port),
"client_encoding": client_encoding,
"remote_address": webserver.decode(client_encoding),
"remote_port": str(port),
"scheme": scheme.decode(client_encoding),
"datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
}
}
2024-02-26 13:07:45 +00:00
# get client address
2024-02-27 09:30:05 +00:00
print ("[*] resolving the client address...")
while len(resolved_address_list) == 0:
try:
_, query_data = jsonrpc2_encode('get_client_address')
2024-02-28 07:10:16 +00:00
query = requests.post(server_url, headers=proxy_data['headers'], data=query_data, timeout=1, auth=auth)
2024-02-27 09:30:05 +00:00
if query.status_code == 200:
result = query.json()['result']
resolved_address_list.append(result['client_address'])
print ("[*] resolved IP: %s" % (result['client_address']))
except requests.exceptions.ReadTimeout as e:
pass
proxy_data['data']['client_address'] = resolved_address_list[0]
2024-02-26 13:07:45 +00:00
# build a tunnel
2024-02-27 09:51:05 +00:00
def relay_connect(id, raw_data, proxy_data):
try:
# The tunnel connect forever until the client destroy it
2024-02-28 07:10:16 +00:00
relay = requests.post(server_url, headers=proxy_data['headers'], data=raw_data, stream=True, timeout=None, auth=auth)
2024-02-27 09:51:05 +00:00
for chunk in relay.iter_content(chunk_size=buffer_size):
2024-03-04 09:37:44 +00:00
jsondata = json.loads(chunk.decode(client_encoding, errors='ignore'))
if jsondata['jsonrpc'] == "2.0" and ("error" in jsondata):
e = jsondata['error']
print ("[*] Error received from the relay server: (%s) %s" % (str(e['code']), str(e['message'])))
2024-02-27 09:51:05 +00:00
except requests.exceptions.ReadTimeout as e:
pass
id, raw_data = jsonrpc2_encode('relay_connect', proxy_data['data'])
start_new_thread(relay_connect, (id, raw_data, proxy_data))
2024-02-26 08:28:10 +00:00
# wait for the relay
2024-02-26 13:07:45 +00:00
print ("[*] waiting for the relay... %s" % (id))
2024-02-27 09:30:05 +00:00
max_reties = 30
t = 0
while t < max_reties and not id in accepted_relay:
2024-02-26 08:28:10 +00:00
time.sleep(1)
2024-02-27 09:30:05 +00:00
t += 1
if t < max_reties:
sock = accepted_relay[id]
print ("[*] connected the relay. %s" % (id))
sendall(sock, conn, data)
else:
resolved_address_list.remove(resolved_address_list[0])
print ("[*] the relay is gone. %s" % (id))
sock_close(sock, is_ssl)
return
2024-02-17 08:44:19 +00:00
2024-02-26 08:35:58 +00:00
# get response
i = 0
buffered = b''
while True:
chunk = sock.recv(buffer_size)
if not chunk:
break
buffered += chunk
if proxy_check_filtered(buffered, webserver, port, scheme, method, url):
sock_close(sock, is_ssl)
add_filtered_host(webserver.decode(client_encoding), '127.0.0.1')
raise Exception("Filtered response")
conn.send(chunk)
if len(buffered) > buffer_size*2:
buffered = buffered[-buffer_size*2:]
i += 1
2024-02-26 13:07:45 +00:00
sock_close(sock, is_ssl)
2024-02-26 08:35:58 +00:00
print("[*] Received %s chunks. (%s bytes per chunk)" % (str(i), str(buffer_size)))
else:
2024-02-26 08:28:10 +00:00
# stateless mode
2024-02-17 05:23:51 +00:00
proxy_data = {
'headers': {
2024-03-04 09:37:44 +00:00
"User-Agent": "php-httpproxy/0.1.5 (Client; Python " + python_version() + "; abuse@catswords.net)",
2024-02-17 05:23:51 +00:00
},
'data': {
2024-02-26 02:41:19 +00:00
"buffer_size": str(buffer_size),
2024-02-26 05:11:09 +00:00
"request_data": base64.b64encode(data).decode(client_encoding),
"request_length": str(len(data)),
2024-02-26 04:07:02 +00:00
"client_address": str(addr[0]),
"client_port": str(listening_port),
2024-02-26 02:41:19 +00:00
"client_encoding": client_encoding,
2024-02-26 04:02:48 +00:00
"remote_address": webserver.decode(client_encoding),
2024-02-26 02:41:19 +00:00
"remote_port": str(port),
2024-02-17 05:23:51 +00:00
"scheme": scheme.decode(client_encoding),
"datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
}
2022-11-24 09:02:32 +00:00
}
2024-02-27 07:13:56 +00:00
_, raw_data = jsonrpc2_encode('relay_request', proxy_data['data'])
2024-02-17 05:40:33 +00:00
2024-02-17 05:23:51 +00:00
print("[*] Sending %s bytes..." % (str(len(raw_data))))
2024-02-17 05:40:33 +00:00
2024-02-17 05:23:51 +00:00
i = 0
2024-02-28 07:10:16 +00:00
relay = requests.post(server_url, headers=proxy_data['headers'], data=raw_data, stream=True, auth=auth)
2024-02-20 02:03:25 +00:00
buffered = b''
2024-02-17 05:23:51 +00:00
for chunk in relay.iter_content(chunk_size=buffer_size):
2024-02-18 16:48:15 +00:00
buffered += chunk
if proxy_check_filtered(buffered, webserver, port, scheme, method, url):
2024-02-18 16:50:43 +00:00
add_filtered_host(webserver.decode(client_encoding), '127.0.0.1')
2024-02-18 17:05:28 +00:00
raise Exception("Filtered response")
2024-02-18 16:48:15 +00:00
conn.send(chunk)
2024-02-18 17:26:04 +00:00
if len(buffered) > buffer_size*2:
2024-02-20 02:03:25 +00:00
buffered = buffered[-buffer_size*2:]
2024-02-17 05:40:33 +00:00
i += 1
2024-02-17 12:08:02 +00:00
print("[*] Received %s chunks. (%s bytes per chunk)" % (str(i), str(buffer_size)))
2022-10-05 17:19:38 +00:00
2024-02-17 05:26:27 +00:00
print("[*] Request and received. Done. %s" % (str(addr[0])))
2022-10-05 17:19:38 +00:00
conn.close()
2022-11-25 08:12:58 +00:00
except Exception as e:
2024-02-22 08:16:07 +00:00
print(traceback.format_exc())
2024-02-18 17:05:28 +00:00
print("[*] Exception on requesting the data. Cause: %s" % (str(e)))
2024-02-23 03:48:00 +00:00
conn.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n{\"status\":403}")
2022-10-05 17:19:38 +00:00
conn.close()
2024-02-18 08:16:14 +00:00
# journaling a filtered hosts
def add_filtered_host(domain, ip_address):
hosts_path = './filtered.hosts'
2024-02-17 16:49:29 +00:00
with open(hosts_path, 'r') as file:
lines = file.readlines()
domain_exists = any(domain in line for line in lines)
if not domain_exists:
lines.append(f"{ip_address}\t{domain}\n")
with open(hosts_path, 'w') as file:
file.writelines(lines)
2024-02-18 22:58:44 +00:00
2024-02-28 06:11:49 +00:00
def start(): #Main Program
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', listening_port))
sock.listen(max_connection)
print("[*] Server started successfully [ %d ]" %(listening_port))
2024-03-05 03:27:38 +00:00
except Exception as e:
print("[*] Unable to Initialize Socket:", str(e))
2024-02-28 06:11:49 +00:00
sys.exit(2)
2024-02-18 22:58:44 +00:00
2024-02-28 06:11:49 +00:00
while True:
try:
conn, addr = sock.accept() #Accept connection from client browser
data = conn.recv(buffer_size) #Recieve client data
start_new_thread(conn_string, (conn, data, addr)) #Starting a thread
except KeyboardInterrupt:
sock.close()
print("\n[*] Graceful Shutdown")
sys.exit(1)
2024-02-18 22:58:44 +00:00
2024-03-01 15:38:48 +00:00
class Extension():
extensions = []
2024-03-05 02:32:27 +00:00
2024-02-28 06:11:49 +00:00
@classmethod
def register(cls, f):
2024-03-01 15:38:48 +00:00
cls.extensions.append(f)
2024-02-20 02:03:25 +00:00
2024-02-28 06:11:49 +00:00
@classmethod
def get_filters(cls):
2024-03-01 15:38:48 +00:00
filters = []
for extension in cls.extensions:
if extension.type == "filter":
filters.append(extension)
return filters
2024-02-18 22:58:44 +00:00
2024-03-01 15:38:48 +00:00
@classmethod
2024-03-01 15:51:20 +00:00
def get_rpcmethod(cls, method):
2024-03-05 02:32:27 +00:00
for extension in cls.extensions:
2024-03-04 09:37:44 +00:00
if extension.type == "rpcmethod" and extension.method == method:
2024-03-01 15:51:20 +00:00
return extension
return None
2024-03-04 14:10:04 +00:00
@classmethod
def send_accept(cls, conn, method, success = True):
2024-03-05 02:32:27 +00:00
_, message = jsonrpc2_encode(f"{method}_accept", {
2024-03-04 14:10:04 +00:00
"success": success
})
2024-03-05 03:31:32 +00:00
conn.send(message.encode(client_encoding))
2024-03-04 14:15:39 +00:00
@classmethod
def readall(cls, conn):
data = b''
while True:
try:
chunk = conn.recv(buffer_size)
if not chunk:
break
data += chunk
except:
pass
2024-03-05 03:31:32 +00:00
2024-03-04 14:15:39 +00:00
return data
2024-03-04 14:10:04 +00:00
2024-03-01 15:51:20 +00:00
def __init__(self):
self.type = ""
self.method = ""
2024-03-04 09:37:44 +00:00
2024-02-28 06:33:04 +00:00
def test(self, filtered, data, webserver, port, scheme, method, url):
2024-03-05 03:29:27 +00:00
raise NotImplementedError
2024-02-24 16:18:21 +00:00
2024-03-04 14:00:58 +00:00
def dispatch(self, type, id, params, conn = None):
2024-03-05 03:29:27 +00:00
raise NotImplementedError
2024-03-01 15:51:20 +00:00
2022-10-05 17:19:38 +00:00
if __name__== "__main__":
2024-03-05 02:25:19 +00:00
# initalization
try:
listening_port = config('PORT', default=5555, cast=int)
_username, _password, server_url = extract_credentials(config('SERVER_URL', default='localhost'))
server_connection_type = config('SERVER_CONNECTION_TYPE', default='stateless')
cakey = config('CA_KEY', default='ca.key')
cacert = config('CA_CERT', default='ca.crt')
certkey = config('CERT_KEY', default='cert.key')
certdir = config('CERT_DIR', default='certs/')
openssl_binpath = config('OPENSSL_BINPATH', default='openssl')
client_encoding = config('CLIENT_ENCODING', default='utf-8')
local_domain = config('LOCAL_DOMAIN', default='')
proxy_pass = config('PROXY_PASS', default='')
except KeyboardInterrupt:
print("\n[*] User has requested an interrupt")
print("[*] Application Exiting.....")
sys.exit()
2024-03-05 03:27:38 +00:00
except Exception as e:
print("[*] Failed to initialize:", str(e))
2024-03-05 02:25:19 +00:00
parser = argparse.ArgumentParser()
parser.add_argument('--max_conn', help="Maximum allowed connections", default=255, type=int)
parser.add_argument('--buffer_size', help="Number of samples to be used", default=8192, type=int)
args = parser.parse_args()
max_connection = args.max_conn
buffer_size = args.buffer_size
accepted_relay = {}
resolved_address_list = []
# set basic authentication
auth = None
if _username:
auth = HTTPBasicAuth(_username, _password)
# load extensions
2024-03-05 02:37:38 +00:00
#Extension.register(importlib.import_module("plugins.fediverse").Fediverse())
2024-02-28 06:11:49 +00:00
2024-02-28 06:33:04 +00:00
# start Caterpillar
2022-10-05 17:19:38 +00:00
start()