diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a253274..bfe64a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,15 +1,20 @@ # CI: run the test suites on every push to main and every PR targeting it. # # This repo is a collection of standalone tools, each with its own -# requirements.txt. Two of them have real pytest suites: +# requirements.txt. Seven of them have real pytest suites: # # FileGuard-AES-SHA256/test_main.py -- encryption, hashing, key handling # network-sniffer/test_sniffer.py -- detection database and detectors +# HeaderScan/test_analyzer.py -- HTTP header checkers + scoring +# JWTInspect/tests/test_parser.py -- JWT parsing (offline) +# HashDetect/test_detector.py -- hash-type identification +# PortMap/test_scanner.py -- service/risk maps, IP checks +# DNSAudit/test_scorer.py -- DNS category scoring + grade caps # -# The other sub-projects have no tests. Their API test files under -# APIGuard/tests/ are OWASP API Security Top 10 test definitions -# (api1_bola.py, api7_ssrf.py, ...), not pytest modules, and are not -# collected here. +# HeaderScan/test.yml is a manual workflow, not a test suite. Their API +# test files under APIGuard/tests/ are OWASP API Security Top 10 test +# definitions (api1_bola.py, api7_ssrf.py, ...), not pytest modules, and +# are not collected here. # # The suites need no network and no display: tkinter is imported by # FileGuard's main.py but never opens a window in the tested code paths. @@ -42,9 +47,9 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - python -m pip install cryptography pytest + python -m pip install cryptography pytest requests rich flask - name: Run test suites run: | - python -m pytest FileGuard-AES-SHA256/test_main.py -v - python -m pytest network-sniffer/test_sniffer.py -v + python -m pytest FileGuard-AES-SHA256/test_main.py HeaderScan/test_analyzer.py HashDetect/test_detector.py PortMap/test_scanner.py DNSAudit/test_scorer.py -v + python -m pytest network-sniffer/test_sniffer.py JWTInspect/tests/test_parser.py -v diff --git a/DNSAudit/test_scorer.py b/DNSAudit/test_scorer.py new file mode 100644 index 0000000..5ebe8e4 --- /dev/null +++ b/DNSAudit/test_scorer.py @@ -0,0 +1,53 @@ +"""Tests for DNSAudit scorer. No network.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).parent)) +from scorer import DNSScorer, score_audit, Grade, MAX_RAW_SCORE, NUM_CATEGORIES + +class TestGrade: + def test_boundaries(self): + cases = {100: "A+", 95: "A+", 94: "A", 85: "A", 84: "B", 70: "B", + 69: "C", 50: "C", 49: "D", 30: "D", 29: "F", 0: "F"} + for pct, label in cases.items(): + assert Grade.from_percentage(pct).label == label + def test_clamped(self): + assert Grade.from_percentage(-5).label == "F" + assert Grade.from_percentage(150).label == "A+" + +class TestCategoryDeductions: + def test_critical_deducts_4(self): + s = DNSScorer("example.com") + s.add_finding("SPF", "CRITICAL", "Bad SPF") + assert s.categories["SPF"].final_score == 6.0 + def test_high_deducts_2(self): + s = DNSScorer("example.com") + s.add_finding("SPF", "HIGH", "Bad SPF") + assert s.categories["SPF"].final_score == 8.0 + def test_low_deducts_0(self): + s = DNSScorer("example.com") + s.add_finding("SPF", "LOW", "Note") + assert s.categories["SPF"].final_score == 10.0 + def test_unknown_category_raises(self): + s = DNSScorer("example.com") + try: + s.add_finding("NOPE", "HIGH", "x") + assert False, "should raise" + except ValueError: + pass + +class TestCalculate: + def test_clean_audit_a_plus(self): + r = DNSScorer("example.com").calculate() + assert r.grade == "A+" and r.raw_total == MAX_RAW_SCORE + assert len(r.categories) == NUM_CATEGORIES + def test_zone_transfer_cap_f(self): + r = score_audit("example.com", {"Zone Transfer": [ + {"severity": "CRITICAL", "description": "Zone transfer is open"}]}) + assert r.grade == "F" + assert any("Zone Transfer" in c for c in r.caps_applied) + def test_no_email_auth_cap_d(self): + r = score_audit("example.com", { + "SPF": [{"severity": "HIGH", "description": "No SPF record"}], + "DKIM": [{"severity": "HIGH", "description": "No DKIM record"}], + "DMARC": [{"severity": "HIGH", "description": "No DMARC record"}]}) + assert r.grade == "D" diff --git a/HashDetect/detector.py b/HashDetect/detector.py index 235b54d..2fb29e5 100644 --- a/HashDetect/detector.py +++ b/HashDetect/detector.py @@ -121,7 +121,29 @@ def detect_hash(hash_input: str) -> DetectionResult: is_valid_hex=False, is_base64=False, error="Empty input") - normalized = hash_input.strip().lower() + stripped = hash_input.strip() + normalized = stripped.lower() + + # Bcrypt/Argon2 use $-prefixed encodings ($2b$12$..., $argon2id$...) which + # are neither hex nor base64. Match them against the raw input before the + # hex/base64 gate, otherwise they always return "not valid hex or base64". + for name, _length, pattern, category, crackable, note in HASH_TYPES: + if name == "bcrypt" and len(stripped) == 60 and re.match(r"^\$2[ab]\$\d{2}$", stripped[:7]): + # $2b$12$ prefix + 53 chars: use the table pattern literally (raw, not lowercased) + if re.match(r"^\$2[ab]\$\d{2}\$.{53}$", stripped): + return DetectionResult( + input_hash=hash_input, normalized_hash=normalized, + is_valid_hex=False, is_base64=False, + matches=[HashMatch(name="bcrypt", confidence=Confidence.HIGH.value, + length=60, category=category.value, + crackable=crackable, note=note)]) + elif name in ("bcrypt", "Argon2") and re.match(pattern, stripped): + return DetectionResult( + input_hash=hash_input, normalized_hash=normalized, + is_valid_hex=False, is_base64=False, + matches=[HashMatch(name=name, confidence=Confidence.HIGH.value, + length=len(stripped), category=category.value, + crackable=crackable, note=note)]) # Check if it's base64-encoded (not a hash) is_b64 = _is_base64(hash_input.strip()) and not _is_hex(normalized) diff --git a/HashDetect/test_detector.py b/HashDetect/test_detector.py new file mode 100644 index 0000000..da16d66 --- /dev/null +++ b/HashDetect/test_detector.py @@ -0,0 +1,44 @@ +"""Tests for HashDetect detector. No network.""" +import hashlib +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).parent)) +from detector import detect_hash, _is_hex, _is_base64 + +class TestPrimitives: + def test_is_hex(self): + assert _is_hex("deadbeef") and _is_hex("ABC123") + assert not _is_hex("nothex!") + def test_is_base64(self): + assert _is_base64("aGVsbG8=") + assert not _is_base64("ab") # too short + +class TestDetect: + def test_empty(self): + r = detect_hash("") + assert r.error == "Empty input" + def test_non_hex_error(self): + r = detect_hash("not-a-hash!!!") + assert r.error == "Input is not valid hex or base64" + def test_md5(self): + md5 = hashlib.md5(b"hello").hexdigest() # 32 hex chars + names = {m.name for m in detect_hash(md5).matches} + assert "MD5" in names + def test_sha256(self): + sha = hashlib.sha256(b"hello").hexdigest() # 64 hex chars + names = {m.name for m in detect_hash(sha).matches} + assert "SHA-256" in names + def test_sha1(self): + sha1 = hashlib.sha1(b"hello").hexdigest() # 40 hex chars + names = {m.name for m in detect_hash(sha1).matches} + assert "SHA-1" in names + def test_sha512(self): + sha512 = hashlib.sha512(b"hello").hexdigest() # 128 hex chars + names = {m.name for m in detect_hash(sha512).matches} + assert "SHA-512" in names + def test_bcrypt(self): + # Real bcrypt is 60 chars: $2b$12$ + 53 chars (22-char salt + 31-char hash) + bc = "$2b$12$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ12345" + assert len(bc) == 60 + r = detect_hash(bc) + assert "bcrypt" in {m.name for m in r.matches} diff --git a/HeaderScan/test_analyzer.py b/HeaderScan/test_analyzer.py new file mode 100644 index 0000000..cb2858a --- /dev/null +++ b/HeaderScan/test_analyzer.py @@ -0,0 +1,84 @@ +"""Tests for HeaderScan pure checkers and scoring. No network.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).parent)) +from analyzer import ( + HEADER_WEIGHTS, TOTAL_WEIGHT, RiskLevel, Grade, + _check_hsts, _check_csp, _check_x_frame_options, + _check_x_content_type_options, _check_referrer_policy, + _check_permissions_policy, _check_xss_protection, + _check_cache_control, _check_set_cookie, _check_server_header, + _normalize_url, _compute_grade, +) + +class TestWeights: + def test_weights_sum_100(self): + assert TOTAL_WEIGHT == 100 + assert sum(HEADER_WEIGHTS.values()) == 100 + +class TestHSTS: + def test_missing_is_critical(self): + r = _check_hsts({}) + assert (r.present, r.risk) == (False, RiskLevel.CRITICAL.value) + def test_short_max_age_warning(self): + r = _check_hsts({"Strict-Transport-Security": "max-age=3600"}) + assert r.risk == RiskLevel.WARNING.value + def test_long_max_age_safe(self): + r = _check_hsts({"Strict-Transport-Security": "max-age=63072000; includeSubDomains"}) + assert r.risk == RiskLevel.SAFE.value + +class TestCSP: + def test_missing_critical(self): + assert _check_csp({}).risk == RiskLevel.CRITICAL.value + def test_unsafe_inline_warning(self): + r = _check_csp({"Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'"}) + assert r.risk == RiskLevel.WARNING.value + def test_strict_csp_safe(self): + r = _check_csp({"Content-Security-Policy": "default-src 'self'"}) + assert r.risk == RiskLevel.SAFE.value + +class TestFrameAndNosniffReferrer: + def test_frame_deny_safe(self): + assert _check_x_frame_options({"X-Frame-Options": "DENY"}).risk == RiskLevel.SAFE.value + def test_frame_missing_critical(self): + assert _check_x_frame_options({}).risk == RiskLevel.CRITICAL.value + def test_nosniff_safe(self): + assert _check_x_content_type_options({"X-Content-Type-Options": "nosniff"}).risk == RiskLevel.SAFE.value + def test_nosniff_missing_warning(self): + assert _check_x_content_type_options({}).risk == RiskLevel.WARNING.value + def test_referrer_safe_values(self): + for v in ["no-referrer", "strict-origin-when-cross-origin", "same-origin", "origin"]: + assert _check_referrer_policy({"Referrer-Policy": v}).risk == RiskLevel.SAFE.value + def test_permissions_missing_warning(self): + assert _check_permissions_policy({}).risk == RiskLevel.WARNING.value + def test_permissions_present_safe(self): + r = _check_permissions_policy({"Permissions-Policy": "camera=(), microphone=()"}) + assert r.risk == RiskLevel.SAFE.value + def test_xss_zero_safe(self): + assert _check_xss_protection({"X-XSS-Protection": "0"}).risk == RiskLevel.SAFE.value + +class TestCacheCookieServer: + def test_cache_no_store_safe(self): + assert _check_cache_control({"Cache-Control": "no-store"}).risk == RiskLevel.SAFE.value + def test_cookie_missing_flags_critical(self): + r = _check_set_cookie({"Set-Cookie": "sid=1"}) + assert r.risk == RiskLevel.CRITICAL.value + def test_cookie_secure_safe(self): + r = _check_set_cookie({"Set-Cookie": "sid=1; Secure; HttpOnly; SameSite=Strict"}) + assert r.risk == RiskLevel.SAFE.value + def test_server_version_leak_warning(self): + r = _check_server_header({"Server": "Apache/2.4.1"}) + assert r.risk == RiskLevel.WARNING.value + def test_server_absent_safe(self): + assert _check_server_header({}).risk == RiskLevel.SAFE.value + +class TestGradeAndUrl: + def test_grades(self): + assert (_compute_grade(95), _compute_grade(80), _compute_grade(60), _compute_grade(10)) == ( + Grade.A, Grade.B, Grade.C, Grade.F) + def test_boundary_grades(self): + assert (_compute_grade(90), _compute_grade(75), _compute_grade(50), _compute_grade(49)) == ( + Grade.A, Grade.B, Grade.C, Grade.F) + def test_normalize_url(self): + assert _normalize_url("example.com") == "https://example.com" + assert _normalize_url("https://example.com/x") == "https://example.com/x" diff --git a/JWTInspect/tests/test_parser.py b/JWTInspect/tests/test_parser.py new file mode 100644 index 0000000..c3694fc --- /dev/null +++ b/JWTInspect/tests/test_parser.py @@ -0,0 +1,68 @@ +"""Tests for JWTInspect parser. No network.""" +import sys +import time +from pathlib import Path +sys.path.insert(0, str(Path(__file__).parent.parent)) +from parser import parse_jwt, forge_token, _base64url_decode, _base64url_encode, _normalize_token, format_timestamp, format_duration + +def make_token(payload, header=None, **kw): + h = header or {"alg": "HS256", "typ": "JWT"} + return forge_token(h, payload, secret=kw.get("secret", "s3cr3t"), algorithm=kw.get("alg", "HS256")) + +class TestBase64: + def test_roundtrip(self): + assert _base64url_decode(_base64url_encode(b"hi")) == b"hi" + def test_strips_padding_equals(self): + enc = _base64url_encode(b"hello") + assert "=" not in enc + def test_decode_unpadded(self): + # "hi" -> aGk (unpadded) decodes back + assert _base64url_decode("aGk") == b"hi" + +class TestNormalize: + def test_bearer_prefix(self): + assert _normalize_token("Bearer abc.def.ghi") == "abc.def.ghi" + def test_whitespace(self): + assert _normalize_token(" abc ") == "abc" + +class TestParse: + def test_valid_token(self): + now = int(time.time()) + tok = make_token({"sub": "u1", "exp": now + 3600, "iat": now}) + p = parse_jwt(tok) + assert p.errors == [] + assert p.algorithm == "HS256" + assert p.claims.sub == "u1" + assert p.is_expired is False + assert p.is_valid_time is True + def test_expired_token(self): + now = int(time.time()) + tok = make_token({"sub": "u1", "exp": now - 10}) + p = parse_jwt(tok) + assert p.is_expired is True + assert p.is_valid_time is False + assert p.expires_in is not None and p.expires_in < 0 + def test_alg_none(self): + tok = forge_token({"alg": "none"}, {"sub": "u1"}, algorithm="none") + p = parse_jwt(tok) + assert p.algorithm == "none" + def test_malformed_too_few_parts(self): + p = parse_jwt("not-a-jwt") + assert p.algorithm == "UNKNOWN" + assert p.errors and "Invalid JWT format" in p.errors[0] + def test_garbage_header_errors(self): + p = parse_jwt("!!!.!!!.xxx") + assert p.errors + def test_bearer_prefix_parses(self): + now = int(time.time()) + tok = make_token({"sub": "u2", "exp": now + 60}) + assert parse_jwt("Bearer " + tok).claims.sub == "u2" + +class TestFormat: + def test_timestamp_utc(self): + s = format_timestamp(0) + assert "1970-01-01" in s and "UTC" in s + def test_duration(self): + assert format_duration(None) == "N/A" + assert format_duration(30) == "30s" + assert format_duration(90) == "1.5m" diff --git a/PortMap/test_scanner.py b/PortMap/test_scanner.py new file mode 100644 index 0000000..1d56497 --- /dev/null +++ b/PortMap/test_scanner.py @@ -0,0 +1,35 @@ +"""Tests for PortMap scanner maps. No sockets, no network.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).parent)) +from scanner import SERVICE_MAP, RISK_MAP, PORT_PROFILES, RiskLevel, get_service_name, get_risk, is_private_ip + +class TestMaps: + def test_known_services(self): + assert get_service_name(22) == "SSH" + assert get_service_name(80) == "HTTP" + assert get_service_name(443) == "HTTPS" + def test_unknown_service(self): + assert get_service_name(59999) == "Unknown" + def test_risk_high_ports(self): + for p in [21, 23, 69, 445, 3306, 6379]: + lvl, _ = get_risk(p) + assert lvl == RiskLevel.HIGH + def test_risk_low_ports(self): + for p in [22, 53, 443]: + lvl, _ = get_risk(p) + assert lvl == RiskLevel.LOW + def test_risk_unknown_port_medium(self): + lvl, _ = get_risk(59999) + assert lvl == RiskLevel.MEDIUM + def test_profiles(self): + assert 22 in PORT_PROFILES["quick"] + assert PORT_PROFILES["full"] == list(range(1, 1025)) + +class TestPrivateIP: + def test_private(self): + assert is_private_ip("10.0.0.1") and is_private_ip("192.168.1.1") + def test_public(self): + assert not is_private_ip("8.8.8.8") + def test_invalid(self): + assert is_private_ip("not-an-ip") is False