Prives 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prives/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import version, PackageNotFoundError
2
+
3
+ try:
4
+ __version__ = version("priv")
5
+ except PackageNotFoundError:
6
+ __version__ = "unknown"
@@ -0,0 +1,129 @@
1
+ import hashlib
2
+ import json
3
+
4
+ from importlib.resources import files
5
+
6
+
7
+ def load_sensitive_keys():
8
+ path = files("prives.db").joinpath("sensitive_keys.txt")
9
+ return {
10
+ key.strip()
11
+ for key in path.read_text(encoding="utf-8").splitlines()
12
+ if key.strip()
13
+ }
14
+
15
+
16
+ SENSITIVE_KEYS = load_sensitive_keys()
17
+
18
+
19
+ def get_content_type(response):
20
+ return response.headers.get("Content-Type", "").lower()
21
+
22
+
23
+ def get_body(response):
24
+ return response.content or b""
25
+
26
+
27
+ def get_hash(body):
28
+ return hashlib.sha256(body).hexdigest()
29
+
30
+
31
+ def parse_json(response):
32
+ try:
33
+ return True, response.json()
34
+ except ValueError:
35
+ return False, None
36
+
37
+
38
+ def extract_sensitive_keys(data, path="$"):
39
+ found = {}
40
+
41
+ if isinstance(data, dict):
42
+ for key, value in data.items():
43
+ current_path = f"{path}.{key}"
44
+
45
+ if key in SENSITIVE_KEYS:
46
+ found[current_path] = value
47
+
48
+ found.update(extract_sensitive_keys(value, current_path))
49
+
50
+ elif isinstance(data, list):
51
+ for index, value in enumerate(data):
52
+ found.update(extract_sensitive_keys(value, f"{path}[{index}]"))
53
+
54
+ return found
55
+
56
+
57
+ def analyze_sensitive_keys(baseline_data, response_data):
58
+ baseline_keys = extract_sensitive_keys(baseline_data)
59
+ response_keys = extract_sensitive_keys(response_data)
60
+
61
+ newly_exposed = {}
62
+ changed = {}
63
+ missing = {}
64
+
65
+ for path, value in response_keys.items():
66
+ if path not in baseline_keys:
67
+ newly_exposed[path] = True
68
+ elif baseline_keys[path] != value:
69
+ changed[path] = True
70
+
71
+ for path in baseline_keys:
72
+ if path not in response_keys:
73
+ missing[path] = True
74
+
75
+ return {
76
+ "baseline_count": len(baseline_keys),
77
+ "response_count": len(response_keys),
78
+ "newly_exposed": newly_exposed,
79
+ "changed": changed,
80
+ "missing": missing,
81
+ "match": not (newly_exposed or changed or missing)
82
+ }
83
+
84
+
85
+ def analyze_response(baseline, response):
86
+ baseline_body = get_body(baseline)
87
+ response_body = get_body(response)
88
+
89
+ baseline_type = get_content_type(baseline)
90
+ response_type = get_content_type(response)
91
+
92
+ baseline_json, baseline_data = parse_json(baseline)
93
+ response_json, response_data = parse_json(response)
94
+
95
+ result = {
96
+ "status_code": {
97
+ "baseline": baseline.status_code,
98
+ "response": response.status_code,
99
+ "match": baseline.status_code == response.status_code
100
+ },
101
+ "content_length": {
102
+ "baseline": len(baseline_body),
103
+ "response": len(response_body),
104
+ "match": len(baseline_body) == len(response_body)
105
+ },
106
+ "content_type": {
107
+ "baseline": baseline_type,
108
+ "response": response_type,
109
+ "match": baseline_type == response_type
110
+ },
111
+ "body": {
112
+ "type": "json" if baseline_json and response_json else "text",
113
+ "match": None
114
+ },
115
+ "sensitive_keys": None
116
+ }
117
+
118
+ if baseline_json and response_json:
119
+ result["body"]["match"] = baseline_data == response_data
120
+ result["sensitive_keys"] = analyze_sensitive_keys(
121
+ baseline_data,
122
+ response_data
123
+ )
124
+ else:
125
+ result["body"]["match"] = (
126
+ get_hash(baseline_body) == get_hash(response_body)
127
+ )
128
+
129
+ return result
prives/core/colors.py ADDED
@@ -0,0 +1,7 @@
1
+ colors = {
2
+ "red": "\033[91m",
3
+ "green": "\033[92m",
4
+ "yellow": "\033[93m",
5
+ "blue": "\033[94m",
6
+ "reset": "\033[0m"
7
+ }
@@ -0,0 +1,15 @@
1
+ import json
2
+
3
+
4
+ def export_json(findings):
5
+ return json.dumps(findings, indent=4, ensure_ascii=False)
6
+
7
+
8
+ def report(findings, output=None):
9
+ content = export_json(findings)
10
+
11
+ if output:
12
+ with open(output, "w", encoding="utf-8") as file:
13
+ file.write(content)
14
+ else:
15
+ print(content)
@@ -0,0 +1,17 @@
1
+ import requests
2
+
3
+
4
+ def send_request(task):
5
+ try:
6
+ return requests.request(
7
+ method=task["method"],
8
+ url=task["url"],
9
+ headers=task.get("headers"),
10
+ cookies=task.get("cookies"),
11
+ timeout=task.get("timeout", 10),
12
+ allow_redirects=False
13
+ )
14
+
15
+ except requests.RequestException as err:
16
+ print(f"[!] Request error: {err}")
17
+ return None
prives/core/scanner.py ADDED
@@ -0,0 +1,97 @@
1
+ from urllib.parse import urlsplit
2
+
3
+ from prives.core.colors import colors
4
+ from prives.core.tasks import GENERATORS
5
+ from prives.core.requester import send_request
6
+ from prives.core.analyzer import analyze_response
7
+
8
+
9
+ def print_stage(message):
10
+ print(f"{colors['yellow']}[+] {message}{colors['reset']}")
11
+
12
+
13
+ def print_finding(url, result):
14
+ print(f"{colors['red']}[!] Anomaly: {url}{colors['reset']}")
15
+ for key, value in result.items():
16
+ if isinstance(value, dict) and value.get("match") is False:
17
+ print(f" {key}: {value}")
18
+
19
+
20
+ def is_local_url(url):
21
+ hostname = (urlsplit(url).hostname or "").lower()
22
+ return hostname in {"localhost", "127.0.0.1", "::1"}
23
+
24
+
25
+ def start_scanner(base_request, tasks):
26
+ findings = []
27
+
28
+ print_stage("Sending baseline request")
29
+ baseline = send_request(base_request)
30
+
31
+ if baseline is None:
32
+ print_stage("Baseline request failed")
33
+ return findings
34
+
35
+ print(f"[+] Status: {baseline.status_code} | Length: {len(baseline.content)}")
36
+
37
+ grouped = {}
38
+ for task in tasks:
39
+ grouped.setdefault(task["techniques"], []).append(task)
40
+
41
+ for technique in GENERATORS:
42
+ technique_tasks = grouped.get(technique, [])
43
+
44
+ if not technique_tasks:
45
+ print_stage(f"Skipping {technique}")
46
+ continue
47
+
48
+ print_stage(f"Test {technique}")
49
+
50
+ for task in technique_tasks:
51
+ added_headers = {
52
+ key: value
53
+ for key, value in task.get("headers", {}).items()
54
+ if base_request["headers"].get(key) != value
55
+ }
56
+
57
+ if added_headers:
58
+ payload = ", ".join(f"{key}: {value}" for key, value in added_headers.items())
59
+ label = f"{task['url']} > {payload}"
60
+ else:
61
+ label = task["url"]
62
+
63
+ response = send_request(task)
64
+
65
+ if response is None:
66
+ print(label)
67
+ continue
68
+
69
+ result = analyze_response(baseline, response)
70
+
71
+ finding = {
72
+ "technique": technique,
73
+ "url": task["url"],
74
+ "headers": task.get("headers", {}),
75
+ "status_code": response.status_code,
76
+ "analysis": result
77
+ }
78
+
79
+ findings.append(finding)
80
+
81
+ anomalous = any(
82
+ isinstance(value, dict) and value.get("match") is False
83
+ for value in result.values()
84
+ )
85
+
86
+ if anomalous:
87
+ print(f"\n{colors['red']}[!] {label} - Anomaly Detection{colors['reset']}")
88
+
89
+ for key, value in result.items():
90
+ if isinstance(value, dict) and value.get("match") is False:
91
+ print(f" {key}: {value}")
92
+
93
+ print()
94
+ else:
95
+ print(label)
96
+
97
+ return findings
prives/core/tasks.py ADDED
@@ -0,0 +1,79 @@
1
+ from urllib.parse import urlsplit, urlunsplit
2
+
3
+ from prives.generators.api_version import build_api_version
4
+ from prives.generators.forwarded import build_forwarded
5
+ from prives.generators.idor import build_idor
6
+ from prives.generators.override import build_override
7
+ from prives.generators.params import build_params
8
+ from prives.generators.paths import build_paths
9
+ from prives.generators.user_agents import build_user_agents
10
+
11
+
12
+ GENERATORS = {
13
+ "IDOR": lambda url: build_idor(url),
14
+ "Path Manipulation": lambda url: build_paths(url),
15
+ "Param": lambda url: build_params(url),
16
+ "API Version": lambda url: build_api_version(url),
17
+ "Forwarded": lambda url: build_forwarded(),
18
+ "Header Override": lambda url: build_override(url),
19
+ "User-Agent": lambda url: build_user_agents(),
20
+ }
21
+
22
+
23
+ def clone_request(base_request, **overrides):
24
+ """Create a copy of the base request with the specified overrides."""
25
+ new_request = {
26
+ key: value.copy() if isinstance(value, dict) else value
27
+ for key, value in base_request.items()
28
+ }
29
+ new_request.update(overrides)
30
+ return new_request
31
+
32
+
33
+ def build_tasks(context):
34
+ tasks = []
35
+ base_request = context["request"]
36
+ config = context["config"]
37
+
38
+ url = base_request["url"]
39
+ target_id = config.get("target_id")
40
+ second_id = config.get("second_id")
41
+
42
+ parts = urlsplit(url)
43
+ root_url = urlunsplit((parts.scheme, parts.netloc, "/", "", ""))
44
+ full_path = parts.path or "/"
45
+
46
+ generators = {
47
+ "API Version": lambda: build_api_version(url),
48
+ "Forwarded": lambda: build_forwarded(),
49
+ "IDOR": lambda: build_idor(url, target_id, second_id),
50
+ "Header Override": lambda: build_override(url),
51
+ "Param": lambda: build_params(url),
52
+ "Path Manipulation": lambda: build_paths(url),
53
+ "User-Agent": lambda: build_user_agents()
54
+ }
55
+
56
+ for name, generator in generators.items():
57
+ result = generator()
58
+ payloads = result.get("payload", [])
59
+ location = result.get("location", "url")
60
+
61
+ for payload in payloads:
62
+ if name == "Header Override":
63
+ task = clone_request(base_request, url=root_url, headers={**base_request["headers"], **payload})
64
+ task["headers"] = {
65
+ key: value.replace("{path}", full_path)
66
+ for key, value in task["headers"].items()
67
+ }
68
+ elif location == "url":
69
+ task = clone_request(base_request, url=payload)
70
+ elif location == "header":
71
+ task = clone_request(base_request, headers={**base_request["headers"], **payload})
72
+ else:
73
+ continue
74
+
75
+ task["techniques"] = name
76
+ tasks.append(task)
77
+
78
+ total = len(tasks)
79
+ return total, tasks