Fixes for errors by pycodestyle (except E501) to run it

pycodestyle . --ignore=E501
pull/9/head
Tanaydin Sirin 2019-04-05 16:32:45 +02:00
parent b3734a43f7
commit fe8786101a
4 changed files with 170 additions and 156 deletions

View File

@ -24,7 +24,8 @@ def analysis(path, plain):
for credential in credz:
content_pure = content.replace(' ', '')
regex = re.compile("\$" + credential + ".*?=[\"|'][^\$]+[\"|']", re.I)
credential += ".*?=[\"|'][^\\$]+[\"|']"
regex = re.compile("\\$" + credential, re.I)
matches = regex.findall(content_pure)
# If we find a variable with a constant for a given indicator
@ -35,16 +36,26 @@ def analysis(path, plain):
line_vuln = -1
splitted_content = content.split('\n')
for i in range(len(splitted_content)):
regex = re.compile("\$" + credential + ".*?=", re.I)
regex = re.compile("\\$" + credential + ".*?=", re.I)
matches = regex.findall(splitted_content[i])
if len(matches) > 0:
line_vuln = i
declaration_text = vuln_content
line_declaration = str(line_vuln)
line = str(line_vuln)
occurence = 1
display(path, payload, vuln_content, line_vuln, declaration_text, line_declaration, vuln_content, occurence, plain)
display(
path,
payload,
vuln_content,
line_vuln,
declaration_text,
line,
vuln_content,
occurence,
plain
)
# Detection of RCE/SQLI/LFI/RFI/RFU/XSS/...
for payload in payloads:
@ -55,43 +66,48 @@ def analysis(path, plain):
occurence = 0
# Security hole detected, is it protected ?
if check_protection(payload[2], vuln_content) == False:
declaration_text, line_declaration = "", ""
if not check_protection(payload[2], vuln_content):
declaration_text, line = "", ""
# Managing multiple variable in a single line/function
sentence = "".join(vuln_content)
regax = re.compile(regex_indicators[2:-2])
for vulnerable_var in regax.findall(sentence):
regex = re.compile(regex_indicators[2:-2])
for vulnerable_var in regex.findall(sentence):
false_positive = False
occurence += 1
# No declaration for $_GET, $_POST ...
if check_exception(vulnerable_var[1]) == False:
if not check_exception(vulnerable_var[1]):
# Look for the declaration of $something = xxxxx
false_positive, declaration_text, line_declaration = check_declaration(content, vulnerable_var[1], path)
false_positive, declaration_text, line = check_declaration(
content,
vulnerable_var[1],
path)
# Set false positive if protection is in the variable's declaration
false_positive = false_positive or check_protection(payload[2], declaration_text) == True
is_protected = check_protection(payload[2], declaration_text)
false_positive = is_protected if is_protected else false_positive
# Display all the vuln
line_vuln = find_line_vuln(path, payload, vuln_content, content)
line_vuln = find_line_vuln(payload, vuln_content, content)
# Check for not $dest="constant"; $dest='cste'; $dest=XX;
if not "$_" in vulnerable_var[1]:
if not "$" in declaration_text.replace(vulnerable_var[1], ''):
if "$_" not in vulnerable_var[1]:
if "$" not in declaration_text.replace(vulnerable_var[1], ''):
false_positive = True
if not false_positive:
global result_count
result_count = result_count + 1
display(path, payload, vuln_content, line_vuln, declaration_text, line_declaration, vulnerable_var[1], occurence, plain)
display(path, payload, vuln_content, line_vuln, declaration_text, line, vulnerable_var[1], occurence, plain)
# Run thru every files and subdirectories
def recursive(dir, progress, plain):
progress += 1
progress_indicator = ''
if plain: progress_indicator = ""
if plain:
progress_indicator = ""
try:
for name in os.listdir(dir):

View File

