File size: 1,071 Bytes
c3d4795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Policy profiles: which items count as injections, as benign, or are left out (design section 7)."""
import json
from pathlib import Path


def load(path_or_name, data_dir=None):
    p = Path(path_or_name)
    if not p.exists() and data_dir is not None:
        p = Path(data_dir) / "policies" / f"{path_or_name}.json"
    return json.loads(p.read_text())


def _match(rule, item):
    attrs = {k for k, v in item["attrs"].items() if v}
    if "attrs_any" in rule and not attrs & set(rule["attrs_any"]):
        return False
    if "attrs_none" in rule and attrs & set(rule["attrs_none"]):
        return False
    if "label" in rule and item["injection"] != rule["label"]:
        return False
    if "direction" in rule and item.get("direction") != rule["direction"]:
        return False
    return True


def target(policy, item):
    """1, 0 or None (left out) for this item under the policy."""
    for rule in policy["rules"]:
        if _match(rule, item):
            return None if rule["then"] == "ignore" else int(rule["then"])
    return item["injection"]