fix(security): defusedxml для парса user-XML (пентест XXE-DOS-01)

Половина XML-парсеров была на defusedxml, половина на сыром xml.etree (тот же
паттерн «guard точечно»). Хост-side парсеры (_preprocess_xlsx, xlsx_utils) крутятся
без mem-капа → billion-laughs = память-DoS всего сервера. Все parse/fromstring
user-XML (.gge/.xlsx) переведены на defusedxml (forbid_dtd). Создание XML (ET.Element
в gge_deep) осталось на stdlib. Хирургически — заменены только вызовы, не модуль.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-19 13:36:50 +10:00
co-authored by Claude Opus 4.8
parent fba821fb5e
commit fd5eb5ed1c
5 changed files with 18 additions and 14 deletions
+5 -4
View File
@@ -49,6 +49,7 @@ def _preprocess_xlsx(work_dir: Path):
Runs BEFORE Claude sees the files — transparent to user."""
import zipfile
import xml.etree.ElementTree as ET
from defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01)
import csv
for f in work_dir.iterdir():
@@ -68,17 +69,17 @@ def _preprocess_xlsx(work_dir: Path):
# Read shared strings
strings = []
try:
ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
ss = _safe_parse(z.open('xl/sharedStrings.xml')).getroot()
for si in ss.findall('.//s:si', ns):
strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
except KeyError:
pass
# Get sheet names
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
wb = _safe_parse(z.open('xl/workbook.xml')).getroot()
sheets = [(s.attrib.get('name', ''), s.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', ''))
for s in wb.findall('.//s:sheet', ns)]
# Read rels to map rId to file
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
rels = _safe_parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
rid_map = {r.get('{http://schemas.openxmlformats.org/package/2006/relationships}id', r.get('Id', '')): r.get('Target', '')
for r in rels.findall('.//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship')}
# Convert each sheet to CSV
@@ -90,7 +91,7 @@ def _preprocess_xlsx(work_dir: Path):
continue
sheet_path = f'xl/{target}'
try:
sheet_xml = ET.parse(z.open(sheet_path)).getroot()
sheet_xml = _safe_parse(z.open(sheet_path)).getroot()
except KeyError:
continue
csv_path = csv_dir / f'{sheet_name}.csv'
+4 -3
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01)
from pathlib import Path
# Проект-специфичные идентификаторы для обезличивания (scrub в индексаторах).
@@ -154,7 +155,7 @@ def parse_estimate_full(path: Path) -> dict:
"""Полный разбор ЛСР/ОСР. Возвращает estimate-метаданные + позиции с
ресурсным составом, ценами база/текущие, накладными/прибылью, коэффициентами."""
try:
root = ET.parse(str(path)).getroot()
root = _safe_parse(str(path)).getroot()
except (ET.ParseError, OSError) as e:
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
@@ -256,7 +257,7 @@ def parse_estimate_full(path: Path) -> dict:
def parse_vor(path: Path) -> dict:
"""Разбор ВОР (QuantityTakeoff): секции → работы (объём, формула, ссылка)."""
try:
root = ET.parse(str(path)).getroot()
root = _safe_parse(str(path)).getroot()
except (ET.ParseError, OSError) as e:
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
@@ -296,7 +297,7 @@ def parse_ka(data: bytes) -> list[dict]:
обезличивания индексатором).
"""
try:
root = ET.fromstring(data)
root = _safe_fromstring(data)
except ET.ParseError:
return []
items = []
+3 -2
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import zipfile
import xml.etree.ElementTree as ET
from defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01)
from pathlib import Path
@@ -99,7 +100,7 @@ def parse_gge_file(path: Path) -> dict:
тоже включаем).
"""
try:
tree = ET.parse(str(path))
tree = _safe_parse(str(path))
except (ET.ParseError, OSError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
root = tree.getroot()
@@ -219,7 +220,7 @@ def _safe_xml_root(data: bytes):
from defusedxml.ElementTree import fromstring as _fromstring
return _fromstring(data)
except ImportError:
return ET.fromstring(data)
return _safe_fromstring(data)
def parse_gsfx_file(path: Path) -> dict:
+1 -1
View File
@@ -151,7 +151,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-19d"
APP_VERSION = "2026-07-19e"
# Audit: path → action name mapping
_AUDIT_MAP = [
+5 -4
View File
@@ -2,6 +2,7 @@
import zipfile
import xml.etree.ElementTree as ET
from defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01)
from pathlib import Path
@@ -14,14 +15,14 @@ def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
# Shared strings
strings = []
try:
ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
ss = _safe_parse(z.open('xl/sharedStrings.xml')).getroot()
for si in ss.findall('.//s:si', ns):
strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
except KeyError:
pass
# Sheet names and rels
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
wb = _safe_parse(z.open('xl/workbook.xml')).getroot()
rels = _safe_parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
rid_map = {}
for r in rels.iter():
rid = r.get('Id', '')
@@ -42,7 +43,7 @@ def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
else:
sheet_path = f'xl/{target}'
try:
sheet_xml = ET.parse(z.open(sheet_path)).getroot()
sheet_xml = _safe_parse(z.open(sheet_path)).getroot()
except KeyError:
continue
rows = []