@ -2,9 +2,9 @@
# -*- coding: utf-8 -*-
import os
import re
from indicators import *
# Replace the nth occurence of a string
# Replace the nth occurrence of a string
# Inspired from https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string
def nth_replace(string, old, new, n):
if string.count(old) >= n:
@ -16,44 +16,44 @@ def nth_replace(string, old, new, n):
return string.replace(old, new)
# Display the found vulnerability with basic informations like the line
def display(path,payload,vulnerability,line,declaration_text,declaration_line, colored, occurence, plain):
# Display the found vulnerability with basic information like the line
def display(path, payload, vulnerability, line, declaration_text, declaration_line, colored, occurrence, plain):
# Potential vulnerability found : SQL Injection
header = "{}Potential vulnerability found : {}{}{}".format('' if plain else '\033[1m', '' if plain else '\033[92m', payload[1], '' if plain else '\033[0m')
# Line 25 in test/sqli.php
line = "{}{}{} in {}".format('' if plain else '\033[92m',line, '' if plain else '\033[0m', path)
line = "{}{}{} in {}".format('' if plain else '\033[92m', line, '' if plain else '\033[0m', path)
# Code : include($_GET['patisserie'])
vuln = nth_replace("".join(vulnerability), colored, "{}".format('' if plain else '\033[92m')+colored+"{}".format('' if plain else '\033[0m'), occurence)
vuln = nth_replace("".join(vulnerability), colored, "{}".format('' if plain else '\033[92m') + colored + "{}".format('' if plain else '\033[0m'), occurrence)
vuln = "{}({})".format(payload[0], vuln)
# Final Display
rows, columns = os.popen('stty size', 'r').read().split()
print("-" * (int(columns)-1))
print("-" * (int(columns) - 1))
print("Name \t{}".format(header))
print("-" * (int(columns)-1))
print("-" * (int(columns) - 1))
print("{}Line {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', line))
print("{}Code {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', vuln))
# Declared at line 1 : $dest = $_GET['who'];
if not "$_" in colored:
if "$_" not in colored:
declared = "Undeclared in the file"
if declaration_text != "":
declared = "Line n°{}{}{} : {}".format('' if plain else '\033[0;92m', declaration_line, '' if plain else '\033[0m', declaration_text)
#declared = "Line n°\033[0;{}m{}\033[0m : {}".format('0' if plain else '92', declaration_line, declaration_text)
print("{}Declaration {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', declared))
# Small delimiter
print("")
# Find the line where the vulnerability is located
def find_line_vuln(path,payload,vulnerability,content):
def find_line_vuln(payload, vulnerability, content):
content = content.split('\n')
for i in range(len(content)):
if payload[0]+'('+vulnerability[0]+vulnerability[1]+vulnerability[2]+')' in content[i]:
return str(i-1)
if payload[0] + '(' + vulnerability[0] + vulnerability[1] + vulnerability[2] + ')' in content[i]:
return str(i - 1)
return "-1"
@ -70,13 +70,14 @@ def find_line_declaration(declaration, content):
# Format the source code in order to improve the detection
def clean_source_and_format(content):
# Clean up - replace tab by space
content = content.replace(" "," ")
content = content.replace(" ", " ")
# Quickfix to detect both echo("something") and echo "something"
content = content.replace("echo ","echo(")
content = content.replace(";",");")
content = content.replace("echo ", "echo(")
content = content.replace(";", ");")
return content
# Check the line to detect an eventual protection
def check_protection(payload, match):
for protection in payload:
@ -84,52 +85,52 @@ def check_protection(payload, match):
return True
return False
# Check exception - When it's a function($SOMETHING) Match declaration $SOMETHING = ...
def check_exception(match):
exceptions = ["_GET","_REQUEST","_POST","_COOKIES","_FILES"]
is_exception = False
exceptions = ["_GET", "_REQUEST", "_POST", "_COOKIES", "_FILES"]
for exception in exceptions:
if exception in match:
return True
return False
# Check declaration
def check_declaration(content, vuln, path):
# Follow and parse include, then add it's content
regex_declaration = re.compile("(include.*?|require.*?)\([\"\'](.*?)[\"\']\)")
regex_declaration = re.compile("(include.*?|require.*?)\\([\"\'](.*?)[\"\']\\)")
includes = regex_declaration.findall(content)
# Path is the path of the current scanned file, we can use it to compute the relative include
for include in includes:
relative_include = os.path.dirname(path)+"/"
relative_include = os.path.dirname(path) + "/"
try:
path_include = relative_include + include[1]
with open(path_include, 'r') as f:
content = f.read() + content
except Exception as e:
return (False, "","")
return False, "", ""
# Extract declaration - for ($something as $somethingelse)
vulnerability = vuln[1:].replace(')', '\)').replace('(', '\(')
regex_declaration2 = re.compile("\$(.*?)([\t ]*)as(?!=)([\t ]*)\$"+vulnerability)
vulnerability = vuln[1:].replace(')', '\\)').replace('(', '\\(')
regex_declaration2 = re.compile("\\$(.*?)([\t ]*)as(?!=)([\t ]*)\\$" + vulnerability)
declaration2 = regex_declaration2.findall(content)
if len(declaration2) > 0:
return check_declaration(content, "$"+declaration2[0][0], path)
return check_declaration(content, "$" + declaration2[0][0], path)
# Extract declaration - $something = $_GET['something']
regex_declaration = re.compile("\$"+vulnerability+"([\t ]*)=(?!=)(.*)")
regex_declaration = re.compile("\\$" + vulnerability + "([\t ]*)=(?!=)(.*)")
declaration = regex_declaration.findall(content)
if len(declaration)>0:
if len(declaration) > 0:
# Check constant then return True if constant because it's false positive
declaration_text = "$"+vulnerability +declaration[0][0]+"="+declaration[0][1]
declaration_text = "$" + vulnerability + declaration[0][0] + "=" + declaration[0][1]
line_declaration = find_line_declaration(declaration_text, content)
regex_constant = re.compile("\$"+vuln[1:]+"([\t ]*)=[\t ]*?([\"\'(]*?[a-zA-Z0-9{}_\(\)@\.,!: ]*?[\"\')]*?);")
regex_constant = re.compile("\\$" + vuln[1:] + "([\t ]*)=[\t ]*?([\"\'(]*?[a-zA-Z0-9{}_\\(\\)@\\.,!: ]*?[\"\')]*?);")
false_positive = regex_constant.match(declaration_text)
if false_positive:
return (True, "","")
return (False, declaration_text,line_declaration)
return True, "", ""
return False, declaration_text, line_declaration
return (False, "","")
return False, "", ""

View File

@ -7,26 +7,23 @@
# TODO afficher toutes les modifications de la variable
import sys
import argparse
import os, re
from detection import *
from indicators import *
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dir', action ='store', dest='dir', help="Directory to analyse")
parser.add_argument('--plain', action ='store_true', dest='plain', help="No color in output")
parser.add_argument('--dir', action='store', dest='dir', help="Directory to analyse")
parser.add_argument('--plain', action='store_true', dest='plain', help="No color in output")
results = parser.parse_args()
if results.dir != None:
if results.dir is not None:
print(""" (`-') <-. (`-')_ _(`-') (`-') _
_(OO ) .-> <-. \( OO) ) .-> _ .-> ( (OO ).-> ( OO).-/
,--.(_/,-.\,--.(,--. ,--. ) ,--./ ,--/ ,--.' ,-.\-,-----.(`-')----. \ .'_ (,------.
\ \ / (_/| | |(`-') | (`-')| \ | | (`-')'.' / | .--./( OO).-. ''`'-..__) | .---'
\ / / | | |(OO ) | |OO )| . '| |)(OO \ / /_) (`-')( _) | | || | ' |(| '--.
_ \ /_)| | | | \(| '__ || |\ | | / /) || |OO ) \| |)| || | / : | .--'
\-'\ / \ '-'(_ .' | |'| | \ | `-/ /` (_' '--'\ ' '-' '| '-' / | `---.
_(OO ) .-> <-. \\( OO) ) .-> _ .-> ( (OO ).-> ( OO).-/
,--.(_/,-.\\,--.(,--. ,--. ) ,--./ ,--/ ,--.' ,-.\\-,-----.(`-')----. \\ .'_ (,------.
\\ \\ / (_/| | |(`-') | (`-')| \\ | | (`-')'.' / | .--./( OO).-. ''`'-..__) | .---'
\\ / / | | |(OO ) | |OO )| . '| |)(OO \\ / /_) (`-')( _) | | || | ' |(| '--.
_ \\ /_)| | | | \\(| '__ || |\\ | | / /) || |OO ) \\| |)| || | / : | .--'
\\-'\\ / \\ '-'(_ .' | |'| | \\ | `-/ /` (_' '--'\\ ' '-' '| '-' / | `---.
`-' `-----' `-----' `--' `--' `--' `-----' `-----' `------' `------'
Copyright @pentest_swissky """)
print("\n{}Analyzing '{}' source code{}".format('' if results.plain else '\033[1m', results.dir, '' if results.plain else '\033[0m'))
@ -34,7 +31,7 @@ if __name__ == "__main__":
if os.path.isfile(results.dir):
analysis(results.dirm, results.plain)
else:
recursive(results.dir,0, results.plain)
recursive(results.dir, 0, results.plain)
scanresults()
else:

View File

@ -2,115 +2,115 @@
# -*- coding: utf-8 -*-
# /!\ Detection Format (.*)function($vuln)(.*) matched by payload[0]+regex_indicators
regex_indicators = '\((.*?)(\$_GET\[.*?\]|\$_FILES\[.*?\]|\$_POST\[.*?\]|\$_REQUEST\[.*?\]|\$_COOKIES\[.*?\]|\$_SESSION\[.*?\]|\$(?!this|e-)[a-zA-Z0-9_]*)(.*?)\)'
regex_indicators = '\\((.*?)(\\$_GET\\[.*?\\]|\\$_FILES\\[.*?\\]|\\$_POST\\[.*?\\]|\\$_REQUEST\\[.*?\\]|\\$_COOKIES\\[.*?\\]|\\$_SESSION\\[.*?\\]|\\$(?!this|e-)[a-zA-Z0-9_]*)(.*?)\\)'
# Function_Name:String, Vulnerability_Name:String, Protection_Function:Array
payloads = [
# Remote Command Execution
["eval","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["popen","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["system","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["passthru","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["exec","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["shell_exec","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["assert","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["proc_open","Remote Command Execution",["escapeshellarg","escapeshellcmd"]],
["call_user_func","Remote Code Execution",[]],
["call_user_func_array","Remote Code Execution",[]],
["preg_replace","Remote Command Execution",["preg_quote"]],
["ereg_replace","Remote Command Execution",["preg_quote"]],
["eregi_replace","Remote Command Execution",["preg_quote"]],
["mb_ereg_replace","Remote Command Execution",["preg_quote"]],
["mb_eregi_replace","Remote Command Execution",["preg_quote"]],
["eval", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["popen", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["system", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["passthru", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["exec", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["shell_exec", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["assert", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["proc_open", "Remote Command Execution", ["escapeshellarg", "escapeshellcmd"]],
["call_user_func", "Remote Code Execution", []],
["call_user_func_array", "Remote Code Execution", []],
["preg_replace", "Remote Command Execution", ["preg_quote"]],
["ereg_replace", "Remote Command Execution", ["preg_quote"]],
["eregi_replace", "Remote Command Execution", ["preg_quote"]],
["mb_ereg_replace", "Remote Command Execution", ["preg_quote"]],
["mb_eregi_replace", "Remote Command Execution", ["preg_quote"]],
# File Inclusion / Path Traversal
["virtual","File Inclusion",[]],
["include","File Inclusion",[]],
["require","File Inclusion",[]],
["include_once","File Inclusion",[]],
["require_once","File Inclusion",[]],
["virtual", "File Inclusion", []],
["include", "File Inclusion", []],
["require", "File Inclusion", []],
["include_once", "File Inclusion", []],
["require_once", "File Inclusion", []],
["readfile","File Inclusion / Path Traversal",[]],
["file_get_contents","File Inclusion / Path Traversal",[]],
["show_source","File Inclusion / Path Traversal",[]],
["fopen","File Inclusion / Path Traversal",[]],
["file","File Inclusion / Path Traversal",[]],
["fpassthru","File Inclusion / Path Traversal",[]],
["gzopen","File Inclusion / Path Traversal",[]],
["gzfile","File Inclusion / Path Traversal",[]],
["gzpassthru","File Inclusion / Path Traversal",[]],
["readgzfile","File Inclusion / Path Traversal",[]],
["readfile", "File Inclusion / Path Traversal", []],
["file_get_contents", "File Inclusion / Path Traversal", []],
["show_source", "File Inclusion / Path Traversal", []],
["fopen", "File Inclusion / Path Traversal", []],
["file", "File Inclusion / Path Traversal", []],
["fpassthru", "File Inclusion / Path Traversal", []],
["gzopen", "File Inclusion / Path Traversal", []],
["gzfile", "File Inclusion / Path Traversal", []],
["gzpassthru", "File Inclusion / Path Traversal", []],
["readgzfile", "File Inclusion / Path Traversal", []],
# MySQL(i) SQL Injection
["mysql_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_multi_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_send_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_master_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_master_query","SQL Injection",["mysql_real_escape_string"]],
["mysql_unbuffered_query","SQL Injection",["mysql_real_escape_string"]],
["mysql_db_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli::real_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_real_query","SQL Injection",["mysql_real_escape_string"]],
["mysqli::query","SQL Injection",["mysql_real_escape_string"]],
["mysqli_query","SQL Injection",["mysql_real_escape_string"]],
["mysql_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_multi_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_send_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_master_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_master_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysql_unbuffered_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysql_db_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli::real_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_real_query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli::query", "SQL Injection", ["mysql_real_escape_string"]],
["mysqli_query", "SQL Injection", ["mysql_real_escape_string"]],
# PostgreSQL Injection
["pg_query","SQL Injection",["pg_escape_string","pg_pconnect","pg_connect"]],
["pg_send_query","SQL Injection",["pg_escape_string","pg_pconnect","pg_connect"]],
["pg_query", "SQL Injection", ["pg_escape_string", "pg_pconnect", "pg_connect"]],
["pg_send_query", "SQL Injection", ["pg_escape_string", "pg_pconnect", "pg_connect"]],
# SQLite SQL Injection
["sqlite_array_query","SQL Injection",["sqlite_escape_string"]],
["sqlite_exec","SQL Injection",["sqlite_escape_string"]],
["sqlite_query","SQL Injection",["sqlite_escape_string"]],
["sqlite_single_query","SQL Injection",["sqlite_escape_string"]],
["sqlite_unbuffered_query","SQL Injection",["sqlite_escape_string"]],
["sqlite_array_query", "SQL Injection", ["sqlite_escape_string"]],
["sqlite_exec", "SQL Injection", ["sqlite_escape_string"]],
["sqlite_query", "SQL Injection", ["sqlite_escape_string"]],
["sqlite_single_query", "SQL Injection", ["sqlite_escape_string"]],
["sqlite_unbuffered_query", "SQL Injection", ["sqlite_escape_string"]],
# PDO SQL Injection
["->arrayQuery","SQL Injection",["->prepare"]],
["->query","SQL Injection",["->prepare"]],
["->queryExec","SQL Injection",["->prepare"]],
["->singleQuery","SQL Injection",["->prepare"]],
["->querySingle","SQL Injection",["->prepare"]],
["->exec","SQL Injection",["->prepare"]],
["->execute","SQL Injection",["->prepare"]],
["->unbufferedQuery","SQL Injection",["->prepare"]],
["->real_query","SQL Injection",["->prepare"]],
["->multi_query","SQL Injection",["->prepare"]],
["->send_query","SQL Injection",["->prepare"]],
["->arrayQuery", "SQL Injection", ["->prepare"]],
["->query", "SQL Injection", ["->prepare"]],
["->queryExec", "SQL Injection", ["->prepare"]],
["->singleQuery", "SQL Injection", ["->prepare"]],
["->querySingle", "SQL Injection", ["->prepare"]],
["->exec", "SQL Injection", ["->prepare"]],
["->execute", "SQL Injection", ["->prepare"]],
["->unbufferedQuery", "SQL Injection", ["->prepare"]],
["->real_query", "SQL Injection", ["->prepare"]],
["->multi_query", "SQL Injection", ["->prepare"]],
["->send_query", "SQL Injection", ["->prepare"]],
# Cubrid SQL Injection
["cubrid_unbuffered_query","SQL Injection",["cubrid_real_escape_string"]],
["cubrid_query","SQL Injection",["cubrid_real_escape_string"]],
["cubrid_unbuffered_query", "SQL Injection", ["cubrid_real_escape_string"]],
["cubrid_query", "SQL Injection", ["cubrid_real_escape_string"]],
# MSSQL SQL Injection : Warning there is not any real_escape_string
["mssql_query","SQL Injection",["mssql_escape"]],
["mssql_query", "SQL Injection", ["mssql_escape"]],
# File Upload
["move_uploaded_file","File Upload",[]],
["move_uploaded_file", "File Upload", []],
# Cross Site Scripting
["echo","Cross Site Scripting",["htmlentities","htmlspecialchars"]],
["print","Cross Site Scripting",["htmlentities","htmlspecialchars"]],
["printf","Cross Site Scripting",["htmlentities","htmlspecialchars"]],
["echo", "Cross Site Scripting", ["htmlentities", "htmlspecialchars"]],
["print", "Cross Site Scripting", ["htmlentities", "htmlspecialchars"]],
["printf", "Cross Site Scripting", ["htmlentities", "htmlspecialchars"]],
# XPATH and LDAP
["xpath","XPATH Injection",[]],
["ldap_search","LDAP Injection",["Zend_Ldap","ldap_escape"]],
["xpath", "XPATH Injection", []],
["ldap_search", "LDAP Injection", ["Zend_Ldap", "ldap_escape"]],
# Insecure E-Mail
["mail", "Insecure E-mail",[]],
["mail", "Insecure E-mail", []],
# PHP Objet Injection
["unserialize", "PHP Object Injection",[]],
["unserialize", "PHP Object Injection", []],
# Header Injection
["header","Header Injection",[]],
["HttpMessage::setHeaders","Header Injection",[]],
["HttpRequest::setHeaders","Header Injection",[]],
["header", "Header Injection", []],
["HttpMessage::setHeaders", "Header Injection", []],
["HttpRequest::setHeaders", "Header Injection", []],
# URL Redirection
["http_redirect","URL Redirection",[]],
["HttpMessage::setResponseCode","URL Redirection",[]],
["http_redirect", "URL Redirection", []],
["HttpMessage::setResponseCode", "URL Redirection", []],
]