diff options
| author | Claude <noreply@anthropic.com> | 2026-11-10 02:52:05 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-10 02:52:05 +0000 |
| commit | 9e43c9567ec9ba546916eb52b3f92385ebf65dd3 (patch) | |
| tree | 9ba3fdff6e5a1bed20bc3e13f1839ac30a361661 /plugins | |
| parent | dceb15d50832e6adf380bedc26dde03d251324b9 (diff) | |
security-guidance: read yaml, torch and numpy load calls across their argumentsmhegazy/sg-call-argument-scan
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/patterns.py | 39 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_call_argument_patterns.py | 106 |
2 files changed, 140 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/patterns.py b/plugins/security-guidance/hooks/patterns.py index 8e749cad..46224164 100644 --- a/plugins/security-guidance/hooks/patterns.py +++ b/plugins/security-guidance/hooks/patterns.py @@ -26,6 +26,28 @@ _UNSAFE_TORCH_LOAD_REMINDER = """⚠️ Security Warning: torch.load() defaults If the file only contains tensors and simple data structures, pass weights_only=True (or set TORCH_FORCE_WEIGHTS_ONLY_LOAD=1).""" + +def _call_args(): + """Regex for the arguments of one call, read from just after its "(". + + Steps over strings, comments and up to three levels of nested brackets as + units, across lines, so text that follows it is an argument of this call: not + of a nested one, not part of a comment, and not past the closing bracket. + Each alternative starts with a different character and every repeat is + bounded, so it cannot backtrack badly. + """ + char = r"[^()\x22\x27#]" + string = r"\x22(?:[^\x22\\\n]|\\.){0,300}\x22|\x27(?:[^\x27\\\n]|\\.){0,300}\x27" + comment = r"#[^\n]{0,300}\n" + leaf = rf"{char}|{string}|{comment}" + group = rf"\((?:{leaf}){{0,200}}\)" + for _ in range(2): + group = rf"\((?:{leaf}|{group}){{0,200}}\)" + return rf"(?:{leaf}|{group}){{0,400}}" + + +_CALL_ARGS = _call_args() + # Security patterns configuration SECURITY_PATTERNS = [ { @@ -188,7 +210,8 @@ Additionally, validate user inputs: }, { "ruleName": "unsafe_yaml_load", - "regex": r"\byaml\.load\s*\((?![^)\n]{0,80}\bSafe)", + # Suppressed by SafeLoader or CSafeLoader among the call's own arguments. + "regex": rf"\byaml\.load\s*\((?![^)\n]{{0,80}}\bC?Safe|{_CALL_ARGS}\bC?SafeLoader\b)", "reminder": _UNSAFE_YAML_LOAD_REMINDER, }, { @@ -254,9 +277,12 @@ Additionally, validate user inputs: }, { "ruleName": "torch_unsafe_load", - # Suppressed by weights_only=True on the same line (within 200 chars). weights_only=False - # still triggers. Multi-line calls false-positive — same known limitation as unsafe_yaml_load. - "regex": r"(?:\btorch\.load|\.torch_load)\s*\((?![^)\n]{0,200}weights_only\s*=\s*True)", + # Suppressed by weights_only=True among the call's own arguments. weights_only=False + # still triggers. + "regex": ( + r"(?:\btorch\.load|\.torch_load)\s*\(" + rf"(?![^)\n]{{0,200}}weights_only\s*=\s*True|{_CALL_ARGS}\bweights_only\s*=\s*True)" + ), "reminder": _UNSAFE_TORCH_LOAD_REMINDER, }, { @@ -270,7 +296,10 @@ Additionally, validate user inputs: "ruleName": "pickle_wrapper_load", # Library APIs that unpickle without saying "pickle". numpy.load only triggers # when allow_pickle=True is explicit (defaults to False since numpy 1.16.3). - "regex": r"\bjoblib\.load\s*\(|\b(?:pd|pandas)\.read_pickle\s*\(|\.cloudpickle_load\s*\(|\b(?:np|numpy)\.load\s*\([^)\n]{0,200}allow_pickle\s*=\s*True", + "regex": ( + r"\bjoblib\.load\s*\(|\b(?:pd|pandas)\.read_pickle\s*\(|\.cloudpickle_load\s*\(" + rf"|\b(?:np|numpy)\.load\s*\((?:[^)\n]{{0,200}}|{_CALL_ARGS}\b)allow_pickle\s*=\s*True" + ), "reminder": _UNSAFE_DESERIALIZATION_REMINDER, }, ] diff --git a/plugins/security-guidance/tests/test_call_argument_patterns.py b/plugins/security-guidance/tests/test_call_argument_patterns.py new file mode 100644 index 00000000..650db7b3 --- /dev/null +++ b/plugins/security-guidance/tests/test_call_argument_patterns.py @@ -0,0 +1,106 @@ +"""yaml.load, torch.load and np.load rules read the whole argument list of the call.""" +import time + +import pytest + +import security_reminder_hook as hook + +YAML, TORCH, NUMPY = "unsafe_yaml_load", "torch_unsafe_load", "pickle_wrapper_load" + + +def fires(rule, code): + return rule in {name for name, _ in hook.check_patterns("t.py", code)} + + +@pytest.mark.parametrize("rule, code", [ + (YAML, "yaml.load(open(path), Loader=yaml.SafeLoader)"), + (YAML, "yaml.load(m.group(1), SafeLoader)"), + (YAML, "yaml.load(f, Loader=yaml.CSafeLoader)"), + (YAML, "yaml.load(f.read(), Loader=CSafeLoader)"), + (YAML, "yaml.load(\n open(p),\n Loader=yaml.SafeLoader,\n)"), + (YAML, "yaml.load(s.replace(')', ''), Loader=yaml.SafeLoader)"), + (YAML, "yaml.load(s.replace('\\'', ''), Loader=yaml.SafeLoader)"), + (TORCH, 'torch.load(os.path.join(d, "m.pt"), weights_only=True)'), + (TORCH, 'torch.load(str(os.path.join(root(), "m.pt")), weights_only=True)'), + (TORCH, "torch.load(\n path,\n map_location=torch.device('cpu'),\n weights_only=True,\n)"), + (TORCH, "torch.load(\r\n path(),\r\n weights_only=True,\r\n)"), + (TORCH, "torch.load(\n path,\n # the model's device (cpu\n weights_only=True)"), + (NUMPY, "np.load(os.path.join(d, 'x.npy'))"), +]) +def test_safe_call_is_quiet(rule, code): + assert not fires(rule, code) + + +@pytest.mark.parametrize("rule, code", [ + (YAML, "yaml.load(f)"), + (YAML, "yaml.load(open(p), Loader=yaml.Loader)"), + (YAML, "yaml.load(open(p), Loader=yaml.UnsafeLoader)"), + (YAML, "yaml.load(\n open(p),\n Loader=yaml.Loader,\n)"), + (TORCH, "torch.load(os.path.join(d, 'm.pt'))"), + (TORCH, "torch.load(os.path.join(d, 'm.pt'), weights_only=False)"), + (TORCH, "torch.load(\n path,\n weights_only=False,\n)"), + (NUMPY, "np.load(path, allow_pickle=True)"), + (NUMPY, "np.load(os.path.join(d, 'x.npy'), allow_pickle=True)"), + (NUMPY, "np.load(\n path(),\n allow_pickle=True,\n)"), +]) +def test_unsafe_call_fires(rule, code): + assert fires(rule, code) + + +@pytest.mark.parametrize("rule, code", [ + # Another call or a comment after the closing bracket. + (YAML, "yaml.load(f) # TODO use SafeLoader"), + (YAML, "yaml.load(open(p)) # TODO use SafeLoader"), + (YAML, "yaml.load(f), yaml.load(g, Loader=yaml.SafeLoader)"), + (YAML, "yaml.load(f())\nyaml.load(g, Loader=yaml.SafeLoader)"), + (YAML, "yaml.load(s.replace('(', '')) or SafeThing()"), + (TORCH, "torch.load(p()) if old else torch.load(p, weights_only=True)"), + # A comment or string inside the argument list. + (TORCH, "torch.load(\n path, # weights_only=True breaks this\n)"), + (TORCH, "torch.load(\n path('weights_only=True'),\n 'weights_only=True'\n)"), + # An argument of a nested call. + (TORCH, "torch.load(\n fetch(url, weights_only=True),\n)"), +]) +def test_safe_keyword_elsewhere_does_not_hide_an_unsafe_call(rule, code): + assert fires(rule, code) + + +@pytest.mark.parametrize("code", [ + "np.load(p()); other(q, allow_pickle=True)", + "np.load(p()) # allow_pickle=True is not needed", + "np.load(\n path, # allow_pickle=True is not needed\n)", + "np.load(\n fetch(q, allow_pickle=True),\n)", +]) +def test_allow_pickle_elsewhere_does_not_fire(code): + assert not fires(NUMPY, code) + + +# Text today's rules already accept stays accepted. +@pytest.mark.parametrize("rule, code", [ + (YAML, "yaml.load(s, get_loader(yaml.SafeLoader))"), + (TORCH, "torch.load(p, **dict(weights_only=True))"), +]) +def test_previously_quiet_stays_quiet(rule, code): + assert not fires(rule, code) + + +@pytest.mark.parametrize("head", ["yaml.load(", "torch.load(", "np.load("]) +@pytest.mark.parametrize("body", [ + "(", "()", "(a", "((a))x", "\"'", '("', "\n", "#", "# a\n", "(((a)(b))", "\\'", "'\\", + "{head}", "{head}a()", "{head}((", "{head}(((a", "{head}'", "{head}#", +]) +def test_large_file_is_matched_quickly(head, body): + body = body.replace("{head}", head) + text = head + body * (60000 // len(body)) + start = time.perf_counter() + hook.check_patterns("t.py", text) + # Seconds only when matching is far worse than linear; normally tens of ms. + assert time.perf_counter() - start < 5 + + +@pytest.mark.parametrize("text", [ + "yaml.load(\n SafeConfigPath.read_text(),\n)", + "yaml.load(\n cfg[SafeKey],\n Loader=yaml.Loader,\n)", +]) +def test_a_word_starting_with_safe_is_not_a_safe_loader(text): + assert fires("unsafe_yaml_load", text) |
