Skip to content

Commit bbed258

Browse files
committed
Warn when a site loses the code behind it
A site's code reading steers the curated rules and the open route check. When the repositories behind a site are removed, or stop cloning, the next scan reads fewer routes or none, and nothing said so: the scan looked the same with less behind it. Each scan now compares its code reading with the site's earlier scans. When it reads fewer routes and a repository that gave routes before gives none now, the code reading row turns to a warning naming it and why: removed from the site (by whom and when), no longer linked, linked again, or still linked but unread (a clone that took too long, for one). A removed repository only counts when an earlier scan showed it really was behind the site: the host written in its code, or the site answering one of its routes. A link made on a loose name match has neither, and removing it is the cleanup working, so it is not reported. The site page shows the warning above the code section, with Use it again for a removed repository, naming only repositories the viewer can see. The list counts the sites that lost their code and filters to them. The answer is kept on the site at the end of each scan, worked out once for sites scanned before, and cleared when a site's links change.
1 parent 344df83 commit bbed258

5 files changed

Lines changed: 203 additions & 2 deletions

File tree

‎app/core/external.py‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,139 @@ def set_proxy(asset, value) -> None:
618618
asset.proxy = store._encrypt(text)
619619

620620

621+
# How far back a scan's code reading is compared, in scans.
622+
CODE_LOST_LOOKBACK = 12
623+
624+
625+
def _whitebox_entries(engines) -> list:
626+
"""The repositories one scan's code reading went through."""
627+
try:
628+
rows = json.loads(engines) if isinstance(engines, str) else (engines or [])
629+
except ValueError:
630+
return []
631+
for row in rows if isinstance(rows, list) else []:
632+
if isinstance(row, dict) and row.get("tool") == "whitebox":
633+
return [r for r in row.get("repos") or [] if isinstance(r, dict)]
634+
return []
635+
636+
637+
def _routes_reached(raw) -> dict:
638+
"""{repository: how many of its routes the site answered}, from one
639+
scan's code matches."""
640+
try:
641+
value = json.loads(raw) if isinstance(raw, str) else (raw or {})
642+
except ValueError:
643+
return {}
644+
out = {}
645+
if not isinstance(value, dict):
646+
return out
647+
for c in value.get("candidates") or []:
648+
if isinstance(c, dict) and c.get("full_name") and c.get("matched_count"):
649+
out[c["full_name"]] = max(out.get(c["full_name"], 0), int(c["matched_count"]))
650+
for c in value.get("linked") or []:
651+
if isinstance(c, dict) and c.get("full_name") and c.get("routes_reached"):
652+
out[c["full_name"]] = max(out.get(c["full_name"], 0), int(c["routes_reached"]))
653+
return out
654+
655+
656+
def code_lost(db, asset_id: int, current: list = None, current_scan_id: int = None):
657+
"""The code behind a site that an earlier scan read and the newest did not.
658+
659+
current is the newest scan's code reading when the scan is still running
660+
and has not saved it; otherwise the newest finished scan's is used.
661+
-> None when nothing was lost, else {"scan_id", "routes", "before_scan_id",
662+
"before_routes", "repos": [{"repository", "repository_id", "routes",
663+
"scan_id", "state", "detail"}]}, where state is hidden, unlinked or
664+
unread (still linked, but the newest scan got nothing from it).
665+
"""
666+
rows = (db.query(ExternalDastScan.id, ExternalDastScan.engines, ExternalDastScan.code_matches)
667+
.filter(ExternalDastScan.asset_id == asset_id,
668+
ExternalDastScan.status == "done",
669+
ExternalDastScan.source == "builtin")
670+
.order_by(ExternalDastScan.id.desc()).limit(CODE_LOST_LOOKBACK).all())
671+
readings = [(sid, _whitebox_entries(eng)) for sid, eng, _cm in rows]
672+
reached = {sid: _routes_reached(cm) for sid, _eng, cm in rows}
673+
if current is not None:
674+
readings = [(current_scan_id, current)] + [r for r in readings if r[0] != current_scan_id]
675+
if len(readings) < 2:
676+
return None
677+
newest_id, newest = readings[0]
678+
now = {e.get("repository"): e for e in newest}
679+
now_routes = sum(int(e.get("routes") or 0) for e in newest)
680+
gave, before_id, before_routes, proof = {}, None, 0, {}
681+
for sid, entries in readings[1:]:
682+
total = sum(int(e.get("routes") or 0) for e in entries)
683+
if total and before_id is None:
684+
before_id, before_routes = sid, total
685+
for e in entries:
686+
name = e.get("repository") or ""
687+
if int(e.get("routes") or 0) > 0 and name not in gave \
688+
and not name.startswith("ad-hoc:"):
689+
gave[name] = (int(e["routes"]), sid)
690+
# Evidence the repository really is behind the site, from any
691+
# earlier scan: the host written in its code, or the site
692+
# answering one of its routes. A link made on a loose name
693+
# match has neither, and losing it is the cleanup working.
694+
if name not in proof:
695+
if e.get("host_in_code"):
696+
proof[name] = "the site's host is written in its code"
697+
elif reached.get(sid, {}).get(name):
698+
n = reached[sid][name]
699+
proof[name] = f"the site answered {n} of its routes"
700+
lost = {n: v for n, v in gave.items() if int((now.get(n) or {}).get("routes") or 0) == 0}
701+
if not lost or now_routes >= before_routes:
702+
return None
703+
ids = dict(db.query(Repository.full_name, Repository.id)
704+
.filter(Repository.full_name.in_(list(lost))).all())
705+
links = {r.repository_id: r for r in db.query(ExternalAssetRepo)
706+
.filter(ExternalAssetRepo.asset_id == asset_id,
707+
ExternalAssetRepo.repository_id.in_(list(ids.values()) or [0])).all()}
708+
out = []
709+
for name, (routes, sid) in sorted(lost.items(), key=lambda kv: (-kv[1][0], kv[0])):
710+
repo_id = ids.get(name)
711+
link = links.get(repo_id)
712+
entry = now.get(name)
713+
if link is not None and link.source == "hidden":
714+
when = link.added_at.strftime("%Y-%m-%d") if link.added_at else ""
715+
state, detail = "hidden", (f"removed from this site by {link.added_by or 'somebody'}"
716+
+ (f" on {when}" if when else ""))
717+
elif entry is None and link is not None:
718+
state, detail = "relinked", "linked again; the next scan reads it"
719+
elif entry is None:
720+
state, detail = "unlinked", "no longer linked to this site"
721+
else:
722+
state = "unread"
723+
detail = (f"still linked, but {entry['error']}" if entry.get("error")
724+
else "still linked, but it declared no routes this time")
725+
if state != "unread" and name not in proof:
726+
continue
727+
out.append({"repository": name, "repository_id": repo_id, "routes": routes,
728+
"scan_id": sid, "state": state, "detail": detail[:300],
729+
"evidence": proof.get(name, "")})
730+
if not out:
731+
return None
732+
return {"scan_id": newest_id, "routes": now_routes, "before_scan_id": before_id,
733+
"before_routes": before_routes, "repos": out}
734+
735+
736+
def code_lost_text(lost: dict) -> str:
737+
"""One sentence for a scan's engines row."""
738+
names = ", ".join(f"{r['repository']} ({r['detail']})" for r in lost["repos"][:4])
739+
more = f" and {len(lost['repos']) - 4} more" if len(lost["repos"]) > 4 else ""
740+
return (f"The code behind the site was lost: scan {lost['before_scan_id']} read "
741+
f"{lost['before_routes']} routes, this one {lost['routes']}. "
742+
f"No longer read: {names}{more}. Routes from the code steer the curated "
743+
"rules and the open route check, so they ran with less to go on.")
744+
745+
746+
def remember_code_lost(asset_id: int, lost) -> None:
747+
"""Keep the answer on the site, for the list's count and filter."""
748+
with session_scope() as db:
749+
asset = db.get(ExternalAsset, asset_id)
750+
if asset is not None:
751+
asset.code_lost = json.dumps(lost) if lost else ""
752+
753+
621754
MAX_SAMPLE_LINKS = 5
622755

