filewhy 0.2.6__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.
filewhy/__init__.py ADDED
@@ -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"
filewhy/__main__.py ADDED
@@ -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
+ ]
@@ -0,0 +1,241 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from pypdf import PdfReader
8
+ from pypdf.errors import PdfReadError
9
+
10
+ from filewhy.plugin import Finding
11
+
12
+ # pypdf avisa por stderr de cada PDF malformado («invalid pdf header»…) y ensuciaba el informe.
13
+ logging.getLogger("pypdf").setLevel(logging.ERROR)
14
+
15
+ # Acciones que hacen algo más que navegar. Se buscan en la apertura (/OpenAction), en las acciones
16
+ # adicionales (/AA) del documento, de las páginas y de los campos de formulario, y en las
17
+ # anotaciones: antes solo se miraba el árbol /Names, y un /Launch en un enlace pasaba sin aviso.
18
+ _RISKY_ACTIONS = {
19
+ "/JavaScript": ("high", "ejecuta JavaScript"),
20
+ "/Launch": ("high", "abre un programa o fichero externo (/Launch)"),
21
+ "/SubmitForm": ("medium", "envía los datos del formulario a un servidor (/SubmitForm)"),
22
+ "/ImportData": ("medium", "importa datos de un fichero externo (/ImportData)"),
23
+ }
24
+
25
+
26
+ def _looks_like_pdf(path: Path) -> bool:
27
+ """Por la firma: la cabecera %PDF- puede estar en los primeros 1024 bytes. Antes solo se miraba
28
+ la extensión y un PDF sin ella (adjunto «factura») no se analizaba."""
29
+ if path.suffix.lower() == ".pdf":
30
+ return True
31
+ try:
32
+ with path.open("rb") as f:
33
+ return b"%PDF-" in f.read(1024)
34
+ except OSError:
35
+ return False
36
+
37
+
38
+ _RAW_NAME_RE = re.compile(rb"/([A-Za-z0-9#]{2,40})")
39
+ _RAW_HEADER_RE = re.compile(rb"(?:^|[\r\n])%PDF-\d\.\d")
40
+ _RAW_OBJ_RE = re.compile(rb"\d+\s+\d+\s+obj\b")
41
+ _RAW_TOKENS = {
42
+ "JavaScript": ("high", "El PDF contiene JavaScript"),
43
+ "JS": ("high", "El PDF contiene JavaScript"),
44
+ "Launch": ("high", "El PDF abre un programa o fichero externo (/Launch)"),
45
+ "OpenAction": ("medium", "El PDF ejecuta una acción al abrirse (/OpenAction)"),
46
+ "AA": ("medium", "El PDF tiene acciones automáticas (/AA)"),
47
+ "EmbeddedFile": ("medium", "El PDF lleva ficheros embebidos (/EmbeddedFile)"),
48
+ "SubmitForm": ("medium", "El PDF envía datos de formulario a un servidor (/SubmitForm)"),
49
+ "ImportData": ("medium", "El PDF importa datos de un fichero externo (/ImportData)"),
50
+ }
51
+
52
+
53
+ def _raw_scan(path: Path) -> list[Finding]:
54
+ """Revisión a nivel de bytes, para cuando pypdf no puede leer la estructura.
55
+
56
+ Los PDF maliciosos suelen ir malformados a propósito (sin xref, offsets rotos): los lectores
57
+ los reparan y los abren, pero pypdf fallaba y el fichero salía como limpio. Los nombres se
58
+ normalizan (`/J#61vaScript` es `/JavaScript`), como hace pdfid."""
59
+ try:
60
+ data = path.read_bytes()
61
+ except OSError:
62
+ return []
63
+ # Cabecera al principio de una línea y al menos un objeto: un .py o un .pyc que solo contiene
64
+ # el texto «%PDF-» (el propio código de filewhy) no es un PDF.
65
+ if not _RAW_HEADER_RE.search(data[:1024]) or not _RAW_OBJ_RE.search(data):
66
+ return [] # no es un PDF (otro check se encarga de la extensión engañosa)
67
+ names = {
68
+ re.sub(rb"#([0-9A-Fa-f]{2})", lambda m: bytes([int(m.group(1), 16)]), m.group(1)).decode("latin-1")
69
+ for m in _RAW_NAME_RE.finditer(data)
70
+ }
71
+ findings = [
72
+ Finding(
73
+ severity="medium",
74
+ title="PDF malformado: no se pudo leer su estructura, revisado a nivel de bytes",
75
+ detail="Los lectores suelen reparar estos PDF y abrirlos igual. Si el contenido va "
76
+ "comprimido en flujos de objetos, esta revisión puede no verlo.",
77
+ )
78
+ ]
79
+ seen: set[str] = set()
80
+ for token, (severity, title) in _RAW_TOKENS.items():
81
+ if token in names and title not in seen:
82
+ seen.add(title)
83
+ findings.append(Finding(severity=severity, title=title,
84
+ detail="Detectado en los bytes del fichero, no en su estructura."))
85
+ return findings
86
+
87
+
88
+ def _resolve(obj):
89
+ return obj.get_object() if hasattr(obj, "get_object") else obj
90
+
91
+
92
+ def _iter_actions(obj, depth: int = 0):
93
+ """La acción `obj` y las encadenadas con /Next."""
94
+ obj = _resolve(obj)
95
+ if depth > 20 or not hasattr(obj, "get") or "/S" not in obj:
96
+ return
97
+ yield obj
98
+ nxt = _resolve(obj.get("/Next"))
99
+ for item in (nxt if isinstance(nxt, list) else [nxt]) if nxt is not None else []:
100
+ yield from _iter_actions(item, depth + 1)
101
+
102
+
103
+ def _additional_actions(obj):
104
+ aa = _resolve(obj.get("/AA")) if hasattr(obj, "get") else None
105
+ if hasattr(aa, "values"):
106
+ for value in aa.values():
107
+ yield from _iter_actions(value)
108
+
109
+
110
+ def _form_fields(fields, depth: int = 0):
111
+ for ref in _resolve(fields) or []:
112
+ field = _resolve(ref)
113
+ if not hasattr(field, "get") or depth > 20:
114
+ continue
115
+ yield field
116
+ if "/Kids" in field:
117
+ yield from _form_fields(field["/Kids"], depth + 1)
118
+
119
+
120
+ class PdfRiskCheck:
121
+ """Señales de riesgo en PDF: JavaScript embebido, acción de apertura automática,
122
+ ficheros embebidos, y si está cifrado. Solo inspecciona la estructura de objetos
123
+ del PDF -- nunca ejecuta ningún JavaScript ni abre ningún fichero embebido.
124
+ """
125
+
126
+ name = "pdf_risk"
127
+
128
+ def run(self, path: Path) -> list[Finding]:
129
+ if not _looks_like_pdf(path):
130
+ return []
131
+
132
+ try:
133
+ reader = PdfReader(path)
134
+ except (PdfReadError, OSError, ValueError):
135
+ return _raw_scan(path)
136
+
137
+ findings: list[Finding] = []
138
+
139
+ if reader.is_encrypted:
140
+ # Muchos PDF solo llevan contraseña de propietario (la de apertura está vacía): se
141
+ # abren sin pedir nada y antes se dejaban sin revisar.
142
+ try:
143
+ opened = bool(reader.decrypt(""))
144
+ except Exception: # noqa: BLE001 -- cifrado no soportado o roto
145
+ opened = False
146
+ if not opened:
147
+ findings.append(
148
+ Finding(
149
+ severity="info",
150
+ title="El PDF está cifrado/protegido con contraseña",
151
+ )
152
+ )
153
+ return findings # sin la contraseña no se puede inspeccionar más
154
+ findings.append(
155
+ Finding(
156
+ severity="info",
157
+ title="El PDF está cifrado, pero se abre sin contraseña (solo restringe permisos)",
158
+ )
159
+ )
160
+
161
+ try:
162
+ catalog = reader.trailer["/Root"]
163
+ except (KeyError, PdfReadError):
164
+ return findings
165
+
166
+ names = catalog.get("/Names", {}) if hasattr(catalog, "get") else {}
167
+
168
+ if hasattr(names, "get") and "/JavaScript" in names:
169
+ findings.append(
170
+ Finding(
171
+ severity="high",
172
+ title="El PDF contiene JavaScript embebido",
173
+ detail="Revisar el JS antes de abrir el PDF en un lector que lo ejecute.",
174
+ )
175
+ )
176
+
177
+ if hasattr(names, "get") and "/EmbeddedFiles" in names:
178
+ findings.append(
179
+ Finding(
180
+ severity="medium",
181
+ title="El PDF contiene ficheros embebidos",
182
+ detail="Extraer y revisar por separado antes de confiar en ellos.",
183
+ )
184
+ )
185
+
186
+ if hasattr(catalog, "get") and catalog.get("/OpenAction") is not None:
187
+ findings.append(
188
+ Finding(
189
+ severity="medium",
190
+ title="El PDF tiene una acción de apertura automática (/OpenAction)",
191
+ detail="Se ejecuta algo en cuanto se abre el documento -- revisar qué hace.",
192
+ )
193
+ )
194
+
195
+ actions: list[tuple[str, object]] = []
196
+ try:
197
+ if hasattr(catalog, "get"):
198
+ actions += [("la apertura del documento", a) for a in _iter_actions(catalog.get("/OpenAction"))]
199
+ actions += [("un evento del documento", a) for a in _additional_actions(catalog)]
200
+ acroform = _resolve(catalog.get("/AcroForm"))
201
+ if hasattr(acroform, "get") and "/Fields" in acroform:
202
+ for field in _form_fields(acroform["/Fields"]):
203
+ actions += [("un campo de formulario", a) for a in _additional_actions(field)]
204
+ for number, page in enumerate(reader.pages, start=1):
205
+ actions += [(f"la página {number}", a) for a in _additional_actions(page)]
206
+ for annot_ref in page.get("/Annots", []) or []:
207
+ annot = _resolve(annot_ref)
208
+ if not hasattr(annot, "get"):
209
+ continue
210
+ where = f"un enlace o anotación de la página {number}"
211
+ actions += [(where, a) for a in _iter_actions(annot.get("/A"))]
212
+ actions += [(where, a) for a in _additional_actions(annot)]
213
+ except (PdfReadError, KeyError, AttributeError, TypeError, ValueError):
214
+ pass
215
+
216
+ seen: set[tuple[str, str]] = set()
217
+ for where, action in actions:
218
+ kind = action.get("/S")
219
+ if kind == "/URI":
220
+ key = ("uri", str(action.get("/URI")))
221
+ if key not in seen:
222
+ seen.add(key)
223
+ findings.append(
224
+ Finding(
225
+ severity="low",
226
+ title=f"Enlace URI en el PDF: {action.get('/URI')}",
227
+ detail="No necesariamente malicioso -- revisar el destino.",
228
+ )
229
+ )
230
+ elif kind in _RISKY_ACTIONS and (kind, where) not in seen:
231
+ seen.add((kind, where))
232
+ severity, what = _RISKY_ACTIONS[kind]
233
+ findings.append(
234
+ Finding(
235
+ severity=severity,
236
+ title=f"Acción en {where}: {what}",
237
+ detail="Se ejecuta al abrir o al interactuar con el PDF -- revisar antes de abrirlo.",
238
+ )
239
+ )
240
+
241
+ return findings
filewhy/cli.py ADDED
@@ -0,0 +1,85 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from filewhy import __version__
8
+ from filewhy.plugin import SEVERITIES
9
+ from filewhy.report import to_console, to_json, worst_severity
10
+ from filewhy.runner import analyze_path, discover_checks
11
+
12
+ _SEVERITY_ORDER = {sev: idx for idx, sev in enumerate(SEVERITIES)}
13
+
14
+
15
+ def _cmd_scan(args: argparse.Namespace) -> int:
16
+ path = Path(args.path).resolve()
17
+ only = set(args.only) if args.only else None
18
+ skip = set(args.skip) if args.skip else None
19
+
20
+ # Sin esto, una ruta mal escrita o un check con errata daban «0 hallazgos» y exit 0.
21
+ if not path.exists():
22
+ print(f"error: {path} no existe", file=sys.stderr)
23
+ return 2
24
+ unknown = ((only or set()) | (skip or set())) - set(discover_checks())
25
+ if unknown:
26
+ print(f"error: check(s) desconocido(s): {', '.join(sorted(unknown))} "
27
+ "(ver `filewhy list-checks`)", file=sys.stderr)
28
+ return 2
29
+
30
+ reports = analyze_path(path, only=only, skip=skip)
31
+
32
+ if args.json:
33
+ print(to_json(reports))
34
+ else:
35
+ print(to_console(reports))
36
+
37
+ # Un check que revienta deja el fichero sin revisar del todo: antes era un hallazgo «medium» más
38
+ # y con --fail-on high el CI pasaba por verde.
39
+ failed = sorted({r.path for r in reports for f in r.findings if f.check_error})
40
+ if failed:
41
+ print(f"error: hubo checks que no se pudieron ejecutar en: {', '.join(failed)} "
42
+ "(análisis incompleto)", file=sys.stderr)
43
+ return 2
44
+
45
+ if args.fail_on:
46
+ worst = worst_severity(reports)
47
+ if worst is not None and _SEVERITY_ORDER[worst] >= _SEVERITY_ORDER[args.fail_on]:
48
+ return 1
49
+ return 0
50
+
51
+
52
+ def _cmd_list_checks(args: argparse.Namespace) -> int:
53
+ for name, cls in sorted(discover_checks().items()):
54
+ doc = (cls.__doc__ or "").strip().splitlines()[0] if cls.__doc__ else ""
55
+ print(f"{name}: {doc}")
56
+ return 0
57
+
58
+
59
+ def build_parser() -> argparse.ArgumentParser:
60
+ parser = argparse.ArgumentParser(prog="filewhy")
61
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
62
+ sub = parser.add_subparsers(dest="command", required=True)
63
+
64
+ p_scan = sub.add_parser("scan", help="Analiza un fichero o carpeta")
65
+ p_scan.add_argument("path")
66
+ p_scan.add_argument("--only", action="append", help="Ejecutar solo este check (repetible)")
67
+ p_scan.add_argument("--skip", action="append", help="Saltar este check (repetible)")
68
+ p_scan.add_argument("--json", action="store_true")
69
+ p_scan.add_argument("--fail-on", choices=SEVERITIES, default=None)
70
+ p_scan.set_defaults(func=_cmd_scan)
71
+
72
+ p_list = sub.add_parser("list-checks", help="Lista los checks instalados")
73
+ p_list.set_defaults(func=_cmd_list_checks)
74
+
75
+ return parser
76
+
77
+
78
+ def main(argv: list[str] | None = None) -> int:
79
+ parser = build_parser()
80
+ args = parser.parse_args(argv)
81
+ return args.func(args)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ sys.exit(main())
filewhy/plugin.py ADDED
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Protocol
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+ Severity = str
9
+ SEVERITIES: tuple[Severity, ...] = ("info", "low", "medium", "high")
10
+
11
+
12
+ class Finding(BaseModel):
13
+ severity: Severity
14
+ title: str
15
+ detail: str = ""
16
+ check_error: bool = False # el check reventó: el fichero no se ha revisado del todo
17
+
18
+ def model_post_init(self, context: object, /) -> None:
19
+ if self.severity not in SEVERITIES:
20
+ raise ValueError(f"severity {self.severity!r} no es una de {SEVERITIES}")
21
+
22
+
23
+ class FileReport(BaseModel):
24
+ path: str
25
+ findings: list[Finding] = Field(default_factory=list)
26
+
27
+
28
+ class Check(Protocol):
29
+ name: str
30
+
31
+ def run(self, path: Path) -> list[Finding]: ...
filewhy/report.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from filewhy.plugin import SEVERITIES, FileReport
6
+
7
+ _SEVERITY_ORDER = {sev: idx for idx, sev in enumerate(SEVERITIES)}
8
+
9
+
10
+ def worst_severity(reports: list[FileReport]) -> str | None:
11
+ sevs = [f.severity for r in reports for f in r.findings]
12
+ if not sevs:
13
+ return None
14
+ return max(sevs, key=lambda s: _SEVERITY_ORDER[s])
15
+
16
+
17
+ def to_console(reports: list[FileReport]) -> str:
18
+ with_findings = [r for r in reports if r.findings]
19
+ if not with_findings:
20
+ return f"{len(reports)} fichero(s) analizados, 0 hallazgo(s)."
21
+
22
+ lines = []
23
+ for r in with_findings:
24
+ lines.append(f"── {r.path} " + "─" * max(0, 50 - len(r.path)))
25
+ for f in r.findings:
26
+ label = f"[{f.severity.upper():<6}]"
27
+ lines.append(f" {label} {f.title}")
28
+ if f.detail:
29
+ lines.append(f" {f.detail}")
30
+ lines.append("")
31
+
32
+ total = sum(len(r.findings) for r in reports)
33
+ lines.append(f"Total: {total} hallazgo(s) en {len(with_findings)} de {len(reports)} fichero(s).")
34
+ return "\n".join(lines)
35
+
36
+
37
+ def to_json(reports: list[FileReport]) -> str:
38
+ return json.dumps([r.model_dump() for r in reports], ensure_ascii=False, indent=2)
filewhy/runner.py ADDED
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import traceback
4
+ from importlib.metadata import entry_points
5
+ from pathlib import Path
6
+
7
+ from filewhy.plugin import Check, FileReport, Finding
8
+
9
+ ENTRY_POINT_GROUP = "filewhy.checks"
10
+
11
+
12
+ def discover_checks() -> dict[str, type[Check]]:
13
+ found: dict[str, type[Check]] = {}
14
+ for ep in entry_points(group=ENTRY_POINT_GROUP):
15
+ found[ep.name] = ep.load()
16
+ return found
17
+
18
+
19
+ def analyze_file(
20
+ path: Path, *, only: set[str] | None = None, skip: set[str] | None = None
21
+ ) -> FileReport:
22
+ checks = discover_checks()
23
+ names = set(checks) if only is None else (set(checks) & only)
24
+ if skip:
25
+ names -= skip
26
+
27
+ findings: list[Finding] = []
28
+ for name in sorted(names):
29
+ try:
30
+ findings.extend(checks[name]().run(path))
31
+ except Exception as exc: # noqa: BLE001 -- aislar un check roto del resto del escaneo
32
+ findings.append(
33
+ Finding(
34
+ severity="medium", title=f"Check '{name}' falló: {exc}",
35
+ detail=traceback.format_exc(), check_error=True,
36
+ )
37
+ )
38
+ return FileReport(path=str(path), findings=findings)
39
+
40
+
41
+ def analyze_path(
42
+ root: Path, *, only: set[str] | None = None, skip: set[str] | None = None
43
+ ) -> list[FileReport]:
44
+ if root.is_file():
45
+ files = [root]
46
+ else:
47
+ files = sorted(p for p in root.rglob("*") if p.is_file())
48
+
49
+ return [analyze_file(f, only=only, skip=skip) for f in files]
@@ -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,16 @@
1
+ filewhy/__init__.py,sha256=5wxoU3-SbP4pgJDO3dT1I7HUMeG9q1HzPwxD1bLFTvY,113
2
+ filewhy/__main__.py,sha256=4J05OubMpTBO9vi-cL85G1jh68VGHhgcEScQ6CGIH40,90
3
+ filewhy/cli.py,sha256=q4nrvZP4U3KVxaJpGy7PnutDICbCVA8yrzxhT-zquw8,3018
4
+ filewhy/plugin.py,sha256=kJxVHdnkDczgPiLyljr8jBJ52KTvovY3t00tD3FPR80,775
5
+ filewhy/report.py,sha256=vALA96aUULMdMCInE8jehaXMCF449lOczfBJtLNhw0M,1257
6
+ filewhy/runner.py,sha256=5uCHXyiZvmZSsRkU7w6cmO6TCoNjxVAHrat2oQ5H30M,1484
7
+ filewhy/checks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ filewhy/checks/archive_risk.py,sha256=YodopODELZ7k0uTRD1gIz8CrBMwxRslLWmtZ-8D1T_M,6050
9
+ filewhy/checks/file_identity.py,sha256=oYOkNiE4MRuKkLAJ77swpWhK9UdAwpiVReLOTRstC5U,2847
10
+ filewhy/checks/pdf_risk.py,sha256=trkoK9yKkwJn5N6-IlsbK8VAT8G9ft-SC1syuuXm52c,10052
11
+ filewhy-0.2.6.dist-info/licenses/LICENSE,sha256=70acRqGbi12E-RBHctB4yHLzZOoCFayZUXlhAUvwaAM,1080
12
+ filewhy-0.2.6.dist-info/METADATA,sha256=KtU_Wr5eT2HZ1aloDPCSLcPOBZADThr47PoA5PFqwOM,5575
13
+ filewhy-0.2.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ filewhy-0.2.6.dist-info/entry_points.txt,sha256=FrGkI9XSB7kmcpOKCLtw9--2GAE8axHSIW72wiWScMw,234
15
+ filewhy-0.2.6.dist-info/top_level.txt,sha256=MkhNlBSqdV_8A4j1_UHKDCM7pcl-UrorlrUIK5YeQ2g,8
16
+ filewhy-0.2.6.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,7 @@
1
+ [console_scripts]
2
+ filewhy = filewhy.cli:main
3
+
4
+ [filewhy.checks]
5
+ archive_risk = filewhy.checks.archive_risk:ArchiveRiskCheck
6
+ file_identity = filewhy.checks.file_identity:FileIdentityCheck
7
+ pdf_risk = filewhy.checks.pdf_risk:PdfRiskCheck
@@ -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.
@@ -0,0 +1 @@
1
+ filewhy