From f6deea08a0130f66e4a3baf7a854b134e80997f6 Mon Sep 17 00:00:00 2001 From: Sinatras Date: Fri, 1 May 2026 21:03:01 +0300 Subject: [PATCH] fix(detector): extend TIMER_MONKEYPATCH to cover time-module reassignment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets red #127 (Timing monkeypatch direction): import time def custom_kernel(data): setattr(time, 'perf_counter', lambda: 0.0) return data.clone() The existing detect_timer_monkeypatch only catches torch.cuda.Event-side patching. A host-side timer monkeypatch is the same family of attack at a different layer — the harness reads time.perf_counter etc. for elapsed calculations and a stub returning 0.0 lets a 'submission' claim arbitrary speedups. Add two regex matchers: * 'time.{perf_counter|perf_counter_ns|monotonic|monotonic_ns|process_time|time} = ...' * 'setattr(time, '', ...)' Both emit the existing TIMER_MONKEYPATCH pattern (timing_monkeypatch family, AUTO_FILTER) with evidence specifying which attribute was hit. --- kernelguard.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/kernelguard.py b/kernelguard.py index f086847..44e11ab 100644 --- a/kernelguard.py +++ b/kernelguard.py @@ -39,6 +39,12 @@ # Pattern 1: Timer monkey-patching RE_CUDA_EVENT_ASSIGN = re.compile(r'torch\.cuda\.Event\s*=\s*') RE_CUDA_EVENT_SETATTR = re.compile(r'setattr\s*\(\s*torch\.cuda\s*,\s*[\'"]Event[\'"]\s*,') +RE_TIME_MODULE_ATTR_ASSIGN = re.compile( + r'\btime\.(perf_counter|perf_counter_ns|monotonic|monotonic_ns|process_time|time)\s*=\s*' +) +RE_TIME_MODULE_SETATTR = re.compile( + r'setattr\s*\(\s*time\s*,\s*[\'"](perf_counter|perf_counter_ns|monotonic|monotonic_ns|process_time|time)[\'"]\s*,' +) RE_ELAPSED_TIME_METHOD_PATCH = re.compile(r'torch\.cuda\.Event\.elapsed_time\s*=') RE_CUDA_SYNCHRONIZE_PATCH = re.compile(r'torch\.cuda\.synchronize\s*=') RE_DUMMY_FAKE_EVENT = re.compile(r'class\s+_?(?:Dummy|Fake|Mock|Stub|Noop)\w*Event', re.IGNORECASE) @@ -586,6 +592,20 @@ def detect_timer_monkeypatch(code: str | SubmissionFacts) -> list[dict]: "severity": "critical", "evidence": "torch.cuda.synchronize patched", }) + if RE_TIME_MODULE_ATTR_ASSIGN.search(code): + m = RE_TIME_MODULE_ATTR_ASSIGN.search(code) + matches.append({ + "pattern": "TIMER_MONKEYPATCH", + "severity": "critical", + "evidence": f"time.{m.group(1)} reassigned (host-clock monkeypatch)", + }) + if RE_TIME_MODULE_SETATTR.search(code): + m = RE_TIME_MODULE_SETATTR.search(code) + matches.append({ + "pattern": "TIMER_MONKEYPATCH", + "severity": "critical", + "evidence": f"setattr(time, '{m.group(1)}', ...) patching", + }) if RE_DUMMY_FAKE_EVENT.search(code): matches.append({ "pattern": "TIMER_MONKEYPATCH",