OSINT Advanced

OSINT for Defenders: Legal Framework, Scope, and Method

Set up defensive OSINT properly: the intelligence cycle, passive versus active collection, GDPR and computer intrusion basics, a written scope document, analyst OPSEC, Admiralty source grading, and a Python evidence logger that hashes every collection step.

KC Ramo DjangoZen Team Dec 05, 2026 16 min read 5 views

Open source intelligence is easy to start and easy to get wrong. A defender who maps the public exposure of their own organisation needs the same discipline as any other security assessment: a mandate, a written scope, a repeatable method, and a record of every step. This tutorial sets out that framework and ends with a small Python evidence logger you can use in every later exercise in this category.

What OSINT is, and what it is not

OSINT is intelligence produced from information that is publicly and lawfully available: DNS records, Certificate Transparency logs, published code, search engine caches, regulatory filings, archived web pages, and similar sources. The word that matters is intelligence. A pile of search results is raw material. Intelligence is what remains after the material has been collected for a stated question, checked for reliability, analysed, and turned into a conclusion someone can act on.

In this category OSINT has one purpose: an organisation examining what the internet can see about its own assets. Typical questions are "Which hostnames under our domains are publicly visible?", "Did a deployment leak configuration into a public repository?", or "Which of our certificates expire in the next 30 days?". The answers feed patching, decommissioning and policy decisions.

Some things are explicitly out of scope and will not be covered anywhere in this series:

  • Investigating, locating, profiling or identifying private individuals. That includes people search, social media profiling, face recognition, and compiling addresses or phone numbers. Under the GDPR (in Dutch: AVG) such processing needs a lawful basis that a security team almost never has, and it creates real risks for the people concerned. Ethically it is the line between defending systems and surveilling people.
  • Assessing assets that belong to someone else, even "just looking". Being curious about a supplier or a competitor is not a mandate.
  • Anything that requires logging in, guessing credentials, bypassing access controls, or exploiting a weakness. That is no longer OSINT and may be a criminal offence.

The intelligence cycle

The classic intelligence cycle is a useful backbone for exposure reviews because it forces you to write down the question before you start collecting. It has five phases.

  1. Planning and direction. Agree the intelligence requirement with the person who will act on it. "Give us an inventory of internet-facing hostnames under example.com and example.org, with their current DNS state, by Friday" is a requirement. "See what you can find" is not. Planning also produces the scope document described below.
  2. Collection. Gather data from the sources the scope allows, using the techniques the scope allows, and log every request.
  3. Processing. Normalise, deduplicate and parse. Convert timestamps to UTC, lowercase hostnames, strip trailing dots, discard records that are out of scope. Processing should be scripted so it is reproducible.
  4. Analysis. Interpret the processed data against the requirement. Which hosts are unexpected? Which are owned by a team nobody remembers? Grade the reliability of sources and the credibility of each finding.
  5. Dissemination. Deliver the answer in a form the requester can use: a short report, a ticket per finding, or an update to an asset inventory. Include confidence levels and the evidence references.

Feedback from dissemination flows back into planning. If the network team says a hostname was retired last year, the next cycle should explain why it still appears in your sources.

Passive versus active collection

Passive collection means you never send traffic to the systems under review. You query third parties that have already recorded information: Certificate Transparency logs, passive DNS databases, web archives, code hosting search. The target cannot see you and your actions cannot affect its availability.

Active collection means you interact with the target: resolving its DNS names against its authoritative servers, requesting web pages, grabbing TLS banners, port scanning. Even a simple HTTP request is active, because it reaches the target's infrastructure and appears in its logs.

The line matters for three reasons:

  • Legal. Most computer intrusion statutes punish unauthorised access, and some also punish disrupting availability. Passive queries against public third-party sources rarely raise those questions. Active techniques can, depending on what you do and whether you are authorised. Your scope document should state which active techniques are permitted, against which assets, and at what rate.
  • Operational. Active probing can trigger intrusion detection, wake up an on-call engineer, or cause a fragile service to fall over. Coordinate with operations before any active step, even on your own assets.
  • Evidential. Passive sources reflect what someone else saw at some earlier time. Active checks reflect the present. Record which kind each data point is, because it changes how much weight a finding can bear.

Some steps sit in between. Resolving a hostname through a public recursive resolver queries the target's authoritative name servers indirectly. Treat that as low-impact active collection and put it in scope explicitly rather than arguing about it afterwards.

