🎯 The ultimate OSINT toolkit: investigation graph, confidence scoring, alias families, map, timeline and reports. 49 modules, 400+ sites, no API keys required.
Python chilecybersecurityfastapiinvestigationosintosint-frameworkosint-toolpythonreconnaissanceusername-search
Base de datos y robustez: migraciones schema_version, consultas puntuales, escrituras por lotes y validación de /api/import (D4, D5, D6, D12)
letox4d237653d51db
diff --git a/app/analysis.py b/app/analysis.pyindex d47e720..42beca1 100644--- a/app/analysis.py+++ b/app/analysis.py@@ -101,14 +101,15 @@ async def photo_match(engine, job) -> None:if dist <= 6:pairs.append((a, b, dist))new = 0- for a, b, dist in pairs:- if db.add_edge(job.case_id, a["id"], b["id"], PHOTO_REL, "photo_match"):- new += 1- job.emit({"type": "edge", "edge": {"src": a["id"], "dst": b["id"], "label": PHOTO_REL, "source": "photo_match"}})- sim = round(100 - dist * 100 / 64)- for x, y in ((a, b), (b, a)):- ent = db.update_attrs(job.case_id, x["id"], {"Foto coincide con": [f"{y['label']} ({sim}%)"]})- _emit_entity(job, ent)+ with db.batch():+ for a, b, dist in pairs:+ if db.add_edge(job.case_id, a["id"], b["id"], PHOTO_REL, "photo_match"):+ new += 1+ job.emit({"type": "edge", "edge": {"src": a["id"], "dst": b["id"], "label": PHOTO_REL, "source": "photo_match"}})+ sim = round(100 - dist * 100 / 64)+ for x, y in ((a, b), (b, a)):+ ent = db.update_attrs(job.case_id, x["id"], {"Foto coincide con": [f"{y['label']} ({sim}%)"]})+ _emit_entity(job, ent)if todo or new:_record(job, "photo_match", "ok" if pairs else "empty",f"{len(hashed)} fotos comparadas · {len(pairs)} coincidencias" + (f" ({new} nuevas)" if new else ""),@@ -167,15 +168,16 @@ def score_identities(job) -> int:scores[a["id"]], reasons[a["id"]] = _score_account(a, ents, adj, names, ref_tokens, linked_from, scores, marks)changed = 0- for a in accounts:- at = a["attrs"]- score, why = scores[a["id"]], reasons[a["id"]]- level = "Alta" if score >= 70 else "Media" if score >= 40 else "Baja"- if at.get("Confianza") != score or at.get("Señales") != why:- ent = db.update_attrs(job.case_id, a["id"], {"Confianza": score, "Nivel de confianza": level, "Señales": why},- replace=True)- _emit_entity(job, ent)- changed += 1+ with db.batch():+ for a in accounts:+ at = a["attrs"]+ score, why = scores[a["id"]], reasons[a["id"]]+ level = "Alta" if score >= 70 else "Media" if score >= 40 else "Baja"+ if at.get("Confianza") != score or at.get("Señales") != why:+ ent = db.update_attrs(job.case_id, a["id"], {"Confianza": score, "Nivel de confianza": level, "Señales": why},+ replace=True)+ _emit_entity(job, ent)+ changed += 1return changeddiff --git a/app/db.py b/app/db.pyindex f682750..eac1716 100644--- a/app/db.py+++ b/app/db.py@@ -1,3 +1,4 @@+from contextlib import contextmanagerimport jsonimport sqlite3import threading@@ -6,11 +7,17 @@ import timefrom .config import DATA_DIRfrom .models import display_label, entity_id, normalize+CURRENT_SCHEMA_VERSION = 2+SCHEMA = """+CREATE TABLE IF NOT EXISTS schema_version(+ version INTEGER NOT NULL+);CREATE TABLE IF NOT EXISTS cases(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,notes TEXT DEFAULT '',+ layout TEXT DEFAULT '{}',created REAL,updated REAL);@@ -75,14 +82,65 @@ class DB:self.conn = sqlite3.connect(path, check_same_thread=False)self.conn.row_factory = sqlite3.Rowself.lock = threading.RLock()+ self._batch_depth = 0with self.lock:self.conn.execute("PRAGMA journal_mode=WAL")+ self.conn.execute("PRAGMA synchronous=NORMAL")self.conn.executescript(SCHEMA)+ self._migrate()+ self.conn.commit()++ def _migrate(self) -> None:+ row = self.conn.execute("SELECT version FROM schema_version LIMIT 1").fetchone()+ if row is None:+ ver = 0+ self.conn.execute("INSERT INTO schema_version(version) VALUES(0)")+ else:+ ver = int(row["version"])++ if ver < 1:cols = {r[1] for r in self.conn.execute("PRAGMA table_info(cases)")}if "layout" not in cols:self.conn.execute("ALTER TABLE cases ADD COLUMN layout TEXT DEFAULT '{}'")+ ver = 1+ self.conn.execute("UPDATE schema_version SET version=?", (ver,))++ if ver < 2:+ self.conn.executescript("""+ CREATE INDEX IF NOT EXISTS entities_case_type ON entities(case_id, type);+ CREATE INDEX IF NOT EXISTS edges_case_src ON edges(case_id, src);+ CREATE INDEX IF NOT EXISTS edges_case_dst ON edges(case_id, dst);+ CREATE INDEX IF NOT EXISTS runs_case_module ON runs(case_id, module, status);+ """)+ ver = 2+ self.conn.execute("UPDATE schema_version SET version=?", (ver,))++ def schema_version(self) -> int:+ with self.lock:+ row = self.conn.execute("SELECT version FROM schema_version LIMIT 1").fetchone()+ return int(row["version"]) if row else 0++ def _commit(self) -> None:+ if self._batch_depth == 0:self.conn.commit()+ @contextmanager+ def batch(self):+ """Agrupa múltiples escrituras SQLite en un único commit al salir del bloque."""+ with self.lock:+ self._batch_depth += 1+ try:+ yield+ except Exception:+ self._batch_depth -= 1+ if self._batch_depth == 0:+ self.conn.rollback()+ raise+ else:+ self._batch_depth -= 1+ if self._batch_depth == 0:+ self.conn.commit()+# ---------- casos ----------def list_cases(self) -> list[dict]:with self.lock:@@ -98,7 +156,7 @@ class DB:cur = self.conn.execute("INSERT INTO cases(name, created, updated) VALUES(?,?,?)", (name.strip() or "Caso sin nombre", now, now))- self.conn.commit()+ self._commit()return self.get_case(cur.lastrowid)def get_case(self, case_id: int) -> dict | None:@@ -128,19 +186,18 @@ class DB:def touch(self, case_id: int) -> None:with self.lock:self.conn.execute("UPDATE cases SET updated=? WHERE id=?", (time.time(), case_id))- self.conn.commit()+ self._commit()def delete_case(self, case_id: int) -> None:- with self.lock:+ with self.batch():for table in ("entities", "edges", "runs"):self.conn.execute(f"DELETE FROM {table} WHERE case_id=?", (case_id,))self.conn.execute("DELETE FROM cases WHERE id=?", (case_id,))- self.conn.commit()# ---------- entidades ----------@staticmethoddef _entity(row) -> dict:- attrs = json.loads(row["attrs"] or "{}")+ attrs = json.loads(row["attrs"] or "{}") if isinstance(row["attrs"], str) else (row["attrs"] or {})return {"id": row["id"],"type": row["type"],@@ -165,24 +222,38 @@ class DB:row = self.conn.execute("SELECT * FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()if row:merged = merge_attrs(json.loads(row["attrs"] or "{}"), attrs or {})+ new_root = max(int(row["root"]), int(root))+ new_pivot = max(int(row["pivot"]), int(pivot))self.conn.execute(- "UPDATE entities SET attrs=?, root=MAX(root, ?), pivot=MAX(pivot, ?) WHERE case_id=? AND id=?",- (json.dumps(merged, ensure_ascii=False), int(root), int(pivot), case_id, eid),+ "UPDATE entities SET attrs=?, root=?, pivot=? WHERE case_id=? AND id=?",+ (json.dumps(merged, ensure_ascii=False), new_root, new_pivot, case_id, eid),)created = Falseelse:+ merged = dict(attrs or {})+ new_root = int(root)+ new_pivot = int(pivot)self.conn.execute("INSERT INTO entities(case_id, id, type, value, attrs, root, pivot, created) VALUES(?,?,?,?,?,?,?,?)",- (case_id, eid, etype, value, json.dumps(attrs or {}, ensure_ascii=False), int(root), int(pivot), time.time()),+ (case_id, eid, etype, value, json.dumps(merged, ensure_ascii=False), new_root, new_pivot, time.time()),)created = True- self.conn.commit()- return self.get_entity(case_id, eid), created+ self._commit()+ ent = {+ "id": eid,+ "type": etype,+ "value": value,+ "attrs": merged,+ "root": bool(new_root),+ "pivot": bool(new_pivot),+ "label": display_label(etype, value, merged),+ }+ return ent, createddef update_attrs(self, case_id: int, eid: str, attrs: dict, replace: bool = False) -> dict | None:"""Fusiona atributos; con replace=True las claves dadas se sobrescriben (o se borran si valen None)."""with self.lock:- row = self.conn.execute("SELECT attrs FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()+ row = self.conn.execute("SELECT * FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()if not row:return Nonecurrent = json.loads(row["attrs"] or "{}")@@ -198,24 +269,37 @@ class DB:self.conn.execute("UPDATE entities SET attrs=? WHERE case_id=? AND id=?", (json.dumps(merged, ensure_ascii=False), case_id, eid))- self.conn.commit()- return self.get_entity(case_id, eid)+ self._commit()+ return {+ "id": row["id"],+ "type": row["type"],+ "value": row["value"],+ "attrs": merged,+ "root": bool(row["root"]),+ "pivot": bool(row["pivot"]),+ "label": display_label(row["type"], row["value"], merged),+ }def delete_entity(self, case_id: int, eid: str) -> None:- with self.lock:+ with self.batch():self.conn.execute("DELETE FROM entities WHERE case_id=? AND id=?", (case_id, eid))self.conn.execute("DELETE FROM edges WHERE case_id=? AND (src=? OR dst=?)", (case_id, eid, eid))self.conn.execute("DELETE FROM runs WHERE case_id=? AND entity_id=?", (case_id, eid))- self.conn.commit()def delete_entities(self, case_id: int, ids: list[str]) -> int:+ if not ids:+ return 0n = 0- with self.lock:- for eid in ids:- n += self.conn.execute("DELETE FROM entities WHERE case_id=? AND id=?", (case_id, eid)).rowcount- self.conn.execute("DELETE FROM edges WHERE case_id=? AND (src=? OR dst=?)", (case_id, eid, eid))- self.conn.execute("DELETE FROM runs WHERE case_id=? AND entity_id=?", (case_id, eid))- self.conn.commit()+ with self.batch():+ for i in range(0, len(ids), 400):+ chunk = ids[i:i + 400]+ ph = ",".join("?" for _ in chunk)+ n += self.conn.execute(f"DELETE FROM entities WHERE case_id=? AND id IN ({ph})", (case_id, *chunk)).rowcount+ self.conn.execute(+ f"DELETE FROM edges WHERE case_id=? AND (src IN ({ph}) OR dst IN ({ph}))",+ (case_id, *chunk, *chunk),+ )+ self.conn.execute(f"DELETE FROM runs WHERE case_id=? AND entity_id IN ({ph})", (case_id, *chunk))return n# ---------- relaciones y ejecuciones ----------@@ -225,14 +309,14 @@ class DB:"INSERT OR IGNORE INTO edges(case_id, src, dst, label, source) VALUES(?,?,?,?,?)",(case_id, src, dst, label, source),)- self.conn.commit()+ self._commit()return cur.rowcount > 0def delete_edge(self, case_id: int, src: str, dst: str, label: str) -> bool:with self.lock:cur = self.conn.execute("DELETE FROM edges WHERE case_id=? AND src=? AND dst=? AND label=?",(case_id, src, dst, label))- self.conn.commit()+ self._commit()return cur.rowcount > 0def add_run(self, case_id: int, eid: str, module: str, status: str, message: str, found: int, started: float) -> dict:@@ -242,9 +326,43 @@ class DB:"INSERT INTO runs(case_id, entity_id, module, status, message, found, started, finished) VALUES(?,?,?,?,?,?,?,?)",(case_id, eid, module, status, message, found, started, now),)- self.conn.commit()- row = self.conn.execute("SELECT * FROM runs WHERE id=?", (cur.lastrowid,)).fetchone()- return dict(row)+ self._commit()+ rid = cur.lastrowid+ return {+ "id": rid,+ "case_id": case_id,+ "entity_id": eid,+ "module": module,+ "status": status,+ "message": message,+ "found": found,+ "started": started,+ "finished": now,+ }++ def completed_modules(self, case_id: int, eid: str, statuses: tuple[str, ...] = ("ok", "empty")) -> set[str]:+ """Consultas puntuales (D4): devuelve los módulos ya ejecutados sobre una entidad."""+ ph = ",".join("?" for _ in statuses)+ with self.lock:+ rows = self.conn.execute(+ f"SELECT DISTINCT module FROM runs WHERE case_id=? AND entity_id=? AND status IN ({ph})",+ (case_id, eid, *statuses),+ ).fetchall()+ return {r["module"] for r in rows}++ def entities_without_run(+ self, case_id: int, module: str, statuses: tuple[str, ...] = ("ok", "empty", "skipped")+ ) -> list[dict]:+ """Consultas puntuales (D4): entidades del caso que aún no ejecutaron el módulo dado."""+ ph = ",".join("?" for _ in statuses)+ with self.lock:+ rows = self.conn.execute(+ f"SELECT * FROM entities WHERE case_id=? AND id NOT IN ("+ f"SELECT entity_id FROM runs WHERE case_id=? AND module=? AND status IN ({ph})"+ f") ORDER BY created",+ (case_id, case_id, module, *statuses),+ ).fetchall()+ return [self._entity(r) for r in rows]def graph(self, case_id: int) -> dict:with self.lock:diff --git a/app/engine.py b/app/engine.pyindex 51e7f86..b2c375d 100644--- a/app/engine.py+++ b/app/engine.py@@ -102,12 +102,14 @@ class Context:return Noneattrs = dict(attrs or {})attrs["_fuentes"] = [self.module.title]- ent, created = db.upsert_entity(self.case_id, etype, str(value), attrs, pivot=pivot)+ src = parent or self.entity["id"]+ with db.batch():+ ent, created = db.upsert_entity(self.case_id, etype, str(value), attrs, pivot=pivot)+ edge_added = src != ent["id"] and db.add_edge(self.case_id, src, ent["id"], rel, self.module.name)self.job.emit({"type": "entity", "entity": ent, "created": created})if created:self.job.created.append(ent["id"])- src = parent or self.entity["id"]- if src != ent["id"] and db.add_edge(self.case_id, src, ent["id"], rel, self.module.name):+ if edge_added:self.job.emit({"type": "edge", "edge": {"src": src, "dst": ent["id"], "label": rel, "source": self.module.name}})self.found += 1if pivot and etype in AUTO_PIVOT_TYPES:@@ -177,9 +179,7 @@ class Engine:from . import analysistry:- graph = db.graph(job.case_id)- done = {r["entity_id"] for r in graph["runs"] if r["module"] == m.name and r["status"] in ("ok", "empty", "skipped")}- ents = [e for e in graph["entities"] if m.applies(e) and e["id"] not in done]+ ents = [e for e in db.entities_without_run(job.case_id, m.name) if m.applies(e)]sem = asyncio.Semaphore(8)async def one(e):@@ -273,11 +273,7 @@ class Engine:else:mods = [m for m in mods if not m.deep]if not rerun:- done = {- r["module"]- for r in db.graph(job.case_id)["runs"]- if r["entity_id"] == eid and r["status"] in ("ok", "empty")- }+ done = db.completed_modules(job.case_id, eid, ("ok", "empty"))mods = [m for m in mods if m.name not in done]if not mods:return []diff --git a/app/main.py b/app/main.pyindex c120a28..88018ce 100644--- a/app/main.py+++ b/app/main.py@@ -318,23 +318,24 @@ async def upload_image(case_id: int, file: UploadFile = File(...)):except Exception as e: # noqa: BLE001raise HTTPException(400, f"No se pudo leer la imagen: {e}") from einfo["_fuentes"] = ["Metadatos EXIF"]- img, _ = db.upsert_entity(case_id, "image", info["SHA256"], info, root=True)- h, _ = db.upsert_entity(case_id, "hash", info["SHA256"], {"_fuentes": ["Metadatos EXIF"]})- db.add_edge(case_id, img["id"], h["id"], "sha256", "exif")- if "_lat" in info:- lat, lon = info["_lat"], info["_lon"]- loc, _ = db.upsert_entity(case_id, "location", f"{lat}, {lon}", {- "_lat": lat, "_lon": lon, "Precisión": "GPS de la foto",- "_links": [["Google Maps", f"https://www.google.com/maps?q={lat},{lon}"],- ["OpenStreetMap", f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=17/{lat}/{lon}"]],- "_fuentes": ["Metadatos EXIF"],- }, pivot=False)- db.add_edge(case_id, img["id"], loc["id"], "tomada en", "exif")- for key, rel in (("Autor", "autor"), ("Propietario cámara", "propietario"), ("Autor (Windows)", "autor")):- if info.get(key) and len(info[key]) > 2:- p, _ = db.upsert_entity(case_id, "person", info[key], {"_fuentes": ["Metadatos EXIF"]}, pivot=False)- db.add_edge(case_id, img["id"], p["id"], rel, "exif")- db.touch(case_id)+ with db.batch():+ img, _ = db.upsert_entity(case_id, "image", info["SHA256"], info, root=True)+ h, _ = db.upsert_entity(case_id, "hash", info["SHA256"], {"_fuentes": ["Metadatos EXIF"]})+ db.add_edge(case_id, img["id"], h["id"], "sha256", "exif")+ if "_lat" in info:+ lat, lon = info["_lat"], info["_lon"]+ loc, _ = db.upsert_entity(case_id, "location", f"{lat}, {lon}", {+ "_lat": lat, "_lon": lon, "Precisión": "GPS de la foto",+ "_links": [["Google Maps", f"https://www.google.com/maps?q={lat},{lon}"],+ ["OpenStreetMap", f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=17/{lat}/{lon}"]],+ "_fuentes": ["Metadatos EXIF"],+ }, pivot=False)+ db.add_edge(case_id, img["id"], loc["id"], "tomada en", "exif")+ for key, rel in (("Autor", "autor"), ("Propietario cámara", "propietario"), ("Autor (Windows)", "autor")):+ if info.get(key) and len(info[key]) > 2:+ p, _ = db.upsert_entity(case_id, "person", info[key], {"_fuentes": ["Metadatos EXIF"]}, pivot=False)+ db.add_edge(case_id, img["id"], p["id"], rel, "exif")+ db.touch(case_id)return {"entity": img}@@ -350,23 +351,78 @@ def export_case(case_id: int):)+MAX_IMPORT_BYTES = 25 * 1024 * 1024+MAX_IMPORT_ITEMS = 50000++@app.post("/api/import")async def import_case(file: UploadFile = File(...)):+ raw = await file.read(MAX_IMPORT_BYTES + 1)+ if len(raw) > MAX_IMPORT_BYTES:+ raise HTTPException(413, "Archivo demasiado grande (máx. 25 MB)")try:- data = json.loads(await file.read())- src_case = data["case"]- except (ValueError, KeyError) as e:- raise HTTPException(400, "Archivo no válido") from e- case = db.create_case(src_case.get("name", "Importado") + " (importado)")- for e in data.get("entities", []):- db.upsert_entity(case["id"], e["type"], e["value"], e.get("attrs") or {}, root=e.get("root", False),- pivot=e.get("pivot", True))- for ed in data.get("edges", []):- db.add_edge(case["id"], ed["src"], ed["dst"], ed["label"], ed.get("source", "import"))- if src_case.get("notes"):- db.update_case(case["id"], notes=src_case["notes"])- if isinstance(src_case.get("layout"), dict):- db.update_case(case["id"], layout=src_case["layout"])+ data = json.loads(raw)+ except ValueError as e:+ raise HTTPException(400, "JSON no válido") from e+ if not isinstance(data, dict) or not isinstance(data.get("case"), dict):+ raise HTTPException(400, "Archivo de caso no válido")+ src_case = data["case"]+ raw_entities = data.get("entities", [])+ raw_edges = data.get("edges", [])+ if not isinstance(raw_entities, list) or not isinstance(raw_edges, list):+ raise HTTPException(400, "Formato de entidades o aristas no válido")+ if len(raw_entities) > MAX_IMPORT_ITEMS or len(raw_edges) > MAX_IMPORT_ITEMS:+ raise HTTPException(400, f"El archivo supera el máximo de {MAX_IMPORT_ITEMS} elementos")++ validated_entities: list[tuple[str, str, dict, bool, bool, str | None]] = []+ for e in raw_entities:+ if not isinstance(e, dict):+ raise HTTPException(400, "Entidad mal formada en el archivo")+ etype = e.get("type")+ val = e.get("value")+ attrs = e.get("attrs") or {}+ if not isinstance(etype, str) or etype not in ENTITY_TYPES:+ raise HTTPException(400, f"Tipo de entidad no válido: {etype}")+ if not isinstance(val, str) or not val.strip() or len(val) > 4096:+ raise HTTPException(400, "Valor de entidad vacío o demasiado largo")+ if not isinstance(attrs, dict):+ raise HTTPException(400, "Atributos de entidad no válidos")+ orig_id = e.get("id") if isinstance(e.get("id"), str) else None+ validated_entities.append((etype, val, attrs, bool(e.get("root", False)), bool(e.get("pivot", True)), orig_id))++ with db.batch():+ case_name = str(src_case.get("name") or "Importado").strip()[:120] or "Importado"+ case = db.create_case(case_name + " (importado)")+ id_map: dict[str, str] = {}+ valid_ids: set[str] = set()+ for etype, val, attrs, is_root, is_pivot, orig_id in validated_entities:+ ent, _ = db.upsert_entity(case["id"], etype, val, attrs, root=is_root, pivot=is_pivot)+ valid_ids.add(ent["id"])+ id_map[ent["id"]] = ent["id"]+ if orig_id:+ id_map[orig_id] = ent["id"]++ for ed in raw_edges:+ if not isinstance(ed, dict):+ raise HTTPException(400, "Arista mal formada en el archivo")+ raw_src = ed.get("src")+ raw_dst = ed.get("dst")+ if not isinstance(raw_src, str) or not isinstance(raw_dst, str):+ raise HTTPException(400, "Arista con identificadores no válidos")+ src = id_map.get(raw_src)+ dst = id_map.get(raw_dst)+ if not src or not dst or src not in valid_ids or dst not in valid_ids:+ raise HTTPException(400, "Arista apunta a una entidad inexistente en el caso")+ if src == dst:+ continue+ label = " ".join(str(ed.get("label") or "relacionado").split())[:60] or "relacionado"+ source = str(ed.get("source") or "import").strip()[:60] or "import"+ db.add_edge(case["id"], src, dst, label, source)++ if isinstance(src_case.get("notes"), str) and src_case["notes"]:+ db.update_case(case["id"], notes=src_case["notes"][:200000])+ if isinstance(src_case.get("layout"), dict):+ db.update_case(case["id"], layout=src_case["layout"])return case