filewhy 0.2.6__tar.gz

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.
filewhy-0.2.6/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 José Luis Segura Yuste
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
filewhy-0.2.6/PKG-INFO ADDED
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: filewhy
3
+ Version: 0.2.6
4
+ Summary: Agregador de señales de riesgo entre formatos de fichero (identidad real vs extensión, riesgos de ZIP/JAR/APK, riesgos de PDF) en un solo informe -- sin ejecutar ni abrir nada peligroso.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/filewhy
8
+ Project-URL: Source, https://github.com/jl-segurayuste/filewhy
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/filewhy/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/filewhy/releases
11
+ Keywords: security,file-analysis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: Spanish
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Security
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: pydantic>=2.6
28
+ Requires-Dist: pypdf>=4.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.4; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5; extra == "dev"
32
+ Requires-Dist: ruff==0.17.6; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # filewhy
36
+
37
+ [![PyPI](https://img.shields.io/pypi/v/filewhy.svg)](https://pypi.org/project/filewhy/)
38
+ [![CI](https://github.com/jl-segurayuste/filewhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/filewhy/actions/workflows/ci.yml)
39
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/filewhy/blob/main/pyproject.toml)
40
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/filewhy/blob/main/LICENSE)
41
+
42
+ `file` con esteroides, pero como agregador: en vez de una herramienta por
43
+ formato, un solo informe con las señales de riesgo que de verdad importan —
44
+ sin ejecutar ni abrir nada peligroso.
45
+
46
+ ```
47
+ $ filewhy scan ./descargas
48
+
49
+ ── descargas/foto_vacaciones.jpg ──────────────────
50
+ [HIGH ] Extensión '.jpg' pero el contenido real es PE/EXE (Windows)
51
+ El fichero no es lo que su extensión afirma -- revisar antes de abrirlo o ejecutarlo.
52
+
53
+ ── descargas/factura.pdf ───────────────────────────
54
+ [HIGH ] El PDF contiene JavaScript embebido
55
+ Revisar el JS antes de abrir el PDF en un lector que lo ejecute.
56
+
57
+ Total: 2 hallazgo(s) en 2 de 15 fichero(s).
58
+ ```
59
+
60
+ ## Así se ve
61
+
62
+ ![Salida de filewhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/filewhy/main/docs/img/demo.svg)
63
+
64
+ <sub>Ejecución real sobre una carpeta de descargas con un ejecutable disfrazado de PDF, un PDF con JavaScript y un ZIP con path traversal (todos los datos son ficticios).</sub>
65
+
66
+ ## Por qué existe
67
+
68
+ Ya existen buenas herramientas por formato (analizadores de PDF, de APK, de
69
+ ZIP...), pero ninguna que las agregue en un único informe de riesgo —
70
+ exactamente el mismo hueco que llevó a construir
71
+ [checkforge](https://github.com/jl-segurayuste/checkforge) para repos de
72
+ código. `filewhy` hace lo mismo para ficheros sueltos: identidad real vs.
73
+ extensión, riesgos estructurales de archivos ZIP-based (ZIP/JAR/APK/DOCX/
74
+ XLSX), y riesgos de PDF.
75
+
76
+ ## Instalación
77
+
78
+ Todavía no está en PyPI:
79
+
80
+ ```bash
81
+ pipx install filewhy # recomendado para herramientas de línea de comandos
82
+ # o bien
83
+ pip install filewhy
84
+ ```
85
+
86
+ ## Uso
87
+
88
+ ```bash
89
+ filewhy scan fichero.pdf
90
+ filewhy scan ./carpeta # recursivo
91
+ filewhy scan ./carpeta --only file_identity
92
+ filewhy scan ./carpeta --json
93
+ filewhy scan ./carpeta --fail-on high # código de salida 1 si hay algo "high"
94
+ # código 2 si algún check no se pudo ejecutar (análisis incompleto)
95
+ filewhy list-checks
96
+ ```
97
+
98
+ ## Checks incluidos
99
+
100
+ | Check | Qué detecta |
101
+ |---|---|
102
+ | `file_identity` | La extensión promete un tipo, pero la firma de bytes real es otra (un `.jpg` que en realidad es un ejecutable, un `.pdf` que es un documento OLE de Office con posibles macros, un RAR o 7-Zip renombrado) |
103
+ | `archive_risk` | En ZIP/JAR/APK/DOCX/XLSX: path traversal ("zip-slip"), enlaces simbólicos, miembros ejecutables (también `.lnk`, `.scr`… y scripts `.js`/`.vbs`/`.hta` en la raíz), miembros cifrados, macros VBA y objetos OLE en documentos de Office, ratio de compresión sospechoso (posible zip bomb, también repartida en varios miembros) |
104
+ | `pdf_risk` | JavaScript embebido, apertura automática (`/OpenAction`), acciones `/JavaScript`, `/Launch`, `/SubmitForm` e `/ImportData` en la apertura, en eventos del documento, de las páginas, de los campos y en los enlaces; ficheros embebidos, enlaces URI, si está cifrado (los que se abren sin contraseña se revisan igual). Reconoce el PDF por su firma aunque no tenga extensión. Si el PDF está malformado (los maliciosos suelen estarlo y los lectores los reparan), lo revisa a nivel de bytes en vez de darlo por limpio |
105
+
106
+ Ningún check extrae archivos a disco, ejecuta JavaScript, ni abre ficheros
107
+ embebidos — solo lee metadatos/estructura (vía `zipfile`/`pypdf`, ambas
108
+ bibliotecas maduras que no ejecutan contenido).
109
+
110
+ ## Desarrollo
111
+
112
+ ```bash
113
+ pip install -e ".[dev]"
114
+ ruff check .
115
+ pytest
116
+ ```
@@ -0,0 +1,82 @@
1
+ # filewhy
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/filewhy.svg)](https://pypi.org/project/filewhy/)
4
+ [![CI](https://github.com/jl-segurayuste/filewhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/filewhy/actions/workflows/ci.yml)
5
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/filewhy/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/filewhy/blob/main/LICENSE)
7
+
8
+ `file` con esteroides, pero como agregador: en vez de una herramienta por
9
+ formato, un solo informe con las señales de riesgo que de verdad importan —
10
+ sin ejecutar ni abrir nada peligroso.
11
+
12
+ ```
13
+ $ filewhy scan ./descargas
14
+
15
+ ── descargas/foto_vacaciones.jpg ──────────────────
16
+ [HIGH ] Extensión '.jpg' pero el contenido real es PE/EXE (Windows)
17
+ El fichero no es lo que su extensión afirma -- revisar antes de abrirlo o ejecutarlo.
18
+
19
+ ── descargas/factura.pdf ───────────────────────────
20
+ [HIGH ] El PDF contiene JavaScript embebido
21
+ Revisar el JS antes de abrir el PDF en un lector que lo ejecute.
22
+
23
+ Total: 2 hallazgo(s) en 2 de 15 fichero(s).
24
+ ```
25
+
26
+ ## Así se ve
27
+
28
+ ![Salida de filewhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/filewhy/main/docs/img/demo.svg)
29
+
30
+ <sub>Ejecución real sobre una carpeta de descargas con un ejecutable disfrazado de PDF, un PDF con JavaScript y un ZIP con path traversal (todos los datos son ficticios).</sub>
31
+
32
+ ## Por qué existe
33
+
34
+ Ya existen buenas herramientas por formato (analizadores de PDF, de APK, de
35
+ ZIP...), pero ninguna que las agregue en un único informe de riesgo —
36
+ exactamente el mismo hueco que llevó a construir
37
+ [checkforge](https://github.com/jl-segurayuste/checkforge) para repos de
38
+ código. `filewhy` hace lo mismo para ficheros sueltos: identidad real vs.
39
+ extensión, riesgos estructurales de archivos ZIP-based (ZIP/JAR/APK/DOCX/
40
+ XLSX), y riesgos de PDF.
41
+
42
+ ## Instalación
43
+
44
+ Todavía no está en PyPI:
45
+
46
+ ```bash
47
+ pipx install filewhy # recomendado para herramientas de línea de comandos
48
+ # o bien
49
+ pip install filewhy
50
+ ```
51
+
52
+ ## Uso
53
+
54
+ ```bash
55
+ filewhy scan fichero.pdf
56
+ filewhy scan ./carpeta # recursivo
57
+ filewhy scan ./carpeta --only file_identity
58
+ filewhy scan ./carpeta --json
59
+ filewhy scan ./carpeta --fail-on high # código de salida 1 si hay algo "high"
60
+ # código 2 si algún check no se pudo ejecutar (análisis incompleto)
61
+ filewhy list-checks
62
+ ```
63
+
64
+ ## Checks incluidos
65
+
66
+ | Check | Qué detecta |
67
+ |---|---|
68
+ | `file_identity` | La extensión promete un tipo, pero la firma de bytes real es otra (un `.jpg` que en realidad es un ejecutable, un `.pdf` que es un documento OLE de Office con posibles macros, un RAR o 7-Zip renombrado) |
69
+ | `archive_risk` | En ZIP/JAR/APK/DOCX/XLSX: path traversal ("zip-slip"), enlaces simbólicos, miembros ejecutables (también `.lnk`, `.scr`… y scripts `.js`/`.vbs`/`.hta` en la raíz), miembros cifrados, macros VBA y objetos OLE en documentos de Office, ratio de compresión sospechoso (posible zip bomb, también repartida en varios miembros) |
70
+ | `pdf_risk` | JavaScript embebido, apertura automática (`/OpenAction`), acciones `/JavaScript`, `/Launch`, `/SubmitForm` e `/ImportData` en la apertura, en eventos del documento, de las páginas, de los campos y en los enlaces; ficheros embebidos, enlaces URI, si está cifrado (los que se abren sin contraseña se revisan igual). Reconoce el PDF por su firma aunque no tenga extensión. Si el PDF está malformado (los maliciosos suelen estarlo y los lectores los reparan), lo revisa a nivel de bytes en vez de darlo por limpio |
71
+
72
+ Ningún check extrae archivos a disco, ejecuta JavaScript, ni abre ficheros
73
+ embebidos — solo lee metadatos/estructura (vía `zipfile`/`pypdf`, ambas
74
+ bibliotecas maduras que no ejecutan contenido).
75
+
76
+ ## Desarrollo
77
+
78
+ ```bash
79
+ pip install -e ".[dev]"
80
+ ruff check .
81
+ pytest
82
+ ```
@@ -0,0 +1,3 @@
1
+ """filewhy — agrega señales de riesgo entre formatos de fichero en un solo informe."""
2
+
3
+ __version__ = "0.2.6"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from filewhy.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
File without changes
@@ -0,0 +1,150 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import stat
5
+ import zipfile
6
+ from pathlib import Path
7
+
8
+ from filewhy.plugin import Finding
9
+
10
+ _EXECUTABLE_SUFFIXES = {
11
+ ".exe", ".dll", ".so", ".sh", ".bat", ".cmd", ".ps1",
12
+ # Los de las campañas de malware por correo: accesos directos, salvapantallas, instaladores…
13
+ ".lnk", ".scr", ".pif", ".cpl", ".msi", ".com", ".reg",
14
+ }
15
+ # Scripts que Windows ejecuta con doble clic. Solo cuentan en la raíz del archivo: dentro de
16
+ # carpetas (una web, un proyecto) un .js es lo normal.
17
+ _ROOT_SCRIPT_SUFFIXES = {".js", ".jse", ".vbs", ".vbe", ".wsf", ".wsh", ".hta"}
18
+ _BOMB_RATIO_THRESHOLD = 100 # tamaño descomprimido / comprimido
19
+ _BOMB_TOTAL_BYTES = 1024 ** 3
20
+
21
+ # Unidad de Windows tipo "C:\..." o "C:/..." -- absoluto aunque no empiece
22
+ # por "/". El propio ZIP no obliga a usar "/" como separador: herramientas
23
+ # que crean el archivo en Windows (o construido a mano, como haría un
24
+ # atacante) pueden usar "\" -- Path(...).parts en Linux NO lo trata como
25
+ # separador, así que ".." solo se detectaría con "/". Por eso el traversal
26
+ # se busca sobre el nombre normalizado a "/" en vez de fiarse solo de
27
+ # Path(name).parts.
28
+ _WINDOWS_DRIVE = re.compile(r"^[A-Za-z]:[\\/]")
29
+
30
+
31
+ class ArchiveRiskCheck:
32
+ """Riesgos estructurales en ZIP/JAR/APK/DOCX/XLSX (todos son contenedores ZIP):
33
+ path traversal ("zip-slip"), miembros ejecutables, ratio de compresión sospechoso
34
+ (posible zip bomb). Nunca extrae nada a disco -- solo lee los metadatos del índice.
35
+ """
36
+
37
+ name = "archive_risk"
38
+
39
+ def run(self, path: Path) -> list[Finding]:
40
+ try:
41
+ if not zipfile.is_zipfile(path):
42
+ return []
43
+ except OSError:
44
+ return []
45
+
46
+ findings: list[Finding] = []
47
+ try:
48
+ with zipfile.ZipFile(path) as zf:
49
+ infos = zf.infolist()
50
+ for info in infos:
51
+ findings.extend(self._check_member(info))
52
+ except (zipfile.BadZipFile, OSError, EOFError):
53
+ return []
54
+
55
+ # Bomba repartida en muchos miembros (cada uno por debajo del umbral individual)
56
+ total = sum(i.file_size for i in infos)
57
+ packed = sum(i.compress_size for i in infos)
58
+ if total > _BOMB_TOTAL_BYTES and packed and total / packed > _BOMB_RATIO_THRESHOLD and not any(
59
+ f.title.startswith("Ratio de compresión") for f in findings
60
+ ):
61
+ findings.append(
62
+ Finding(
63
+ severity="high",
64
+ title=f"El archivo se expande a {total // 1024 ** 2} MB ({total / packed:.0f}x)",
65
+ detail="Posible zip bomb repartida en varios miembros.",
66
+ )
67
+ )
68
+
69
+ return findings
70
+
71
+ def _check_member(self, info: zipfile.ZipInfo) -> list[Finding]:
72
+ findings: list[Finding] = []
73
+ name = info.filename
74
+
75
+ normalized = name.replace("\\", "/")
76
+ if name.startswith("/") or _WINDOWS_DRIVE.match(name) or ".." in Path(normalized).parts:
77
+ findings.append(
78
+ Finding(
79
+ severity="high",
80
+ title=f"Path traversal en miembro del archivo: {name}",
81
+ detail="Extraer este ZIP tal cual podría escribir fuera del directorio destino ('zip-slip').",
82
+ )
83
+ )
84
+
85
+ if stat.S_ISLNK(info.external_attr >> 16):
86
+ findings.append(
87
+ Finding(
88
+ severity="high",
89
+ title=f"Enlace simbólico dentro del archivo: {name}",
90
+ detail="Al extraerlo puede apuntar fuera del destino y hacer que otro miembro escriba allí.",
91
+ )
92
+ )
93
+
94
+ if info.flag_bits & 0x1:
95
+ findings.append(
96
+ Finding(
97
+ severity="medium",
98
+ title=f"Miembro cifrado: {name}",
99
+ detail="Su contenido no se puede revisar sin la contraseña (táctica habitual para esquivar antivirus).",
100
+ )
101
+ )
102
+
103
+ lower = normalized.lower()
104
+ if lower.endswith("vbaproject.bin"):
105
+ findings.append(
106
+ Finding(
107
+ severity="high",
108
+ title="El documento contiene macros VBA",
109
+ detail="Se ejecutan al habilitar el contenido -- no habilitarlas sin revisar.",
110
+ )
111
+ )
112
+ elif "/embeddings/" in lower and lower.endswith(".bin"):
113
+ findings.append(
114
+ Finding(
115
+ severity="medium",
116
+ title=f"Objeto OLE incrustado: {name}",
117
+ detail="Puede contener un ejecutable o un documento con macros.",
118
+ )
119
+ )
120
+
121
+ suffix = Path(normalized).suffix.lower()
122
+ if suffix in _ROOT_SCRIPT_SUFFIXES and "/" not in normalized.strip("/"):
123
+ findings.append(
124
+ Finding(
125
+ severity="high",
126
+ title=f"Script ejecutable en la raíz del archivo: {name}",
127
+ detail="Windows lo ejecuta con un doble clic -- típico de adjuntos maliciosos.",
128
+ )
129
+ )
130
+ if suffix in _EXECUTABLE_SUFFIXES:
131
+ findings.append(
132
+ Finding(
133
+ severity="medium",
134
+ title=f"Miembro ejecutable dentro del archivo: {name}",
135
+ detail="Puede ser legítimo (p.ej. un APK real trae .so) -- revisar si es lo esperado.",
136
+ )
137
+ )
138
+
139
+ if info.compress_size > 0:
140
+ ratio = info.file_size / info.compress_size
141
+ if ratio > _BOMB_RATIO_THRESHOLD and info.file_size > 10 * 1024 * 1024:
142
+ findings.append(
143
+ Finding(
144
+ severity="high",
145
+ title=f"Ratio de compresión sospechoso en {name} ({ratio:.0f}x)",
146
+ detail="Posible zip bomb -- extraerlo podría agotar disco/memoria.",
147
+ )
148
+ )
149
+
150
+ return findings
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from filewhy.plugin import Finding
6
+
7
+ # (nombre, firma de bytes, offset) -- de más específica a más genérica.
8
+ _SIGNATURES: list[tuple[str, bytes, int]] = [
9
+ ("PDF", b"%PDF-", 0),
10
+ ("ZIP", b"PK\x03\x04", 0),
11
+ ("ZIP (vacío)", b"PK\x05\x06", 0),
12
+ ("PE/EXE (Windows)", b"MZ", 0),
13
+ ("ELF (Linux)", b"\x7fELF", 0),
14
+ ("PNG", b"\x89PNG\r\n\x1a\n", 0),
15
+ ("JPEG", b"\xff\xd8\xff", 0),
16
+ ("GIF", b"GIF87a", 0),
17
+ ("GIF", b"GIF89a", 0),
18
+ ("GZIP", b"\x1f\x8b", 0),
19
+ ("OLE (Office antiguo: .doc/.xls/.ppt/.msi)", b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", 0),
20
+ ("RAR", b"Rar!\x1a\x07", 0),
21
+ ("7-Zip", b"7z\xbc\xaf\x27\x1c", 0),
22
+ ]
23
+
24
+ _ZIP = {"ZIP", "ZIP (vacío)"}
25
+ _OLE = "OLE (Office antiguo: .doc/.xls/.ppt/.msi)"
26
+
27
+ # Extensión -> nombres de firma que serían normales para ella.
28
+ _EXPECTED: dict[str, set[str]] = {
29
+ ".pdf": {"PDF"},
30
+ ".zip": {"ZIP", "ZIP (vacío)"},
31
+ ".jar": {"ZIP", "ZIP (vacío)"},
32
+ ".apk": {"ZIP", "ZIP (vacío)"},
33
+ ".docx": {"ZIP", "ZIP (vacío)"},
34
+ ".xlsx": {"ZIP", "ZIP (vacío)"},
35
+ ".pptx": {"ZIP", "ZIP (vacío)"},
36
+ ".exe": {"PE/EXE (Windows)"},
37
+ ".dll": {"PE/EXE (Windows)"},
38
+ ".png": {"PNG"},
39
+ ".jpg": {"JPEG"},
40
+ ".jpeg": {"JPEG"},
41
+ ".gif": {"GIF"},
42
+ ".gz": {"GZIP"},
43
+ ".tgz": {"GZIP"},
44
+ ".docm": _ZIP,
45
+ ".xlsm": _ZIP,
46
+ ".pptm": _ZIP,
47
+ ".odt": _ZIP,
48
+ ".ods": _ZIP,
49
+ ".odp": _ZIP,
50
+ ".epub": _ZIP,
51
+ ".doc": {_OLE},
52
+ ".xls": {_OLE},
53
+ ".ppt": {_OLE},
54
+ ".msi": {_OLE},
55
+ ".rar": {"RAR"},
56
+ ".7z": {"7-Zip"},
57
+ }
58
+
59
+
60
+ def detect_real_type(path: Path) -> str | None:
61
+ try:
62
+ with path.open("rb") as f:
63
+ header = f.read(16) # read_bytes() cargaba en memoria el fichero entero (una ISO de 4 GB)
64
+ except OSError:
65
+ return None
66
+ for name, magic, offset in _SIGNATURES:
67
+ if header[offset : offset + len(magic)] == magic:
68
+ return name
69
+ return None
70
+
71
+
72
+ class FileIdentityCheck:
73
+ """Compara el tipo real del fichero (firma de bytes) contra lo que su extensión promete."""
74
+
75
+ name = "file_identity"
76
+
77
+ def run(self, path: Path) -> list[Finding]:
78
+ ext = path.suffix.lower()
79
+ expected = _EXPECTED.get(ext)
80
+ if expected is None:
81
+ return [] # extensión no vigilada -- no aplica
82
+
83
+ real_type = detect_real_type(path)
84
+ if real_type is None:
85
+ return [] # no reconocido -- podría ser texto plano legítimo, no forzar
86
+
87
+ if real_type in expected:
88
+ return []
89
+
90
+ return [
91
+ Finding(
92
+ severity="high",
93
+ title=f"Extensión '{ext}' pero el contenido real es {real_type}",
94
+ detail="El fichero no es lo que su extensión afirma -- revisar antes de abrirlo o ejecutarlo.",
95
+ )
96
+ ]