File size: 2,027 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""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")