bearscan 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.
- bearscan/__init__.py +6 -0
- bearscan/adapters/__init__.py +0 -0
- bearscan/adapters/base.py +91 -0
- bearscan/adapters/errors.py +6 -0
- bearscan/adapters/execution.py +95 -0
- bearscan/adapters/gitleaks.py +78 -0
- bearscan/adapters/mapping.py +65 -0
- bearscan/adapters/osv.py +116 -0
- bearscan/adapters/osv_schema.py +31 -0
- bearscan/adapters/registry.py +15 -0
- bearscan/adapters/secrets.py +58 -0
- bearscan/adapters/semgrep.py +119 -0
- bearscan/adapters/sslscan.py +158 -0
- bearscan/adapters/testssl.py +106 -0
- bearscan/adapters/trufflehog.py +62 -0
- bearscan/adapters/web.py +60 -0
- bearscan/adapters/whatweb.py +85 -0
- bearscan/agents/__init__.py +0 -0
- bearscan/agents/orchestrator.py +125 -0
- bearscan/agents/prompts.py +81 -0
- bearscan/agents/reviewer.py +128 -0
- bearscan/checks/__init__.py +0 -0
- bearscan/checks/builder.py +68 -0
- bearscan/checks/catalog/javascript.toml +125 -0
- bearscan/checks/catalog/python.toml +124 -0
- bearscan/checks/catalog/secrets.toml +174 -0
- bearscan/checks/engine.py +75 -0
- bearscan/checks/entropy.py +9 -0
- bearscan/checks/errors.py +6 -0
- bearscan/checks/files.py +142 -0
- bearscan/checks/jwt.py +32 -0
- bearscan/checks/rules.py +80 -0
- bearscan/checks/sources.py +37 -0
- bearscan/checks/spans.py +22 -0
- bearscan/cli/__init__.py +0 -0
- bearscan/cli/app.py +92 -0
- bearscan/cli/audits.py +47 -0
- bearscan/cli/observer.py +28 -0
- bearscan/core/__init__.py +0 -0
- bearscan/core/fingerprint.py +17 -0
- bearscan/core/models.py +46 -0
- bearscan/core/process.py +22 -0
- bearscan/core/redaction.py +37 -0
- bearscan/core/run.py +29 -0
- bearscan/core/severity.py +19 -0
- bearscan/core/store.py +23 -0
- bearscan/llm/__init__.py +0 -0
- bearscan/llm/base.py +27 -0
- bearscan/llm/claude_code.py +118 -0
- bearscan/llm/codex.py +110 -0
- bearscan/llm/errors.py +14 -0
- bearscan/llm/factory.py +38 -0
- bearscan/llm/http_client.py +43 -0
- bearscan/llm/json_extract.py +18 -0
- bearscan/llm/ollama.py +58 -0
- bearscan/llm/openai_compat.py +70 -0
- bearscan/report/__init__.py +0 -0
- bearscan/report/terminal.py +118 -0
- bearscan/report/theme.py +42 -0
- bearscan-0.1.0.dist-info/METADATA +239 -0
- bearscan-0.1.0.dist-info/RECORD +64 -0
- bearscan-0.1.0.dist-info/WHEEL +4 -0
- bearscan-0.1.0.dist-info/entry_points.txt +2 -0
- bearscan-0.1.0.dist-info/licenses/LICENSE +202 -0
bearscan/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import subprocess
|
|
4
|
+
from collections.abc import Callable, Container
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
|
|
9
|
+
|
|
10
|
+
from bearscan.adapters.errors import ToolError
|
|
11
|
+
from bearscan.core.models import Evidence, Finding
|
|
12
|
+
from bearscan.core.process import Runner
|
|
13
|
+
|
|
14
|
+
EvidenceFn = Callable[[str, int], Evidence | None]
|
|
15
|
+
DETAIL_CHARS = 300
|
|
16
|
+
UNSAFE_RULE_CHARS = re.compile(r"[^a-z0-9._-]+")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ToolModel(BaseModel):
|
|
20
|
+
model_config = ConfigDict(extra="ignore", frozen=True, populate_by_name=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class ToolSpec:
|
|
25
|
+
name: str
|
|
26
|
+
binaries: tuple[str, ...]
|
|
27
|
+
linux_install: str
|
|
28
|
+
macos_install: str
|
|
29
|
+
timeout_s: float
|
|
30
|
+
superseded_by: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class ToolContext:
|
|
35
|
+
target: str
|
|
36
|
+
executable: str
|
|
37
|
+
workdir: Path
|
|
38
|
+
runner: Runner
|
|
39
|
+
timeout_s: float
|
|
40
|
+
evidence: EvidenceFn | None = None
|
|
41
|
+
|
|
42
|
+
def invoke(self, args: list[str], cwd: Path | None = None) -> "subprocess.CompletedProcess[str]":
|
|
43
|
+
return self.runner([self.executable, *args], "", cwd or self.workdir, os.environ, self.timeout_s)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ToolOutcome:
|
|
48
|
+
findings: tuple[Finding, ...]
|
|
49
|
+
notes: tuple[str, ...] = ()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class Adapter:
|
|
54
|
+
spec: ToolSpec
|
|
55
|
+
run: Callable[[ToolContext], ToolOutcome]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def require_exit(
|
|
59
|
+
completed: "subprocess.CompletedProcess[str]", tool: str, accepted: Container[int] = (0,)
|
|
60
|
+
) -> None:
|
|
61
|
+
if completed.returncode not in accepted:
|
|
62
|
+
detail = (completed.stderr or completed.stdout).strip()[-DETAIL_CHARS:]
|
|
63
|
+
raise ToolError(f"{tool} exited with code {completed.returncode}: {detail}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_json[T](schema: TypeAdapter[T], text: str, tool: str) -> T:
|
|
67
|
+
try:
|
|
68
|
+
return schema.validate_json(text)
|
|
69
|
+
except ValidationError as exc:
|
|
70
|
+
raise ToolError(f"{tool} output could not be read ({exc.error_count()} problems).") from exc
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_report(path: Path, tool: str) -> str:
|
|
74
|
+
try:
|
|
75
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
76
|
+
except OSError as exc:
|
|
77
|
+
raise ToolError(f"{tool} did not write its report: {exc}") from exc
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def rule_id(tool: str, check: str) -> str:
|
|
81
|
+
return f"{tool}.{UNSAFE_RULE_CHARS.sub('-', check.lower()).strip('-') or 'finding'}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def relative_to_root(path: str, root: Path) -> str:
|
|
85
|
+
candidate = Path(path)
|
|
86
|
+
if not candidate.is_absolute():
|
|
87
|
+
return candidate.as_posix()
|
|
88
|
+
for base, item in ((root, candidate), (root.resolve(), candidate.resolve())):
|
|
89
|
+
if item.is_relative_to(base):
|
|
90
|
+
return item.relative_to(base).as_posix()
|
|
91
|
+
return candidate.as_posix()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
import tempfile
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
from bearscan.adapters.base import Adapter, EvidenceFn, ToolContext, ToolOutcome, ToolSpec
|
|
11
|
+
from bearscan.adapters.errors import ToolError, ToolSkippedError
|
|
12
|
+
from bearscan.core.models import Finding
|
|
13
|
+
from bearscan.core.process import Runner, run_command
|
|
14
|
+
from bearscan.core.run import ToolStatus
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ToolObserver(Protocol):
|
|
18
|
+
def stage(self, message: str) -> None: ...
|
|
19
|
+
|
|
20
|
+
def warning(self, message: str) -> None: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Toolbox:
|
|
25
|
+
which: Callable[[str], str | None] = shutil.which
|
|
26
|
+
runner: Runner = run_command
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class ToolsReport:
|
|
31
|
+
findings: tuple[Finding, ...]
|
|
32
|
+
statuses: tuple[ToolStatus, ...]
|
|
33
|
+
notes: tuple[str, ...]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_adapters(
|
|
37
|
+
adapters: Sequence[Adapter],
|
|
38
|
+
target: str,
|
|
39
|
+
toolbox: Toolbox,
|
|
40
|
+
observer: ToolObserver,
|
|
41
|
+
evidence: EvidenceFn | None = None,
|
|
42
|
+
) -> ToolsReport:
|
|
43
|
+
findings: list[Finding] = []
|
|
44
|
+
statuses: list[ToolStatus] = []
|
|
45
|
+
notes: list[str] = []
|
|
46
|
+
for adapter in adapters:
|
|
47
|
+
succeeded = {status.name for status in statuses if status.state == "ran"}
|
|
48
|
+
if adapter.spec.superseded_by in succeeded:
|
|
49
|
+
statuses.append(
|
|
50
|
+
ToolStatus(
|
|
51
|
+
name=adapter.spec.name, state="skipped", detail=f"covered by {adapter.spec.superseded_by}"
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
continue
|
|
55
|
+
status, outcome = _run_adapter(adapter, target, toolbox, observer, evidence)
|
|
56
|
+
statuses.append(status)
|
|
57
|
+
if outcome is not None:
|
|
58
|
+
findings.extend(outcome.findings)
|
|
59
|
+
notes.extend(outcome.notes)
|
|
60
|
+
return ToolsReport(tuple(findings), tuple(statuses), tuple(notes))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _run_adapter(
|
|
64
|
+
adapter: Adapter, target: str, toolbox: Toolbox, observer: ToolObserver, evidence: EvidenceFn | None
|
|
65
|
+
) -> tuple[ToolStatus, ToolOutcome | None]:
|
|
66
|
+
spec = adapter.spec
|
|
67
|
+
executable = locate(spec, toolbox.which)
|
|
68
|
+
if executable is None:
|
|
69
|
+
return ToolStatus(
|
|
70
|
+
name=spec.name, state="missing", detail=f"not installed; {install_hint(spec)}"
|
|
71
|
+
), None
|
|
72
|
+
observer.stage(f"Running {spec.name}")
|
|
73
|
+
try:
|
|
74
|
+
with tempfile.TemporaryDirectory(prefix="bearscan-tool-") as workdir:
|
|
75
|
+
context = ToolContext(target, executable, Path(workdir), toolbox.runner, spec.timeout_s, evidence)
|
|
76
|
+
outcome = adapter.run(context)
|
|
77
|
+
except ToolSkippedError as exc:
|
|
78
|
+
return ToolStatus(name=spec.name, state="skipped", detail=str(exc)), None
|
|
79
|
+
except subprocess.TimeoutExpired:
|
|
80
|
+
detail = f"timed out after {spec.timeout_s:.0f}s"
|
|
81
|
+
except (ToolError, OSError) as exc:
|
|
82
|
+
detail = str(exc)
|
|
83
|
+
else:
|
|
84
|
+
return ToolStatus(name=spec.name, state="ran", findings=len(outcome.findings)), outcome
|
|
85
|
+
observer.warning(f"{spec.name} failed: {detail}")
|
|
86
|
+
return ToolStatus(name=spec.name, state="failed", detail=detail), None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def locate(spec: ToolSpec, which: Callable[[str], str | None]) -> str | None:
|
|
90
|
+
return next((path for binary in spec.binaries if (path := which(binary)) is not None), None)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def install_hint(spec: ToolSpec) -> str:
|
|
94
|
+
command = spec.macos_install if sys.platform == "darwin" else spec.linux_install
|
|
95
|
+
return f"to enable it: {command}"
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from pydantic import Field, TypeAdapter
|
|
4
|
+
|
|
5
|
+
from bearscan.adapters.base import (
|
|
6
|
+
ToolContext,
|
|
7
|
+
ToolModel,
|
|
8
|
+
ToolOutcome,
|
|
9
|
+
ToolSpec,
|
|
10
|
+
parse_json,
|
|
11
|
+
read_report,
|
|
12
|
+
require_exit,
|
|
13
|
+
)
|
|
14
|
+
from bearscan.adapters.secrets import SecretHit, build_secret_finding, require_git_repository
|
|
15
|
+
from bearscan.core.models import Finding
|
|
16
|
+
|
|
17
|
+
SPEC = ToolSpec(
|
|
18
|
+
name="gitleaks",
|
|
19
|
+
binaries=("gitleaks",),
|
|
20
|
+
linux_install="sudo apt install gitleaks",
|
|
21
|
+
macos_install="brew install gitleaks",
|
|
22
|
+
timeout_s=900.0,
|
|
23
|
+
)
|
|
24
|
+
REPORT_NAME = "gitleaks.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GitleaksLeak(ToolModel):
|
|
28
|
+
rule: str = Field(alias="RuleID")
|
|
29
|
+
file: str = Field(alias="File")
|
|
30
|
+
line: int = Field(default=1, alias="StartLine")
|
|
31
|
+
column: int = Field(default=1, alias="StartColumn")
|
|
32
|
+
secret: str = Field(default="", alias="Secret")
|
|
33
|
+
match: str = Field(default="", alias="Match")
|
|
34
|
+
commit: str = Field(default="", alias="Commit")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
REPORT = TypeAdapter(list[GitleaksLeak])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run_gitleaks(context: ToolContext) -> ToolOutcome:
|
|
41
|
+
root = Path(context.target)
|
|
42
|
+
require_git_repository(root)
|
|
43
|
+
report = context.workdir / REPORT_NAME
|
|
44
|
+
completed = context.invoke(
|
|
45
|
+
[
|
|
46
|
+
"git",
|
|
47
|
+
"--report-format",
|
|
48
|
+
"json",
|
|
49
|
+
"--report-path",
|
|
50
|
+
str(report),
|
|
51
|
+
"--exit-code",
|
|
52
|
+
"0",
|
|
53
|
+
"--no-banner",
|
|
54
|
+
"--log-level",
|
|
55
|
+
"error",
|
|
56
|
+
str(root),
|
|
57
|
+
]
|
|
58
|
+
)
|
|
59
|
+
require_exit(completed, SPEC.name)
|
|
60
|
+
return ToolOutcome(parse_gitleaks_report(read_report(report, SPEC.name)))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_gitleaks_report(text: str) -> tuple[Finding, ...]:
|
|
64
|
+
return tuple(
|
|
65
|
+
build_secret_finding(
|
|
66
|
+
SecretHit(
|
|
67
|
+
tool=SPEC.name,
|
|
68
|
+
rule=leak.rule,
|
|
69
|
+
path=leak.file,
|
|
70
|
+
line=leak.line,
|
|
71
|
+
column=leak.column,
|
|
72
|
+
secret=leak.secret,
|
|
73
|
+
commit=leak.commit,
|
|
74
|
+
excerpt=leak.match,
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
for leak in parse_json(REPORT, text, SPEC.name)
|
|
78
|
+
)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Mapping, Sequence
|
|
3
|
+
|
|
4
|
+
from pydantic import JsonValue
|
|
5
|
+
|
|
6
|
+
from bearscan.core.severity import Severity
|
|
7
|
+
|
|
8
|
+
# Why: tools still label findings with the 2021 list; OWASP 2025 renumbered it and folded SSRF into A01.
|
|
9
|
+
OWASP_2021_TO_2025 = {
|
|
10
|
+
"A01": "A01",
|
|
11
|
+
"A02": "A04",
|
|
12
|
+
"A03": "A05",
|
|
13
|
+
"A04": "A06",
|
|
14
|
+
"A05": "A02",
|
|
15
|
+
"A06": "A03",
|
|
16
|
+
"A07": "A07",
|
|
17
|
+
"A08": "A08",
|
|
18
|
+
"A09": "A09",
|
|
19
|
+
"A10": "A01",
|
|
20
|
+
}
|
|
21
|
+
OWASP_LABEL = re.compile(r"\b(A(?:0[1-9]|10)):(2021|2025)\b")
|
|
22
|
+
CWE_LABEL = re.compile(r"\bCWE-\d+\b")
|
|
23
|
+
CVSS_BANDS = ((9.0, Severity.CRITICAL), (7.0, Severity.HIGH), (4.0, Severity.MEDIUM), (0.1, Severity.LOW))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def as_strings(value: JsonValue) -> list[str]:
|
|
27
|
+
if isinstance(value, str):
|
|
28
|
+
return [value]
|
|
29
|
+
if isinstance(value, list):
|
|
30
|
+
return [item for item in value if isinstance(item, str)]
|
|
31
|
+
return []
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def text_field(data: Mapping[str, JsonValue], key: str) -> str:
|
|
35
|
+
value = data.get(key)
|
|
36
|
+
return value if isinstance(value, str) else ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def owasp_2025(labels: Sequence[str], default: str) -> str:
|
|
40
|
+
mapped: str | None = None
|
|
41
|
+
for label in labels:
|
|
42
|
+
match = OWASP_LABEL.search(label)
|
|
43
|
+
if match is None:
|
|
44
|
+
continue
|
|
45
|
+
code, year = match.groups()
|
|
46
|
+
if year == "2025":
|
|
47
|
+
return f"{code}:2025"
|
|
48
|
+
mapped = mapped or f"{OWASP_2021_TO_2025[code]}:2025"
|
|
49
|
+
return mapped or default
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def first_cwe(labels: Sequence[str], default: str) -> str:
|
|
53
|
+
for label in labels:
|
|
54
|
+
match = CWE_LABEL.search(label)
|
|
55
|
+
if match is not None:
|
|
56
|
+
return match.group(0)
|
|
57
|
+
return default
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def severity_from_cvss(score: str) -> Severity | None:
|
|
61
|
+
try:
|
|
62
|
+
value = float(score)
|
|
63
|
+
except ValueError:
|
|
64
|
+
return None
|
|
65
|
+
return next((severity for floor, severity in CVSS_BANDS if value >= floor), None)
|
bearscan/adapters/osv.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from pydantic import Field, JsonValue, TypeAdapter
|
|
5
|
+
|
|
6
|
+
from bearscan.adapters.base import (
|
|
7
|
+
ToolContext,
|
|
8
|
+
ToolModel,
|
|
9
|
+
ToolOutcome,
|
|
10
|
+
ToolSpec,
|
|
11
|
+
parse_json,
|
|
12
|
+
relative_to_root,
|
|
13
|
+
require_exit,
|
|
14
|
+
rule_id,
|
|
15
|
+
)
|
|
16
|
+
from bearscan.adapters.mapping import as_strings, first_cwe, severity_from_cvss, text_field
|
|
17
|
+
from bearscan.adapters.osv_schema import OsvGroup, OsvPackage, OsvVulnerability
|
|
18
|
+
from bearscan.core.fingerprint import compute_fingerprint
|
|
19
|
+
from bearscan.core.models import Evidence, Finding, Location
|
|
20
|
+
from bearscan.core.redaction import clip_text
|
|
21
|
+
from bearscan.core.severity import Severity
|
|
22
|
+
|
|
23
|
+
SPEC = ToolSpec(
|
|
24
|
+
name="osv-scanner",
|
|
25
|
+
binaries=("osv-scanner",),
|
|
26
|
+
linux_install="download it from https://github.com/google/osv-scanner/releases",
|
|
27
|
+
macos_install="brew install osv-scanner",
|
|
28
|
+
timeout_s=900.0,
|
|
29
|
+
)
|
|
30
|
+
DEPENDENCY_CATEGORY = "dependencies"
|
|
31
|
+
VULNERABILITIES_FOUND = 1
|
|
32
|
+
NO_PACKAGES_FOUND = 128
|
|
33
|
+
NO_PACKAGES_NOTE = "osv-scanner found no lockfiles or manifests to check."
|
|
34
|
+
ADVISORY_SEVERITIES = {
|
|
35
|
+
"CRITICAL": Severity.CRITICAL,
|
|
36
|
+
"HIGH": Severity.HIGH,
|
|
37
|
+
"MODERATE": Severity.MEDIUM,
|
|
38
|
+
"MEDIUM": Severity.MEDIUM,
|
|
39
|
+
"LOW": Severity.LOW,
|
|
40
|
+
}
|
|
41
|
+
MAX_TITLE_CHARS = 120
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class OsvResult(ToolModel):
|
|
45
|
+
source: dict[str, JsonValue] = Field(default_factory=dict)
|
|
46
|
+
packages: list[OsvPackage] = Field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class OsvReport(ToolModel):
|
|
50
|
+
results: list[OsvResult] = Field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
REPORT = TypeAdapter(OsvReport)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def run_osv_scanner(context: ToolContext) -> ToolOutcome:
|
|
57
|
+
root = Path(context.target)
|
|
58
|
+
completed = context.invoke(["scan", "source", "--format", "json", "--recursive", str(root)])
|
|
59
|
+
if completed.returncode == NO_PACKAGES_FOUND:
|
|
60
|
+
return ToolOutcome((), (NO_PACKAGES_NOTE,))
|
|
61
|
+
require_exit(completed, SPEC.name, (0, VULNERABILITIES_FOUND))
|
|
62
|
+
return ToolOutcome(tuple(parse_osv_report(completed.stdout, root)))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_osv_report(text: str, root: Path) -> Iterator[Finding]:
|
|
66
|
+
for result in parse_json(REPORT, text, SPEC.name).results:
|
|
67
|
+
source = relative_to_root(text_field(result.source, "path"), root)
|
|
68
|
+
for package in result.packages:
|
|
69
|
+
advisories = {vulnerability.id: vulnerability for vulnerability in package.vulnerabilities}
|
|
70
|
+
for group in package.groups:
|
|
71
|
+
yield _group_finding(source, package, group, advisories)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _group_finding(
|
|
75
|
+
source: str, package: OsvPackage, group: OsvGroup, advisories: dict[str, OsvVulnerability]
|
|
76
|
+
) -> Finding:
|
|
77
|
+
name, version, ecosystem = (text_field(package.package, key) for key in ("name", "version", "ecosystem"))
|
|
78
|
+
primary = group.ids[0] if group.ids else "unknown"
|
|
79
|
+
advisory = next((advisories[i] for i in group.ids if i in advisories), None)
|
|
80
|
+
fixed = _fixed_version(advisory, name) if advisory is not None else None
|
|
81
|
+
advice = f"Upgrade {name} to {fixed} or later." if fixed else f"No fixed release of {name} is listed yet."
|
|
82
|
+
summary = advisory.summary if advisory is not None and advisory.summary else primary
|
|
83
|
+
cwes = as_strings(advisory.database_specific.get("cwe_ids")) if advisory is not None else []
|
|
84
|
+
snippet = f"{name} {version} ({ecosystem})"
|
|
85
|
+
return Finding(
|
|
86
|
+
id=compute_fingerprint(rule_id(SPEC.name, primary), source, snippet, ""),
|
|
87
|
+
rule_id=rule_id(SPEC.name, primary),
|
|
88
|
+
title=clip_text(f"{name} {version}: {summary}", MAX_TITLE_CHARS),
|
|
89
|
+
category=DEPENDENCY_CATEGORY,
|
|
90
|
+
severity=_severity(group, advisory),
|
|
91
|
+
cwe=first_cwe(cwes, "CWE-1395"),
|
|
92
|
+
owasp="A03:2025",
|
|
93
|
+
location=Location(path=source, line=1, column=1),
|
|
94
|
+
evidence=Evidence(snippet=snippet, context_start=1, context=(snippet,)),
|
|
95
|
+
remediation=f"{advice} Advisories: {', '.join(sorted({*group.ids, *group.aliases}))}.",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _severity(group: OsvGroup, advisory: OsvVulnerability | None) -> Severity:
|
|
100
|
+
from_score = severity_from_cvss(group.max_severity)
|
|
101
|
+
if from_score is not None:
|
|
102
|
+
return from_score
|
|
103
|
+
label = text_field(advisory.database_specific, "severity") if advisory is not None else ""
|
|
104
|
+
return ADVISORY_SEVERITIES.get(label.upper(), Severity.MEDIUM)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _fixed_version(advisory: OsvVulnerability, name: str) -> str | None:
|
|
108
|
+
fixes = [
|
|
109
|
+
text_field(event, "fixed")
|
|
110
|
+
for affected in advisory.affected
|
|
111
|
+
if text_field(affected.package, "name") == name
|
|
112
|
+
for version_range in affected.ranges
|
|
113
|
+
for event in version_range.events
|
|
114
|
+
if text_field(event, "fixed")
|
|
115
|
+
]
|
|
116
|
+
return fixes[-1] if fixes else None
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from pydantic import Field, JsonValue
|
|
2
|
+
|
|
3
|
+
from bearscan.adapters.base import ToolModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class OsvRange(ToolModel):
|
|
7
|
+
events: list[dict[str, JsonValue]] = Field(default_factory=list)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class OsvAffected(ToolModel):
|
|
11
|
+
package: dict[str, JsonValue] = Field(default_factory=dict)
|
|
12
|
+
ranges: list[OsvRange] = Field(default_factory=list)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class OsvVulnerability(ToolModel):
|
|
16
|
+
id: str
|
|
17
|
+
summary: str = ""
|
|
18
|
+
database_specific: dict[str, JsonValue] = Field(default_factory=dict)
|
|
19
|
+
affected: list[OsvAffected] = Field(default_factory=list)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class OsvGroup(ToolModel):
|
|
23
|
+
ids: list[str] = Field(default_factory=list)
|
|
24
|
+
aliases: list[str] = Field(default_factory=list)
|
|
25
|
+
max_severity: str = ""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OsvPackage(ToolModel):
|
|
29
|
+
package: dict[str, JsonValue] = Field(default_factory=dict)
|
|
30
|
+
groups: list[OsvGroup] = Field(default_factory=list)
|
|
31
|
+
vulnerabilities: list[OsvVulnerability] = Field(default_factory=list)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from bearscan.adapters import gitleaks, osv, semgrep, sslscan, testssl, trufflehog, whatweb
|
|
2
|
+
from bearscan.adapters.base import Adapter
|
|
3
|
+
|
|
4
|
+
CODE_ADAPTERS = (
|
|
5
|
+
Adapter(gitleaks.SPEC, gitleaks.run_gitleaks),
|
|
6
|
+
Adapter(trufflehog.SPEC, trufflehog.run_trufflehog),
|
|
7
|
+
Adapter(semgrep.SPEC, semgrep.run_semgrep),
|
|
8
|
+
Adapter(osv.SPEC, osv.run_osv_scanner),
|
|
9
|
+
)
|
|
10
|
+
# Why: testssl.sh runs first so sslscan, a faster subset of it, only runs when testssl.sh is missing or fails.
|
|
11
|
+
URL_ADAPTERS = (
|
|
12
|
+
Adapter(testssl.SPEC, testssl.run_testssl),
|
|
13
|
+
Adapter(sslscan.SPEC, sslscan.run_sslscan),
|
|
14
|
+
Adapter(whatweb.SPEC, whatweb.run_whatweb),
|
|
15
|
+
)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from bearscan.adapters.base import rule_id
|
|
5
|
+
from bearscan.adapters.errors import ToolSkippedError
|
|
6
|
+
from bearscan.core.fingerprint import secret_fingerprint
|
|
7
|
+
from bearscan.core.models import Evidence, Finding, Location
|
|
8
|
+
from bearscan.core.redaction import clip_text, mask_secret
|
|
9
|
+
from bearscan.core.severity import Severity
|
|
10
|
+
|
|
11
|
+
MAX_SNIPPET_CHARS = 240
|
|
12
|
+
COMMIT_PREFIX = 8
|
|
13
|
+
REMEDIATION = (
|
|
14
|
+
"Revoke and rotate this credential first. Deleting the line does not remove it from git history: after "
|
|
15
|
+
"rotating, purge it with git filter-repo and ask collaborators to re-clone."
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class SecretHit:
|
|
21
|
+
tool: str
|
|
22
|
+
rule: str
|
|
23
|
+
path: str
|
|
24
|
+
line: int
|
|
25
|
+
column: int
|
|
26
|
+
secret: str
|
|
27
|
+
commit: str
|
|
28
|
+
excerpt: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_secret_finding(hit: SecretHit) -> Finding:
|
|
32
|
+
masked = mask_excerpt(hit.excerpt, hit.secret)
|
|
33
|
+
snippet = f"commit {hit.commit[:COMMIT_PREFIX]}: {masked}" if hit.commit else masked
|
|
34
|
+
line = max(hit.line, 1)
|
|
35
|
+
return Finding(
|
|
36
|
+
id=secret_fingerprint(hit.path, hit.secret),
|
|
37
|
+
rule_id=rule_id(hit.tool, hit.rule),
|
|
38
|
+
title=f"Secret in git history: {hit.rule}" if hit.commit else f"Secret: {hit.rule}",
|
|
39
|
+
category="secrets",
|
|
40
|
+
severity=Severity.HIGH,
|
|
41
|
+
cwe="CWE-798",
|
|
42
|
+
owasp="A07:2025",
|
|
43
|
+
location=Location(path=hit.path, line=line, column=max(hit.column, 1)),
|
|
44
|
+
evidence=Evidence(snippet=snippet, context_start=line, context=(snippet,)),
|
|
45
|
+
remediation=REMEDIATION,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def mask_excerpt(excerpt: str, secret: str) -> str:
|
|
50
|
+
if not secret or secret not in excerpt:
|
|
51
|
+
# Why: if the secret cannot be located inside the excerpt, the whole excerpt may contain it.
|
|
52
|
+
return mask_secret(excerpt or secret)
|
|
53
|
+
return clip_text(" ".join(excerpt.replace(secret, mask_secret(secret)).split()), MAX_SNIPPET_CHARS)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def require_git_repository(root: Path) -> None:
|
|
57
|
+
if not (root / ".git").exists():
|
|
58
|
+
raise ToolSkippedError("not the top of a git repository; current files are covered by bearscan rules")
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from pydantic import Field, JsonValue, TypeAdapter
|
|
4
|
+
|
|
5
|
+
from bearscan.adapters.base import (
|
|
6
|
+
EvidenceFn,
|
|
7
|
+
ToolContext,
|
|
8
|
+
ToolModel,
|
|
9
|
+
ToolOutcome,
|
|
10
|
+
ToolSpec,
|
|
11
|
+
parse_json,
|
|
12
|
+
relative_to_root,
|
|
13
|
+
require_exit,
|
|
14
|
+
rule_id,
|
|
15
|
+
)
|
|
16
|
+
from bearscan.adapters.mapping import as_strings, first_cwe, owasp_2025
|
|
17
|
+
from bearscan.core.fingerprint import compute_fingerprint
|
|
18
|
+
from bearscan.core.models import Evidence, Finding, Location
|
|
19
|
+
from bearscan.core.redaction import clip_text
|
|
20
|
+
from bearscan.core.severity import Severity
|
|
21
|
+
|
|
22
|
+
SPEC = ToolSpec(
|
|
23
|
+
name="semgrep",
|
|
24
|
+
binaries=("semgrep",),
|
|
25
|
+
linux_install="pipx install semgrep",
|
|
26
|
+
macos_install="brew install semgrep",
|
|
27
|
+
timeout_s=1800.0,
|
|
28
|
+
)
|
|
29
|
+
# Why: `--config auto` refuses to run with metrics off, so bearscan names registry rulesets explicitly.
|
|
30
|
+
RULESETS = ("p/default", "p/owasp-top-ten")
|
|
31
|
+
ACCEPTED_EXIT_CODES = (0, 1)
|
|
32
|
+
SEVERITIES = {
|
|
33
|
+
"CRITICAL": Severity.CRITICAL,
|
|
34
|
+
"ERROR": Severity.HIGH,
|
|
35
|
+
"HIGH": Severity.HIGH,
|
|
36
|
+
"WARNING": Severity.MEDIUM,
|
|
37
|
+
"MEDIUM": Severity.MEDIUM,
|
|
38
|
+
"INFO": Severity.LOW,
|
|
39
|
+
"LOW": Severity.LOW,
|
|
40
|
+
}
|
|
41
|
+
CODE_CATEGORY = "code"
|
|
42
|
+
DEFAULT_CWE = "CWE-noinfo"
|
|
43
|
+
DEFAULT_OWASP = "A06:2025"
|
|
44
|
+
MAX_TITLE_CHARS = 120
|
|
45
|
+
MAX_REMEDIATION_CHARS = 600
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SemgrepPosition(ToolModel):
|
|
49
|
+
line: int = 1
|
|
50
|
+
col: int = 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SemgrepExtra(ToolModel):
|
|
54
|
+
message: str = ""
|
|
55
|
+
severity: str = "WARNING"
|
|
56
|
+
metadata: dict[str, JsonValue] = Field(default_factory=dict)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SemgrepResult(ToolModel):
|
|
60
|
+
check_id: str
|
|
61
|
+
path: str
|
|
62
|
+
start: SemgrepPosition = Field(default_factory=SemgrepPosition)
|
|
63
|
+
extra: SemgrepExtra = Field(default_factory=SemgrepExtra)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class SemgrepReport(ToolModel):
|
|
67
|
+
results: list[SemgrepResult] = Field(default_factory=list)
|
|
68
|
+
errors: list[dict[str, JsonValue]] = Field(default_factory=list)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
REPORT = TypeAdapter(SemgrepReport)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run_semgrep(context: ToolContext) -> ToolOutcome:
|
|
75
|
+
root = Path(context.target)
|
|
76
|
+
args = ["scan", "--json", "--metrics", "off", "--disable-version-check", "--quiet"]
|
|
77
|
+
for ruleset in RULESETS:
|
|
78
|
+
args += ["--config", ruleset]
|
|
79
|
+
completed = context.invoke([*args, "."], cwd=root)
|
|
80
|
+
require_exit(completed, SPEC.name, ACCEPTED_EXIT_CODES)
|
|
81
|
+
return parse_semgrep_report(completed.stdout, root, context.evidence)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_semgrep_report(text: str, root: Path, evidence: EvidenceFn | None) -> ToolOutcome:
|
|
85
|
+
report = parse_json(REPORT, text, SPEC.name)
|
|
86
|
+
findings = (build_semgrep_finding(result, root, evidence) for result in report.results)
|
|
87
|
+
notes = (
|
|
88
|
+
(f"semgrep could not fully analyze {len(report.errors)} files or rules.",) if report.errors else ()
|
|
89
|
+
)
|
|
90
|
+
return ToolOutcome(tuple(finding for finding in findings if finding is not None), notes)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def build_semgrep_finding(result: SemgrepResult, root: Path, evidence: EvidenceFn | None) -> Finding | None:
|
|
94
|
+
metadata = result.extra.metadata
|
|
95
|
+
if metadata.get("category", "security") != "security" or "secrets" in result.check_id.split("."):
|
|
96
|
+
# Why: secrets come from built-in rules, gitleaks, and trufflehog, which mask the value first.
|
|
97
|
+
return None
|
|
98
|
+
path = relative_to_root(result.path, root)
|
|
99
|
+
line = max(result.start.line, 1)
|
|
100
|
+
found = evidence(path, line) if evidence is not None else None
|
|
101
|
+
proof = found or Evidence(snippet="", context_start=line, context=())
|
|
102
|
+
message = " ".join(result.extra.message.split())
|
|
103
|
+
rule = rule_id(SPEC.name, result.check_id)
|
|
104
|
+
return Finding(
|
|
105
|
+
id=compute_fingerprint(rule, path, proof.snippet or str(line), ""),
|
|
106
|
+
rule_id=rule,
|
|
107
|
+
title=_first_sentence(message) or result.check_id.rsplit(".", 1)[-1],
|
|
108
|
+
category=CODE_CATEGORY,
|
|
109
|
+
severity=SEVERITIES.get(result.extra.severity.upper(), Severity.MEDIUM),
|
|
110
|
+
cwe=first_cwe(as_strings(metadata.get("cwe")), DEFAULT_CWE),
|
|
111
|
+
owasp=owasp_2025(as_strings(metadata.get("owasp")), DEFAULT_OWASP),
|
|
112
|
+
location=Location(path=path, line=line, column=max(result.start.col, 1)),
|
|
113
|
+
evidence=proof,
|
|
114
|
+
remediation=clip_text(message, MAX_REMEDIATION_CHARS),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _first_sentence(message: str) -> str:
|
|
119
|
+
return clip_text(message.split(". ", 1)[0].rstrip("."), MAX_TITLE_CHARS)
|