This section gives general orientation, not legal advice. Laws differ between jurisdictions and change over time. Before you start a programme, ask your legal counsel or data protection officer to confirm the approach for your organisation.

GDPR basics for collectors

Even when you only look at your own infrastructure, the data you collect can contain personal data: an e-mail address in a certificate, a developer's name in a commit, a staff member's account name in a leaked configuration file. As soon as personal data is in scope, the GDPR applies to your processing.

  • Lawful basis. For a security team, the realistic basis is usually legitimate interest (Article 6(1)(f)): protecting the organisation's systems and the data of its customers. Consent is impractical and contract rarely fits.
  • Legitimate interest assessment (LIA). Document three tests. Purpose: what legitimate interest is served? Necessity: is this processing needed, or could you achieve the purpose with less? Balancing: do the interests and rights of the people concerned override yours? Keep the LIA with the scope document.
  • Data minimisation. Collect only what answers the requirement. If you need hostnames from certificates, store hostnames and discard e-mail addresses that appear in the same fields. Filtering at collection time is better than promising to delete later.
  • Purpose limitation. Data gathered for an exposure review must not be reused for unrelated purposes such as evaluating employees.
  • Retention. Set a retention period per data type in the scope document and enforce it with a scheduled job. Raw collection artefacts that contain personal data usually deserve a short period; aggregated findings without personal data can live longer.
  • Security of processing. Evidence stores are attractive targets. Encrypt them at rest, restrict access, and log who reads them.

Record the processing activity in your register of processing activities, as Article 30 requires for most organisations.

The Dutch and EU context

In the Netherlands, computer intrusion (computervredebreuk) is defined in the Criminal Code as intentionally and unlawfully entering an automated system or part of it. Other EU member states have comparable provisions, harmonised to a large extent by Directive 2013/40/EU on attacks against information systems. The practical rule for defenders is simple: do not access any system without authorisation, and do not bypass any security measure, however weak. Using a password found in a public paste to "check whether it still works" is access, not OSINT.

Authorisation must come from someone entitled to give it. A team lead cannot authorise testing of a system hosted and operated by a third party; the contract with that party determines what is allowed. Many cloud and hosting contracts contain specific testing policies. Read them before any active step.

The Netherlands also has an established practice of coordinated vulnerability disclosure. If your review uncovers a weakness in a third party's system along the way, stop, record what you saw, and report it through that party's disclosure channel. Do not investigate further.

Rules of engagement and the scope document

Rules of engagement translate the mandate into concrete limits. They answer who may do what, against which assets, when, how fast, and what happens when something unexpected turns up. Write them down and get them signed before collection starts. A minimal scope document looks like this.

FieldExample content
Case identifierMYPROJECT-2026-001
Requester and approverHead of IT (requester), CISO (approver), signed and dated
Intelligence requirementInventory of public hostnames under our domains with DNS state and certificate expiry
Assets in scopeexample.com, example.org and all subdomains; 192.0.2.0/24; 198.51.100.0/24
Assets out of scopeThird-party SaaS tenants, supplier domains, personal accounts of staff
Permitted passive sourcesCertificate Transparency logs, public DNS, web archives, public code search
Permitted active techniquesDNS resolution via the corporate resolver; no port scanning, no HTTP requests
Rate limitsOne request per 10 seconds per external source
Personal data handlingNot collected deliberately; incidental personal data removed during processing
Lawful basis and LIALegitimate interest; LIA reference LIA-2026-004
RetentionRaw artefacts 90 days; findings 2 years
Time window2026-12-07 to 2026-12-18, office hours
Stop conditionsSigns of compromise, third-party vulnerability, personal data beyond incidental: stop and escalate
Escalation contactsSecurity on-call, data protection officer
DeliverablesFindings report, evidence log, updated asset inventory

Keep the scope machine-readable as well. Later tutorials in this category refuse to run against a domain that is not listed in a settings file, which turns the scope document into an enforced control rather than a PDF in a shared folder.

OPSEC for the analyst

Operational security in defensive OSINT protects two things: the integrity of your evidence and the confidentiality of your organisation's interests. You are not hiding from your own employer, but you do want clean, attributable, reproducible collection.

  • Separate identities. Use dedicated accounts for any source that requires registration, owned by the organisation, never your personal accounts. Record which account performed each query.
  • Separate browser profile or virtual machine. A dedicated profile avoids leaking your personal session cookies, search history and extensions into collection, and avoids collection artefacts leaking into your personal browsing.
  • No interaction. Do not post, comment, follow, like, message, or submit forms. Passive collection means reading only.
  • Know what you disclose. Searching a third-party service for an unreleased product name tells that service about the product. Consider whether the query itself is sensitive.
  • Identify your automation honestly. Set a descriptive User-Agent with a contact address on scripts, respect robots rules and published rate limits, and back off on errors.
  • Clock discipline. Keep the analysis machine synchronised with NTP and log in UTC. Timeline arguments are lost on clock skew.

