turkic-ocr-code / scripts /r5_ref /ref_scan_executed.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
2.03 kB
"""R5 REF (rule 0.11): scans every pinned PaddleOCR file that the smoke run imported for calls that start processes, use the network, delete files, load pickles,
call eval/exec or import by name, and for module-level code that is not a definition. Reads text only. Usage: python ref_scan_executed.py <list_file> <root> <out_tsv>
"""
import ast
import re
import sys
PAT = re.compile(r"os\.system|subprocess|Popen|urlopen|urllib|requests\.|socket\.|pickle\.load|__import__|wget|shutil\.rmtree|os\.remove|os\.unlink|\beval\(|\bexec\(|importlib|ctypes|setup\.py")
lst, root, out = sys.argv[1], sys.argv[2], sys.argv[3]
rows = []
for p in [l.strip() for l in open(lst) if l.strip()]:
rel = p[len(root):].lstrip("/") if p.startswith(root) else p
src = open(p, encoding="utf-8", errors="replace").read()
hits = []
for i, line in enumerate(src.splitlines(), 1):
if PAT.search(line) and not line.strip().startswith("#"):
hits.append("%d:%s" % (i, line.strip()[:100]))
# module-level statements other than imports, defs, classes, assignments of constants, docstrings
try:
tree = ast.parse(src)
top = []
for n in tree.body:
if isinstance(n, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef, ast.Assign, ast.AnnAssign, ast.AugAssign)):
continue
if isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant):
continue
top.append("%d:%s" % (n.lineno, type(n).__name__))
except SyntaxError as e:
top = ["syntax error %s" % e]
rows.append((rel, len(src.splitlines()), "; ".join(hits), "; ".join(top)))
with open(out, "w", encoding="utf-8") as f:
f.write("path\tlines\trisk_pattern_hits\tmodule_level_statements_other_than_definitions\n")
for r in rows:
f.write("\t".join(str(x) for x in r) + "\n")
print(len(rows), "files;", sum(1 for r in rows if r[2]), "with pattern hits;", sum(1 for r in rows if r[3]), "with module-level statements")