Skip to content

Commit

Permalink
Fix the codacy notice on assertion
Browse files Browse the repository at this point in the history
  • Loading branch information
shenril committed Aug 19, 2019
1 parent 90e4887 commit 692deac
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 72 deletions.
21 changes: 15 additions & 6 deletions lib/modules/attacks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,40 @@ def process(self, start_url, crawled_urls):
raise NotImplementedError(str(self) + ": Process method not found")

def __repr__(self):
parent_module = self.__class__.__module__.split('.')[-2]
parent_module = self.__class__.__module__.split(".")[-2]
return parent_module.title()


class Attacks:
def __init__(self, start_url, crawled_urls):
self.output = Services.get('output')
self.output = Services.get("output")
self.start_url = start_url
self.crawled_urls = crawled_urls

def run(self, plugins_activated):
self.output.info('Launching attacks modules...')
self.output.info("Launching attacks modules...")
# Register the plugins from configuration
for p in plugins_activated:
currentdir = os.path.dirname(os.path.realpath(__file__))
pkgpath = os.path.dirname(currentdir + "/%s/" % p)
modules = [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
for module in modules:
importlib.import_module(".{pkg}.{mod}".format(pkg=p, mod=module), __package__)
importlib.import_module(
".{pkg}.{mod}".format(pkg=p, mod=module), __package__
)

try:
attacks = ([(p(), p().process(self.start_url, self.crawled_urls)) for p in AttackPlugin.plugins])
attacks = [
(p(), p().process(self.start_url, self.crawled_urls))
for p in AttackPlugin.plugins
]
for category, result in attacks:
if result is not None:
self.output.finding('{category} detected: {result}'.format(category=category, result=result))
self.output.finding(
"{category} detected: {result}".format(
category=category, result=result
)
)

except Exception as e:
raise (e)
29 changes: 18 additions & 11 deletions lib/modules/fingerprints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,46 +15,53 @@ def process(self, headers, content):
raise NotImplementedError(str(self) + ": Process method not found")

def __repr__(self):
parent_module = self.__class__.__module__.split('.')[-2]
parent_module = self.__class__.__module__.split(".")[-2]
return parent_module.title()


class Fingerprints:
def __init__(self, agent, proxy, redirect, timeout, url, cookie):

self.url = url
self.cookie = cookie
self.output = Services.get('output')
self.request = Services.get('request_factory')
self.output = Services.get("output")
self.request = Services.get("request_factory")

def run(self, plugins_activated):
self.output.info('Launching fingerprints modules...')
self.output.info("Launching fingerprints modules...")
# Register the plugins from configuration
for p in plugins_activated:
currentdir = os.path.dirname(os.path.realpath(__file__))
pkgpath = os.path.dirname(currentdir + "/%s/" % p)
modules = [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
for module in modules:
importlib.import_module(".{pkg}.{mod}".format(pkg=p, mod=module), __package__)
importlib.import_module(
".{pkg}.{mod}".format(pkg=p, mod=module), __package__
)
try:
# Send the recon request
resp = self.request.send(
url=self.url,
method="GET",
payload=None,
headers=None,
cookies=self.cookie
cookies=self.cookie,
)

# Pass the result over the fingerprint module for processing
fingerprints = (
[(p(), p().process(resp.headers, resp.text)) for p in FingerprintPlugin.plugins])
fingerprints = [
(p(), p().process(resp.headers, resp.text))
for p in FingerprintPlugin.plugins
]

# Display findings for each category of modules
for category, result in fingerprints:
if result is not None:
self.output.finding('{category} detected: {result}'.format(category=category, result=result))
self.output.finding(
"{category} detected: {result}".format(
category=category, result=result
)
)

except Exception as e:
except Exception:
self.output.error("Error occured\nAborting fingerprint...\n")
return
23 changes: 15 additions & 8 deletions tests/lib/config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,20 @@ def test_config_exception():

def test_valid_config_value():
settings.dns_resolver = "2.2.2.2"
assert settings.dns_resolver == "2.2.2.2"
if settings.dns_resolver != "2.2.2.2":
raise AssertionError


def test_singleton_config():
settings.dns_resolver = "9.9.9.9"
assert settings.dns_resolver == "9.9.9.9"
if settings.dns_resolver != "9.9.9.9":
raise AssertionError

settings.dns_resolver = "2.2.2.2"
assert settings.dns_resolver == "2.2.2.2"
assert settings == settings
if settings.dns_resolver != "2.2.2.2":
raise AssertionError
if settings != settings:
raise AssertionError


def test_bad_filepath_config_file():
Expand All @@ -29,8 +34,10 @@ def test_bad_filepath_config_file():


def test_yaml_config_file():
settings.from_yaml(os.path.join(os.path.dirname(__file__), 'good-config.yml'))
assert settings.dns_resolver == "8.8.8.8"
assert settings.plugins[0] == "test-plugin"
settings.from_yaml(os.path.join(os.path.dirname(__file__), "good-config.yml"))
if settings.dns_resolver != "8.8.8.8":
raise AssertionError
if settings.plugins[0] != "test-plugin":
raise AssertionError
with pytest.raises(IndexError):
assert settings.plugins[1]
settings.plugins[1]
40 changes: 26 additions & 14 deletions tests/lib/modules/attacks/test_attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@

def test_attack_plugin():
f = AttackPlugin()
assert f.level == Risk.NOISY
if f.level != Risk.NOISY:
raise AssertionError

assert hasattr(f, 'process')
if not hasattr(f, "process"):
raise AssertionError

with pytest.raises(NotImplementedError):
f.process(start_url=None, crawled_urls=None)

assert f.__repr__() == "Modules"
if f.__repr__() != "Modules":
raise AssertionError


def test_new_attack_plugin():
Expand All @@ -32,9 +35,12 @@ def process(self, start_url, crawled_urls):
pass

dangerous = DangerousAttackPlugin()
assert dangerous is not None
assert dangerous.level == Risk.DANGEROUS
assert dangerous.plugins == []
if dangerous is None:
raise AssertionError
if dangerous.level != Risk.DANGEROUS:
raise AssertionError
if dangerous.plugins != []:
raise AssertionError

class GoodAttackPlugin(AttackPlugin):
level = Risk.NO_DANGER
Expand All @@ -43,26 +49,32 @@ def process(self, start_url, crawled_urls):
pass

good = GoodAttackPlugin()
assert good is not None
assert good.level == Risk.NO_DANGER
assert good.plugins != []
assert id(good.plugins[0]) == id(GoodAttackPlugin)
if good is None:
raise AssertionError
if good.level != Risk.NO_DANGER:
raise AssertionError
if good.plugins == []:
raise AssertionError
if id(good.plugins[0]) != id(GoodAttackPlugin):
raise AssertionError


def test_attack_launcher():
# Add services container for running
Services.register("output", Output())

f = Attacks(None, None)
assert hasattr(f, 'run')
if not hasattr(f, "run"):
raise AssertionError


@pytest.mark.dangerous
def test_current_plugins():
test_url="http://localhost"
test_url = "http://localhost"
settings.from_yaml("tests/lib/config/test_attack_config.yml")
Services.register("datastore", Datastore(settings.datastore))
Services.register("logger", logging.getLogger("sitadelLog"))
Services.register("output", Output())
Services.register("request_factory",SingleRequest(url=test_url, agent="Sitadel"))
Services.register("request_factory", SingleRequest(url=test_url, agent="Sitadel"))
plugins = settings.attack_plugins
Attacks(test_url, [test_url]).run(plugins)
Attacks(test_url, [test_url]).run(plugins)
50 changes: 36 additions & 14 deletions tests/lib/modules/fingerprints/test_fingerprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@

def test_fingerprint_plugin():
f = FingerprintPlugin()
assert f.level == Risk.NO_DANGER
if f.level != Risk.NO_DANGER:
raise AssertionError

assert hasattr(f, 'process')
if not hasattr(f, "process"):
raise AssertionError

with pytest.raises(NotImplementedError):
f.process(headers=None, content=None)

assert f.__repr__() == "Modules"
if f.__repr__() != "Modules":
raise AssertionError


def test_new_fingerprint_plugin():
Expand All @@ -32,9 +35,12 @@ def process(self, headers, content):
pass

dangerous = DangerousFingerPrintPlugin()
assert dangerous is not None
assert dangerous.level == Risk.DANGEROUS
assert dangerous.plugins == []
if dangerous is None:
raise AssertionError
if dangerous.level != Risk.DANGEROUS:
raise AssertionError
if dangerous.plugins != []:
raise AssertionError

class GoodFingerPrintPlugin(FingerprintPlugin):
level = Risk.NO_DANGER
Expand All @@ -43,22 +49,38 @@ def process(self, headers, content):
pass

good = GoodFingerPrintPlugin()
assert good is not None
assert good.level == Risk.NO_DANGER
assert good.plugins != []
assert id(good.plugins[0]) == id(GoodFingerPrintPlugin)
if good is None:
raise AssertionError
if good.level != Risk.NO_DANGER:
raise AssertionError
if good.plugins == []:
raise AssertionError
if id(good.plugins[0]) != id(GoodFingerPrintPlugin):
raise AssertionError


def test_fingerprint_launcher():
Services.register("output", Output())
Services.register("request_factory", SingleRequest())
f = Fingerprints(None, None, None, None, None, None)
assert hasattr(f, 'run')
if not hasattr(f, "run"):
raise AssertionError


@pytest.mark.dangerous
def test_current_plugins():
test_url="http://localhost"
test_url = "http://localhost"
settings.from_yaml("tests/lib/config/test_fingerprint_config.yml")
Services.register("logger", logging.getLogger("sitadelLog"))
Services.register("output", Output())
Services.register("request_factory",SingleRequest(url=test_url, agent="Sitadel"))
Services.register("request_factory", SingleRequest(url=test_url, agent="Sitadel"))
plugins = settings.fingerprint_plugins
Fingerprints(agent="Sitadel",proxy=None,redirect=None,timeout=None,url=test_url,cookie=None).run(plugins)
Fingerprints(
agent="Sitadel",
proxy=None,
redirect=None,
timeout=None,
url=test_url,
cookie=None,
).run(plugins)

6 changes: 4 additions & 2 deletions tests/lib/request/test_ragent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@


def test_random_agent():
assert isinstance(RandomUserAgent(), str)
if not isinstance(RandomUserAgent(), str):
raise AssertionError
ra = RandomUserAgent()
assert "Mozilla" in ra or "Opera" in ra
if "Mozilla" not in ra or "Opera" not in ra:
raise AssertionError
37 changes: 26 additions & 11 deletions tests/lib/request/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,40 @@
import requests

from lib.request.request import SingleRequest
from lib.utils.container import Services
from lib.utils.output import Output


def test_request():
Services.register("output", Output())

r = SingleRequest()
assert hasattr(r, 'send')
if not hasattr(r, "send"):
raise AssertionError

r1 = SingleRequest(url='test', agent='agent', proxy='proxy', redirect='redirect', timeout='timeout')
assert r1.url == 'test'
assert r1.agent == 'agent'
assert r1.proxy == 'proxy'
assert r1.redirect == 'redirect'
assert r1.timeout == 'timeout'
assert isinstance(r1.ruagent, str)
r1 = SingleRequest(
url="test", agent="agent", proxy="proxy", redirect="redirect", timeout="timeout"
)
if r1.url != "test":
raise AssertionError
if r1.agent != "agent":
raise AssertionError
if r1.proxy != "proxy":
raise AssertionError
if r1.redirect != "redirect":
raise AssertionError
if r1.timeout != "timeout":
raise AssertionError
if not isinstance(r1.ruagent, str):
raise AssertionError


def test_request_send():
req = SingleRequest()
with pytest.raises(requests.exceptions.MissingSchema):
req.send(url='test')
req.send(url="test")

assert req.send(url='http://example.com').request.method == 'GET'
assert req.send(url='http://example.com', method='post').request.method == 'POST'
if req.send(url="http://example.com").request.method != "GET":
raise AssertionError
if req.send(url="http://example.com", method="post").request.method != "POST":
raise AssertionError
Loading

0 comments on commit 692deac

Please sign in to comment.