Grading source reliability

The Admiralty system, also used in NATO doctrine, grades each item on two independent axes: the reliability of the source and the credibility of the information. Combining them gives a compact code such as B2.

CodeSource reliabilityCodeInformation credibility
ACompletely reliable1Confirmed by other independent sources
BUsually reliable2Probably true
CFairly reliable3Possibly true
DNot usually reliable4Doubtful
EUnreliable5Improbable
FReliability cannot be judged6Truth cannot be judged

Grade the two axes separately. A Certificate Transparency log operated under a public policy might be a B: it is cryptographically append-only, but an aggregator in front of it can lag, drop entries or time out. A hostname found in a certificate is probably true as a statement that the name was certified, so 2, but it says nothing about whether the host exists today. After your own DNS resolution confirms the name, the finding can move to 1.

Default unknown sources to F6 and upgrade only with reasons you can write down. Do not let a high source grade inflate a claim the source never made.

Documenting every step

Every conclusion in your report should trace back to a specific collection step: which source, which query, when, by whom, and exactly what came back. Three properties make that trace trustworthy:

  • Append-only log. Steps are added, never edited. Corrections are new entries that reference the old one.
  • Content hashing. Store each raw response as a file and record its SHA-256 digest. Anyone can recompute the hash later and confirm the artefact was not altered.
  • UTC timestamps. Record collection time in UTC with an explicit offset.

A JSON Lines evidence logger

The helper below uses only the standard library. It was tested on Python 3.13 and needs Python 3.12 or later. The demonstration uses requests 2.34.2, the latest stable release at the time of writing; later tutorials in this category add Django 5.2.20 LTS (pinned as Django>=5.2,<6.0) and dnspython 2.9.2.

python -m venv .venv
. .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install "requests>=2.34,<3.0"

Save the following as evidence.py:

"""Append-only evidence log for OSINT collection steps (JSON Lines)."""
from __future__ import annotations

import hashlib
import json
import os
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path


@dataclass(frozen=True)
class EvidenceRecord:
    record_id: str
    case_id: str
    analyst: str
    source: str
    query: str
    collected_at: str
    artefact: str
    sha256: str
    size_bytes: int
    grading: str
    note: str


class EvidenceLog:
    def __init__(self, case_id: str, analyst: str, root: Path) -> None:
        self.case_id = case_id
        self.analyst = analyst
        self.root = Path(root)
        self.artefacts = self.root / "artefacts"
        self.artefacts.mkdir(parents=True, exist_ok=True)
        self.log_path = self.root / "evidence.jsonl"

    def record(self, *, source: str, query: str, content: bytes,
               suffix: str = ".bin", grading: str = "F6",
               note: str = "") -> EvidenceRecord:
        digest = hashlib.sha256(content).hexdigest()
        artefact = self.artefacts / f"{digest}{suffix}"
        if not artefact.exists():
            artefact.write_bytes(content)
        rec = EvidenceRecord(
            record_id=str(uuid.uuid4()),
            case_id=self.case_id,
            analyst=self.analyst,
            source=source,
            query=query,
            collected_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
            artefact=artefact.relative_to(self.root).as_posix(),
            sha256=digest,
            size_bytes=len(content),
            grading=grading,
            note=note,
        )
        line = json.dumps(asdict(rec), ensure_ascii=False, sort_keys=True)
        with self.log_path.open("a", encoding="utf-8") as fh:
            fh.write(line + "\n")
            fh.flush()
            os.fsync(fh.fileno())
        return rec

    def verify(self) -> list[str]:
        """Return a list of problems; an empty list means the log is intact."""
        problems = []
        with self.log_path.open(encoding="utf-8") as fh:
            for n, line in enumerate(fh, start=1):
                rec = json.loads(line)
                path = self.root / rec["artefact"]
                if not path.exists():
                    problems.append(f"line {n}: missing {rec['artefact']}")
                    continue
                actual = hashlib.sha256(path.read_bytes()).hexdigest()
                if actual != rec["sha256"]:
                    problems.append(f"line {n}: hash mismatch for {rec['artefact']}")
        return problems

