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

View File

@ -2,9 +2,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
import re 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 # Inspired from https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string
def nth_replace(string, old, new, n): def nth_replace(string, old, new, n):
if string.count(old) >= n: if string.count(old) >= n:
@ -16,8 +16,8 @@ def nth_replace(string, old, new, n):
return string.replace(old, new) return string.replace(old, new)
# Display the found vulnerability with basic informations like the line # Display the found vulnerability with basic information like the line
def display(path,payload,vulnerability,line,declaration_text,declaration_line, colored, occurence, plain): def display(path, payload, vulnerability, line, declaration_text, declaration_line, colored, occurrence, plain):
# Potential vulnerability found : SQL Injection # 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') header = "{}Potential vulnerability found : {}{}{}".format('' if plain else '\033[1m', '' if plain else '\033[92m', payload[1], '' if plain else '\033[0m')
@ -25,7 +25,7 @@ def display(path,payload,vulnerability,line,declaration_text,declaration_line, c
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']) # 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) vuln = "{}({})".format(payload[0], vuln)
# Final Display # Final Display
@ -37,19 +37,19 @@ def display(path,payload,vulnerability,line,declaration_text,declaration_line, c
print("{}Code {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', vuln)) print("{}Code {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', vuln))
# Declared at line 1 : $dest = $_GET['who']; # Declared at line 1 : $dest = $_GET['who'];
if not "$_" in colored: if "$_" not in colored:
declared = "Undeclared in the file" declared = "Undeclared in the file"
if declaration_text != "": 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°{}{}{} : {}".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)) print("{}Declaration {} {}".format('' if plain else '\033[1m', '' if plain else '\033[0m', declared))
# Small delimiter # Small delimiter
print("") print("")
# Find the line where the vulnerability is located # 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') content = content.split('\n')
for i in range(len(content)): for i in range(len(content)):
if payload[0] + '(' + vulnerability[0] + vulnerability[1] + vulnerability[2] + ')' in content[i]: if payload[0] + '(' + vulnerability[0] + vulnerability[1] + vulnerability[2] + ')' in content[i]:
@ -77,6 +77,7 @@ def clean_source_and_format(content):
content = content.replace(";", ");") content = content.replace(";", ");")
return content return content
# Check the line to detect an eventual protection # Check the line to detect an eventual protection
def check_protection(payload, match): def check_protection(payload, match):
for protection in payload: for protection in payload:
@ -84,19 +85,20 @@ def check_protection(payload, match):
return True return True
return False return False
# Check exception - When it's a function($SOMETHING) Match declaration $SOMETHING = ... # Check exception - When it's a function($SOMETHING) Match declaration $SOMETHING = ...
def check_exception(match): def check_exception(match):
exceptions = ["_GET", "_REQUEST", "_POST", "_COOKIES", "_FILES"] exceptions = ["_GET", "_REQUEST", "_POST", "_COOKIES", "_FILES"]
is_exception = False
for exception in exceptions: for exception in exceptions:
if exception in match: if exception in match:
return True return True
return False return False
# Check declaration # Check declaration
def check_declaration(content, vuln, path): def check_declaration(content, vuln, path):
# Follow and parse include, then add it's content # 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) includes = regex_declaration.findall(content)
# Path is the path of the current scanned file, we can use it to compute the relative include # Path is the path of the current scanned file, we can use it to compute the relative include
@ -107,29 +109,28 @@ def check_declaration(content, vuln, path):
with open(path_include, 'r') as f: with open(path_include, 'r') as f:
content = f.read() + content content = f.read() + content
except Exception as e: except Exception as e:
return (False, "","") return False, "", ""
# Extract declaration - for ($something as $somethingelse) # Extract declaration - for ($something as $somethingelse)
vulnerability = vuln[1:].replace(')', '\)').replace('(', '\(') vulnerability = vuln[1:].replace(')', '\\)').replace('(', '\\(')
regex_declaration2 = re.compile("\$(.*?)([\t ]*)as(?!=)([\t ]*)\$"+vulnerability) regex_declaration2 = re.compile("\\$(.*?)([\t ]*)as(?!=)([\t ]*)\\$" + vulnerability)
declaration2 = regex_declaration2.findall(content) declaration2 = regex_declaration2.findall(content)
if len(declaration2) > 0: 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'] # Extract declaration - $something = $_GET['something']
regex_declaration = re.compile("\$"+vulnerability+"([\t ]*)=(?!=)(.*)") regex_declaration = re.compile("\\$" + vulnerability + "([\t ]*)=(?!=)(.*)")
declaration = regex_declaration.findall(content) 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 # 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) 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) false_positive = regex_constant.match(declaration_text)
if false_positive: if false_positive:
return (True, "","") return True, "", ""
return (False, declaration_text,line_declaration) return False, declaration_text, line_declaration
return (False, "","") return False, "", ""

View File

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

View File

@ -2,7 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# /!\ Detection Format (.*)function($vuln)(.*) matched by payload[0]+regex_indicators # /!\ 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 # Function_Name:String, Vulnerability_Name:String, Protection_Function:Array
payloads = [ payloads = [