623756

@@ -2779,6 +2912,16 @@ def _builtin_run(scan_id, host, asset_id, profile, opts, auth, proxy) -> None:
27792912
+ ", ".join(r["repository"] for r in wb["repos"])
27802913
if wb["repos"] else "no repository is mapped"),
27812914
"repos": wb["repos"], "seconds": 0})
2915+
try:
2916+
with session_scope() as db:
2917+
lost = code_lost(db, asset_id, current=wb["repos"], current_scan_id=scan_id)
2918+
remember_code_lost(asset_id, lost)
2919+
if lost:
2920+
engines[-1]["status"] = "warn"
2921+
engines[-1]["detail"] = (engines[-1]["detail"] + ". " + code_lost_text(lost))[:1500]
2922+
engines[-1]["lost"] = lost["repos"]
2923+
except Exception: # noqa: BLE001 - the scan stands without the comparison
2924+
log.exception("scan %s: the code reading was not compared", scan_id)
27822925
# Signing in, for the engines. Baseline and testssl stay signed out:
27832926
# one reads the public posture, the other only talks TLS.
27842927
session, secrets = {}, []

‎app/core/models.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2407,6 +2407,10 @@ class ExternalAsset(Base):
24072407
# sign in and reads what the page hands over. Encrypted, since each one
24082408
# is the key to what it opens. Empty for none.
24092409
sample_links = Column(Text, default="")
2410+
# The code behind the site, lost: repositories an earlier scan read
2411+
# routes from that the newest scan did not. JSON written at the end of
2412+
# each scan, "" when nothing was lost, NULL before it was ever worked out.
2413+
code_lost = Column(Text)
24102414