Design choices worth noting:

  • Artefacts are named by their own hash, so identical responses are stored once and a file name cannot silently point to different content.
  • Each record is one JSON object on one line, written with an explicit fsync. A crash can lose at most the line being written, never corrupt earlier lines.
  • The record stores the exact query string, so the step can be repeated and compared.
  • Grading is a field from the start, which nudges the analyst to think about reliability at collection time.

Using the logger on a passive source

The demonstration below performs one passive query: Certificate Transparency entries for example.com from the public crt.sh aggregator. In a real case you would substitute a domain from your signed scope.

import requests
from pathlib import Path

from evidence import EvidenceLog

log = EvidenceLog(case_id="MYPROJECT-2026-001", analyst="analyst-01",
                  root=Path("case-001"))

url = "https://crt.sh/?q=example.com&output=json"
resp = requests.get(url, timeout=60,
                    headers={"User-Agent": "myproject-exposure-review/1.0"})
resp.raise_for_status()
rec = log.record(source="crt.sh", query=url, content=resp.content,
                 suffix=".json", grading="B2",
                 note="CT entries for own domain, scope item S-01")
print(rec.collected_at, rec.sha256[:16], rec.size_bytes)
print("problems:", log.verify())

Output from a real run:

2026-12-05T16:19:07+00:00 b3b8f7173648f73d 27146
problems: []

The log line, formatted for readability:

{"analyst": "analyst-01",
 "artefact": "artefacts/b3b8f7173648f73da6e90f031cec09f223f42b48d39a25c19e855f495d932fba.json",
 "case_id": "MYPROJECT-2026-001",
 "collected_at": "2026-12-05T16:19:07+00:00",
 "grading": "B2",
 "note": "CT entries for own domain, scope item S-01",
 "query": "https://crt.sh/?q=example.com&output=json",
 "record_id": "d281ae1a-6c29-4688-88a5-bf3f4a870730",
 "sha256": "b3b8f7173648f73da6e90f031cec09f223f42b48d39a25c19e855f495d932fba",
 "size_bytes": 27146,
 "source": "crt.sh"}

To see the integrity check work, append one byte to the stored artefact and call verify() again:

['line 1: hash mismatch for artefacts/b3b8f7173648f73da6e90f031cec09f223f42b48d39a25c19e855f495d932fba.json']

Note that the raw crt.sh response is stored unmodified, so it may contain e-mail addresses that a certificate authority included in a subject field. That is incidental personal data. Your scope document should say how long such raw artefacts are kept and who can read them, and your processing step should drop those values before anything reaches a report.

Hardening the log

A local file protects against accidents, not against a determined insider. For higher assurance:

  • Chain the records by adding the SHA-256 of the previous line to each new line, so deleting or reordering lines becomes detectable.
  • Periodically copy the log and artefacts to write-once storage, or obtain an RFC 3161 timestamp on the log's hash from a trusted timestamping service.
  • Sign the final evidence package when you hand it over, and record the signature in the report.

From log to report

A good defensive OSINT report is short and verifiable. For each finding give a one-sentence statement, the affected asset, the grading, the evidence record identifiers, a recommended action and an owner. Separate observation ("the name staging.example.com appears in a certificate issued in November") from assessment ("the staging environment is probably reachable from the internet"). Readers should be able to disagree with your assessment while accepting your observation.

Close each case formally: confirm that deliverables were accepted, schedule deletion of raw artefacts according to the retention period, and note lessons for the next planning phase.

Checklist

  1. Write the intelligence requirement as one concrete question with a deadline and a requester.
  2. Complete the scope document, including out-of-scope assets, permitted techniques and rate limits, and obtain a signature from someone entitled to authorise it.
  3. Record the lawful basis and a legitimate interest assessment if personal data could appear, and register the processing activity.
  4. Decide which steps are passive and which are active, and confirm active steps with operations.
  5. Prepare a separate browser profile or virtual machine and organisation-owned accounts for any source that needs them.
  6. Log every collection step with source, query, UTC timestamp, artefact hash and grading, using the evidence logger or an equivalent.
  7. Grade each source and each item of information separately on the A to F and 1 to 6 scales.
  8. Strip incidental personal data during processing and keep it out of reports.
  9. Stop and escalate on signs of compromise or on a vulnerability in a third party's system.
  10. Run verify() before handing over evidence, and enforce the retention period afterwards.

Found a mistake in this tutorial? Let us know and we will fix it.