π΅οΈββοΈ (2-in-1) Email & Username OSINT suite featuring native MCP support for deep data extraction just from a single Email/Username. Analyzes 2720+ actively maintained scan vectors (210+ email / 2510+ username) for security research, investigations, and digital footprinting.
Python cybersecuritycybersecurity-toolsemail-osintethical-hackingethical-hacking-toolsidentificationinfosecosintosint-emailosint-toolosint-toolsosint-usernamepentestingpythonredteam-toolsredteamingthreat-intelligence
fix(cli): reject out-of-range numeric options at the CLI and MCP boundary (#732) (#739)
Abdelrhman Mohamed9121b412a31e
diff --git a/docs/FLAGS.md b/docs/FLAGS.mdindex 3e47930..bea7048 100644--- a/docs/FLAGS.md+++ b/docs/FLAGS.md@@ -12,7 +12,7 @@| `--cross-scan` | After the scan, follow the usernames, links and email addresses its results expose and scan those too (see [CROSS_SCAN.md](CROSS_SCAN.md)) || `--cross-links {all,verified,none}` | Which links a cross-scan may pivot from (default: `all`) || `--cross-emails {all,verified,none}` | Which addresses a cross-scan may scan as emails: `all` includes ones scraped from bio text, `verified` only ones a site published in its own email field, `none` scans none. Loud email modules are skipped unless `--allow-loud` (default: `verified`) |-| `--cross-depth N` | Rounds of link-following; each round pivots off the accounts the previous one found (default: 1) |+| `--cross-depth N` | Rounds of link-following; each round pivots off the accounts the previous one found; at least 1 (default: 1) || `--cross-sweep N` | Targets β usernames and addresses together β swept against every module of their kind, across all rounds; `0` disables sweeping (default: 3) || `-c, --category CATEGORY` | Scan all platforms in a specific category (comma-separated for multiple); also narrows `--cross-scan` || `-lu, --list-user` | List all available modules for username scanning |@@ -25,9 +25,9 @@| `-p, --permute PERMUTE` | Generate username permutations using a pattern/suffix || `-P, --proxy-file FILE` | Use proxies from file (one per line). Tip: Combine with `--no-pdf-media` to save proxy bandwidth || `--validate-proxies` | Validate proxies before scanning (tests against google.com) |-| `-s, --stop STOP` | Limit the number of permutations generated |-| `-d, --delay DELAY` | Delay (in seconds) between requests |-| `-t, --timeout TIMEOUT` | Override default request timeout in seconds |+| `-s, --stop STOP` | Limit the number of permutations generated (at least 1) |+| `-d, --delay DELAY` | Delay (in seconds) between requests, 0 to 3600 |+| `-t, --timeout TIMEOUT` | Override default request timeout in seconds, above 0 and at most 3600 || `-C, --concurrency CONC` | Override default concurrency limit (must be at least 1) || `-f, --format {csv,json,pdf}`| Select output format || `--no-pdf-media` | Disable profile photo media fetching in PDF reports (conserves bandwidth on metered proxies) |diff --git a/tests/test_helpers.py b/tests/test_helpers.pyindex 58e7c3a..d75f700 100644--- a/tests/test_helpers.py+++ b/tests/test_helpers.py@@ -243,6 +243,34 @@ def test_cli_concurrency_positive_bound(run_main, capsys):assert "must be at least 1" in err_neg+ "flag, value, message",+ [+ ("--stop", "0", "must be at least 1"),+ ("--stop", "-3", "must be at least 1"),+ ("--delay", "-1", "must be at least 0"),+ ("--delay", "nan", "finite"),+ ("--delay", "inf", "finite"),+ ("--delay", "1e9", "at most"),+ ("--timeout", "0", "greater than 0"),+ ("--timeout", "-5", "greater than 0"),+ ("--timeout", "nan", "finite"),+ ("--timeout", "inf", "finite"),+ ("--timeout", "99999", "at most"),+ ("--cross-depth", "0", "must be at least 1"),+ ("--cross-depth", "-2", "must be at least 1"),+ ("--cross-sweep", "-1", "must be at least 0"),+ ("--stop", "abc", "Invalid"),+ ],+)+def test_cli_numeric_options_are_bounded(run_main, capsys, flag, value, message):+ code = run_main(["-u", "alice", flag, value, "-m", "github"])+ assert code == 2+ err = capsys.readouterr().err+ assert flag in err+ assert message in err++@patch("httpx.AsyncClient")def test_validate_proxy_all_invalid(mock_client):instance = MagicMock()diff --git a/tests/test_limits.py b/tests/test_limits.pynew file mode 100644index 0000000..8a2482e--- /dev/null+++ b/tests/test_limits.py@@ -0,0 +1,96 @@+import math+import sys++import pytest++from user_scanner.core import limits++INVALID_FLOATS = ["nan", "inf", "-inf", float("nan"), float("inf"), math.inf]+++ "check, valid",+ [+ (limits.check_stop, [1, "1", 100, sys.maxsize]),+ (limits.check_concurrency, [1, "1", 60, 10_000]),+ (limits.check_cross_depth, [1, "1", 5]),+ (limits.check_cross_sweep, [0, "0", 3, 1_000]),+ ],+)+def test_int_options_accept_their_valid_range(check, valid):+ for value in valid:+ assert check(value) == int(value)+++ "check, too_small",+ [+ (limits.check_stop, [0, -1, "0", "-5"]),+ (limits.check_concurrency, [0, -1, "-10"]),+ (limits.check_cross_depth, [0, -1, "-5"]),+ (limits.check_cross_sweep, [-1, "-2"]),+ ],+)+def test_int_options_reject_values_below_their_minimum(check, too_small):+ for value in too_small:+ with pytest.raises(ValueError, match="must be at least"):+ check(value)+++ "check",+ [limits.check_stop, limits.check_concurrency, limits.check_cross_depth, limits.check_cross_sweep],+)+def test_int_options_reject_non_integers(check):+ for value in ["abc", "", None, "1.5", 2.7, True, False, *INVALID_FLOATS]:+ with pytest.raises(ValueError):+ check(value)+++def test_stop_rejects_values_islice_cannot_take():+ with pytest.raises(ValueError, match="must be at most"):+ limits.check_stop(sys.maxsize + 1)+++def test_integral_float_is_accepted_as_int():+ assert limits.check_concurrency(4.0) == 4+++def test_delay_accepts_zero_and_bounded_values():+ for value in [0, "0", 0.0, 0.5, "2", limits.MAX_SECONDS]:+ assert limits.check_delay(value) == float(value)+++def test_timeout_accepts_positive_bounded_values():+ for value in [0.1, "1", 15, limits.MAX_SECONDS]:+ assert limits.check_timeout(value) == float(value)++[email protected]("check", [limits.check_delay, limits.check_timeout])+def test_seconds_reject_non_finite_values(check):+ for value in INVALID_FLOATS:+ with pytest.raises(ValueError, match="finite"):+ check(value)++[email protected]("check", [limits.check_delay, limits.check_timeout])+def test_seconds_reject_negative_and_huge_values(check):+ for value in [-1, "-0.5", -1e-9]:+ with pytest.raises(ValueError, match="at least 0|greater than 0"):+ check(value)+ for value in [limits.MAX_SECONDS + 1, "1e9", 1e300]:+ with pytest.raises(ValueError, match="at most"):+ check(value)+++def test_timeout_rejects_zero_but_delay_allows_it():+ with pytest.raises(ValueError, match="greater than 0"):+ limits.check_timeout(0)+ assert limits.check_delay(0) == 0.0++[email protected]("check", [limits.check_delay, limits.check_timeout])+def test_seconds_reject_non_numbers(check):+ for value in ["abc", "", None, True]:+ with pytest.raises(ValueError, match="Invalid"):+ check(value)diff --git a/tests/test_mcp_handlers.py b/tests/test_mcp_handlers.pyindex d161995..5ffde73 100644--- a/tests/test_mcp_handlers.py+++ b/tests/test_mcp_handlers.py@@ -49,6 +49,28 @@ async def test_execute_scan_invalid_concurrency():assert not _scan_lock.locked()+ "arguments, message",+ [+ ({"timeout": 0}, "greater than 0"),+ ({"timeout": -1}, "greater than 0"),+ ({"timeout": float("nan")}, "finite"),+ ({"timeout": float("inf")}, "finite"),+ ({"timeout": 99999}, "at most"),+ ({"cross_depth": 0}, "at least 1"),+ ({"cross_sweep": -1}, "at least 0"),+ ({"concurrency": True}, "Invalid concurrency value"),+ ],+)+async def test_execute_scan_rejects_out_of_range_numbers(arguments, message):+ from user_scanner.mcp.handlers import _scan_lock++ with pytest.raises(ValueError, match=message):+ await execute_scan({"username": "testuser", **arguments}, is_email=False)+ assert not _scan_lock.locked()++@pytest.mark.anyioasync def test_execute_scan_unknown_module_is_an_error():from user_scanner.mcp.handlers import _scan_lock@@ -142,6 +164,11 @@ def test_tool_schema_concurrency_minimum():conc_prop = t.inputSchema["properties"]["concurrency"]assert conc_prop["type"] == "integer"assert conc_prop["minimum"] == 1+ props = t.inputSchema["properties"]+ assert props["timeout"]["exclusiveMinimum"] == 0+ assert props["timeout"]["maximum"] == 3600+ assert props["cross_depth"]["minimum"] == 1+ assert props["cross_sweep"]["minimum"] == 0@pytest.mark.anyiodiff --git a/user_scanner/__main__.py b/user_scanner/__main__.pyindex 3c3b6b0..09f2b72 100644--- a/user_scanner/__main__.py+++ b/user_scanner/__main__.py@@ -50,6 +50,7 @@ from user_scanner.core.hudson import run_hudson_scanfrom user_scanner.utils.update import update_selffrom user_scanner.utils.updater_logic import check_for_updatesfrom user_scanner.core.loud_prompt import check_loud_module_permission+from user_scanner.core import limitsfrom user_scanner.core.patterns import expand_patterns_random, count_patterns# Color configs@@ -62,6 +63,19 @@ X = Fore.RESETMAX_PERMUTATIONS_LIMIT = 100+def _arg_type(check):+ """Wrap a ``limits`` check as an argparse ``type``, so a bad value is a usage error."""++ def convert(text):+ try:+ return check(text)+ except ValueError as e:+ raise argparse.ArgumentTypeError(str(e)) from e++ convert.__name__ = check.__name__.removeprefix("check_")+ return convert++def _csv_names(value) -> tuple:"""Split a repeatable, comma-separated -m/-c value into names."""if not value:@@ -139,7 +153,7 @@ def main():parser.add_argument("-s","--stop",- type=int,+ type=_arg_type(limits.check_stop),default=MAX_PERMUTATIONS_LIMIT,help="Limit permutations",)@@ -147,19 +161,19 @@ def main():parser.add_argument("-t","--timeout",- type=float,+ type=_arg_type(limits.check_timeout),help="Override default request timeout in seconds",)parser.add_argument("-C","--concurrency",- type=int,+ type=_arg_type(limits.check_concurrency),help="Override default concurrency limit (minimum: 1, default: 60 for username, 25 for email scan)",)parser.add_argument(- "-d", "--delay", type=float, default=0, help="Delay between requests"+ "-d", "--delay", type=_arg_type(limits.check_delay), default=0, help="Delay between requests")parser.add_argument("-f", "--format", choices=["csv", "json", "pdf"], help="Output format")@@ -225,7 +239,7 @@ def main():parser.add_argument("--cross-depth",- type=int,+ type=_arg_type(limits.check_cross_depth),default=DEFAULT_DEPTH,help="Rounds of link-following. Each round pivots off the accounts the previous "f"one found, reaching handles only a chain of links names (default: {DEFAULT_DEPTH})",@@ -233,7 +247,7 @@ def main():parser.add_argument("--cross-sweep",- type=int,+ type=_arg_type(limits.check_cross_sweep),default=DEFAULT_SWEEP,metavar="N",help="Targets β usernames and addresses together β a cross-scan sweeps against "@@ -261,8 +275,6 @@ def main():set_global_timeout(args.timeout)if args.concurrency is not None:- if args.concurrency < 1:- parser.error(f"argument -C/--concurrency: must be at least 1, got {args.concurrency}")from user_scanner.core.email_orchestrator import set_concurrency as set_email_concurrencyfrom user_scanner.core.orchestrator import set_concurrency as set_user_concurrencyset_email_concurrency(args.concurrency)diff --git a/user_scanner/core/limits.py b/user_scanner/core/limits.pynew file mode 100644index 0000000..859aeea--- /dev/null+++ b/user_scanner/core/limits.py@@ -0,0 +1,91 @@+"""Bounds for the numeric scan options, shared by the CLI and the MCP server.++Every public entry point validates these values itself instead of relying on+what a downstream library happens to do with them: ``islice`` raises on a+negative stop, ``time.sleep`` on a negative delay, and a falsy timeout is+silently replaced by the default (``get_global_timeout() or 15.0``).++Each check returns the normalized value or raises ``ValueError`` with a+message that names the option, so the CLI can turn it into an argparse+usage error and the MCP server can return it to the client unchanged.+"""++import math+import sys+from typing import Any, Optional++# Longest timeout or delay accepted, in seconds. A larger value is far more+# likely a typo (milliseconds, an extra zero) than an intended hour-long wait.+MAX_SECONDS = 3600.0+++def check_int(name: str, value: Any, minimum: int, maximum: Optional[int] = None) -> int:+ """Return ``value`` as an int in ``[minimum, maximum]``.++ Accepts ints and integral numeric strings. Booleans and non-integral+ floats are rejected rather than truncated, so ``2.7`` never becomes 2.+ """+ if isinstance(value, bool):+ raise ValueError(f"Invalid {name} value: {value!r}")+ if isinstance(value, float):+ if not value.is_integer():+ raise ValueError(f"Invalid {name} value: {value!r}")+ value = int(value)+ try:+ number = int(value)+ except (TypeError, ValueError) as e:+ raise ValueError(f"Invalid {name} value: {value!r}") from e+ if number < minimum:+ raise ValueError(f"{name.capitalize()} must be at least {minimum}, got {number}")+ if maximum is not None and number > maximum:+ raise ValueError(f"{name.capitalize()} must be at most {maximum}, got {number}")+ return number+++def check_seconds(name: str, value: Any, *, allow_zero: bool) -> float:+ """Return ``value`` as a finite number of seconds, at most ``MAX_SECONDS``.++ ``allow_zero`` separates a delay, where 0 means "no delay", from a+ timeout, where 0 would mean "fail every request immediately".+ """+ if isinstance(value, bool):+ raise ValueError(f"Invalid {name} value: {value!r}")+ try:+ seconds = float(value)+ except (TypeError, ValueError) as e:+ raise ValueError(f"Invalid {name} value: {value!r}") from e+ if not math.isfinite(seconds):+ raise ValueError(f"{name.capitalize()} must be a finite number of seconds, got {value!r}")+ if seconds < 0 or (seconds == 0 and not allow_zero):+ bound = "at least 0" if allow_zero else "greater than 0"+ raise ValueError(f"{name.capitalize()} must be {bound} seconds, got {value!r}")+ if seconds > MAX_SECONDS:+ raise ValueError(f"{name.capitalize()} must be at most {MAX_SECONDS:g} seconds, got {value!r}")+ return seconds+++def check_stop(value: Any) -> int:+ """Permutation limit: at least one target must be scanned."""+ return check_int("stop", value, 1, sys.maxsize)+++def check_delay(value: Any) -> float:+ return check_seconds("delay", value, allow_zero=True)+++def check_timeout(value: Any) -> float:+ return check_seconds("timeout", value, allow_zero=False)+++def check_concurrency(value: Any) -> int:+ return check_int("concurrency", value, 1)+++def check_cross_depth(value: Any) -> int:+ """Rounds of link-following; ``run_cross_scan`` always runs at least one."""+ return check_int("cross depth", value, 1)+++def check_cross_sweep(value: Any) -> int:+ """Targets swept against every module; 0 disables sweeping."""+ return check_int("cross sweep", value, 0)diff --git a/user_scanner/mcp/handlers.py b/user_scanner/mcp/handlers.pyindex 87c0fd3..248a14b 100644--- a/user_scanner/mcp/handlers.py+++ b/user_scanner/mcp/handlers.py@@ -7,6 +7,7 @@ import sysimport mcp.types as typesfrom typing import Any+from user_scanner.core import limitsfrom user_scanner.core.formatter import into_jsonfrom user_scanner.core.helpers import (find_module,@@ -144,13 +145,13 @@ async def execute_scan(arguments: dict, is_email: bool) -> list[types.TextContenif category and module_name:raise ValueError("Cannot specify both 'category' and 'module'. Choose one.")+ # The same bounds the CLI enforces (user_scanner/core/limits.py)if concurrency is not None:- try:- conc_val = int(concurrency)- except (ValueError, TypeError) as e:- raise ValueError(f"Invalid concurrency value: {concurrency}") from e- if conc_val < 1:- raise ValueError(f"Concurrency must be at least 1, got {concurrency}")+ concurrency = limits.check_concurrency(concurrency)+ if timeout is not None:+ timeout = limits.check_timeout(timeout)+ cross_depth = limits.check_cross_depth(cross_depth)+ cross_sweep = limits.check_cross_sweep(cross_sweep)# Normalise module name the same way the CLI does (__main__.py:518)if module_name:diff --git a/user_scanner/mcp/schemas.py b/user_scanner/mcp/schemas.pyindex 6ff0d41..61488ac 100644--- a/user_scanner/mcp/schemas.py+++ b/user_scanner/mcp/schemas.py@@ -37,6 +37,7 @@ def get_tool_list() -> list[types.Tool]:},"cross_depth": {"type": "integer",+ "minimum": 1,"description": ("How deep the recursive link-following should go. Default: 1. ""Increase for deeper but slower investigations."@@ -44,6 +45,7 @@ def get_tool_list() -> list[types.Tool]:},"cross_sweep": {"type": "integer",+ "minimum": 0,"description": ("How many targets the cross-scan should automatically sweep ""against all modules. Default: 3. Set to 0 to only scan sites "@@ -98,6 +100,8 @@ def get_tool_list() -> list[types.Tool]:},"timeout": {"type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 3600,"description": ("Override default request timeout in seconds. Useful if the ""target sites are slow or you are using slow proxies."