24112415
# Who answers for the site, as addresses, comma separated.
24122416
executive_owner = Column(String(500), default="")

‎app/web/routes_external.py‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from app.core.models import utcnow as m_utcnow
3636
from app.core.models import (
3737
DastScanProfile, DastServer, ExternalAsset, ExternalAssetRepo,
38-
ExternalAssetTag, ExternalDastScan, SiteGroup, User,
38+
ExternalAssetTag, ExternalDastScan, Repository, SiteGroup, User,
3939
)
4040
from app.web.render import notice_class, page
4141
from app.web.security import (
@@ -173,6 +173,31 @@ def repo_recommendations(hosts: str = "", application: str = "", tags: str = "",
173173
PAGE_SIZES = [50, 100, 200, 500, 1000]
174174

175175

176+
def _code_lost_visible(db, user, asset_id):
177+
"""The site's lost code, naming only repositories this person may see."""
178+
lost = external.code_lost(db, asset_id)
179+
if not lost:
180+
return None
181+
seen = {r.full_name for r in rbac.visible_repositories(db, user).filter(
182+
Repository.full_name.in_([r["repository"] for r in lost["repos"]])).all()}
183+
hidden_from_me = sum(1 for r in lost["repos"] if r["repository"] not in seen)
184+
lost["repos"] = [r for r in lost["repos"] if r["repository"] in seen]
185+
lost["others"] = hidden_from_me
186+
return lost
187+
188+
189+
def _backfill_code_lost(db, assets) -> None:
190+
"""Work it out once for sites scanned before it was kept."""
191+
for a in assets:
192+
if a.code_lost is None:
193+
try:
194+
lost = external.code_lost(db, a.id)
195+
except Exception: # noqa: BLE001 - the list stands without it
196+
log.exception("lost code for site %s was not worked out", a.id)
197+
continue
198+
a.code_lost = json.dumps(lost) if lost else ""
199+
200+
176201
@router.get("/external")
177202
def list_page(request: Request, q: str = "", tag: str = "", app: str = "",
178203
grade: str = "", dast: str = "", risk: str = "", scope: str = "",
@@ -192,6 +217,7 @@ def list_page(request: Request, q: str = "", tag: str = "", app: str = "",
192217
assets = (rbac.visible_external_assets(db, user)
193218
.order_by(ExternalAsset.host).all())
194219
blocked = external.blocked_hosts(db)
220+
_backfill_code_lost(db, assets)
195221
every_link = {a.id: mapper.links(a) for a in assets}
196222
scanning = external.running_scans(db)
197223
from app.core.models import ExternalScanSchedule
@@ -247,6 +273,8 @@ def list_page(request: Request, q: str = "", tag: str = "", app: str = "",
247273
continue
248274
if scope == "unmapped" and linked:
249275
continue
276+
if scope == "code-lost" and not a.code_lost:
277+
continue
250278
rows.append(row)
251279
order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4, "unknown": 5}
252280
rows.sort(key=lambda r: (order.get(r["risk"]["level"], 9), r["a"].host))
@@ -300,6 +328,7 @@ def list_page(request: Request, q: str = "", tag: str = "", app: str = "",
300328
"dast_bad": sum(1 for a in assets if a.last_dast_severity in ("critical", "high")),
301329
"no_scan": sum(1 for a in assets if external.is_blocked(a.host, blocked, a.no_scan)),
302330
"mapped": sum(1 for a in assets if any(l["linked"] for l in every_link[a.id])),
331+
"code_lost": sum(1 for a in assets if a.code_lost),
303332
}
304333
servers = db.query(DastServer).order_by(DastServer.name).all() if manage else []
305334
# Screenshots taken before thumbnails existed, or by a server
@@ -771,6 +800,7 @@ def detail_page(asset_id: int, request: Request, scans: int = 1,
771800
auth_kinds=external_auth_mod.FORM_KINDS,
772801
site_profile=external.profile_for(asset), proxy_label=external.proxy_shown(asset),
773802
sample_links_shown=external.sample_links_shown(asset),
803+
code_lost=_code_lost_visible(db, user, asset.id),
774804
has_shot=external.shot_path(asset.id).is_file(),
775805
exposures=external.EXPOSURES,
776806
has_proxy_shot=external.shot_proxy_path(asset.id).is_file(),
@@ -1126,6 +1156,8 @@ async def link_repo(asset_id: int, request: Request, user: User = Depends(curren
11261156
row.added_by = user.username[:120]
11271157
record(db, f"external.repo_{action}", actor=user.username,
11281158
target=asset.host, detail=repo.full_name, source_ip=client_ip(request))
1159+
# Worked out again on the list's next load.
1160+
asset.code_lost = None
11291161
one = len(names) == 1
11301162
what = names[0] if one else f"{len(names)} repositories"
11311163
if action == "forget":

‎app/web/templates/external.html‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
<a class="stat bad" href="{{ here }}?risk=high"><div class="n">{{ totals.dast_bad }}</div><div class="l">Critical or high on the last scan</div></a>
4343
<a class="stat" href="{{ here }}?scope=mapped"><div class="n">{{ totals.mapped }}</div><div class="l">Mapped to code</div></a>
4444
<a class="stat" href="{{ here }}?scope=no-scan"><div class="n">{{ totals.no_scan }}</div><div class="l">No scan</div></a>
45+
{% if totals.code_lost %}<a class="stat warn" href="{{ here }}?scope=code-lost" title="An earlier scan read routes from code that the newest scan did not"><div class="n">{{ totals.code_lost }}</div><div class="l">Lost their code</div></a>{% endif %}
4546
</div>
4647
<div data-live="list-notices">
4748
{% if running %}<div class="notice info"><div>Reading telemetry for {{ running }} site{{ '' if running == 1 else 's' }}. The list updates as they finish.</div></div>{% endif %}
@@ -77,7 +78,7 @@
7778
{% for k, l in exposures.items() %}<option value="{{ k }}" {{ 'selected' if k == exposure }}>{{ l }}</option>{% endfor %}</select></div>
7879
<div class="field"><label for="scope">Show</label>
7980
<select id="scope" name="scope"><option value="">Every site</option>
80-
{% for v, l in [('mapped','Mapped to a repository'),('unmapped','Not mapped'),('no-scan','No scan')] %}<option value="{{ v }}" {{ 'selected' if v == scope }}>{{ l }}</option>{% endfor %}</select></div>
81+
{% for v, l in [('mapped','Mapped to a repository'),('unmapped','Not mapped'),('no-scan','No scan'),('code-lost','Lost their code')] %}<option value="{{ v }}" {{ 'selected' if v == scope }}>{{ l }}</option>{% endfor %}</select></div>
8182
<button class="btn primary" type="submit">Search</button>
8283
<a class="btn" href="{{ here }}">Clear</a>
8384
</form>

‎app/web/templates/external_site.html‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,27 @@
377377
{% set linked = links | selectattr('linked') | list %}
378378
{% set code = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0} %}
379379
{% for l in linked %}{% for level in code %}{% set _ = code.update({level: code[level] + counts.get(l.full_name, {}).get(level, 0)}) %}{% endfor %}{% endfor %}
380+
{% if code_lost %}
381+
<div class="notice warn" id="code-lost"><div>
382+
<strong>The code behind this site was lost.</strong>
383+
Scan {{ code_lost.before_scan_id }} read {{ code_lost.before_routes }} routes from the code; the newest, scan {{ code_lost.scan_id }}, read {{ code_lost.routes }}.
384+
The routes steer the curated rules and the open route check, so they had less to go on.
385+
{% if code_lost.repos %}<div class="table-scroll"><table class="compact">
386+
<thead><tr><th>Repository</th><th>Routes it gave</th><th>Now</th><th></th></tr></thead><tbody>
387+
{% for r in code_lost.repos %}<tr>
388+
<td class="small">{% if r.repository_id %}<a href="{{ base }}/repositories/{{ r.repository_id }}">{{ r.repository }}</a>{% else %}{{ r.repository }}{% endif %}</td>
389+
<td class="small">{{ r.routes }} in scan {{ r.scan_id }}</td>
390+
<td class="small">{{ r.detail }}{% if r.evidence %}<div class="faint">Behind the site before: {{ r.evidence }}.</div>{% endif %}</td>
391+
<td class="nowrap">{% if can_manage and r.state in ('hidden', 'unlinked') %}
392+
<form method="post" action="{{ base }}/external/{{ asset.id }}/repos" style="display:inline">
393+
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
394+
<input type="hidden" name="repository" value="{{ r.repository }}">
395+
<button class="btn sm" name="action" value="link" type="submit">Use it again</button></form>{% endif %}</td>
396+
</tr>{% endfor %}</tbody></table></div>{% endif %}
397+
{% if code_lost.others %}<div class="faint small">And {{ code_lost.others }} repositor{{ 'y' if code_lost.others == 1 else 'ies' }} you cannot see.</div>{% endif %}
398+
<div class="faint small">The next scan reads the code again.</div>
399+
</div></div>
400+
{% endif %}
380401
<details class="card code-behind" id="code">
381402
<summary class="card-head">Code behind it
382403
<span class="code-summary">{{ linked | length }} repositor{{ 'y' if linked | length == 1 else 'ies' }}

0 commit comments

Comments
 (0)