Leak-Checked Refinement: Porting Code into Secure Enclaves Without Timing Leaks

Hardware secure enclaves, known as trusted execution environments (TEEs), let a program run on a machine whose operating system and administrators are not trusted. Memory is encrypted and the hardware can prove remotely which code is running. Recent work uses large language models to move sensitive functions, such as cryptography and serialization, out of legacy Java and Python programs and into enclave-resident Rust. The model is corrected in a loop by compiler errors and equivalence tests. There is a catch. Enclaves share caches and branch predictors with the untrusted host. Code that is correct but whose running time or memory access pattern depends on a secret therefore leaks that secret to the host. Current porting loops check only that the code compiles and gives the same answers. They never check whether it leaks.

We propose adding a timing-leak oracle to the refinement loop, so that a port is accepted only when it is functionally equivalent and constant-time. "Constant-time" here means that branches, memory addresses, and variable-latency instructions do not depend on secret data. The oracle has two parts, and both feed localized repair hints back to the model. The first is a static dependence analysis on the compiled program. The second is a dynamic timing test run on cores isolated from scheduler noise. Of the three input directions, enclaves are the application regime and iterative refinement is the mechanism. Deterministic execution enters in two ways: as the security property being enforced, and as the measurement discipline that gives the dynamic test enough statistical power to mean anything.

Core Claim

An LLM refinement loop that receives line-level secret-dependence diagnostics can turn a large fraction of automatically ported enclave functions from leaky into constant-time. It does this without losing functional equivalence, and with less runtime overhead than rule-based constant-time rewriting. The specific new element is that a constant-time verifier acts as a repair signal inside the generation loop, not as an after-the-fact audit.

The gap is documented in the file. Automated TEE Adaptation With LLMs (AUTOTEE) finds sensitive leaf functions with an abstract-syntax-tree parser and translates them to Rust using a ReAct-style loop fed by rustc errors and equivalence tests. It reports 91.8% transformation success on Java and 84.3% on Python. It neither measures nor enforces constant-time behavior. CtChecker runs a sound, precise constant-time analysis on LLVM's intermediate representation (IR) using program dependence graphs. It showed that code rewritten by the rule-based Constantine tool still leaks. It audits code but never repairs it. Our proposal sits between the two. We reuse CtChecker's style of analysis as an oracle. We extend AUTOTEE's loop with that oracle. We test whether the combination fixes what each leaves open.

Several papers motivate the threat. Branch Shadowing shows a host can reconstruct fine-grained branch histories inside SGX enclaves. Side Channel Vulnerabilities in Trusted Execution Environments, along with the cache-attack discussions in PRESAGE and Obscuro, establishes that memory encryption does not hide access patterns. Do Users Write More Insecure Code with AI Assistants? adds a warning that is specific to AI assistance. On its symmetric-encryption task, AI-assisted users produced correct and secure code 24% of the time versus 43% for controls, yet rated their trust highly. The lesson is that model-driven security code needs an objective oracle, not self-assessment.

Research Program

The system starts from AUTOTEE's pipeline and outputs: identified sensitive functions, their Rust ports, and equivalence tests. It then adds a third gate after compilation and equivalence.

The first step labels secrets. For each ported function, the model proposes which parameters and fields are secret, such as keys, plaintexts, and private records. A human audits these labels on a sample. The labels are kept fixed across all compared methods, so that no method can win by declaring fewer things secret.

The second step is the static oracle. We compile the Rust port to LLVM IR at the same optimization level used for deployment. We check the optimized IR rather than the source, because optimizing compilers are known to reintroduce secret-dependent branches during later passes. A CtChecker-style dependence analysis then flags every branch condition, memory index, and variable-latency instruction (for example, division) that is reachable from a secret. Each flag is mapped back to a Rust source line through debug information. The model receives the dependence chain itself, for instance "secret key[i] reaches the index of the table lookup on line 42 via t = key[i] ^ x." It does not receive a bare pass/fail.

The third step is the dynamic oracle. A static pass can produce false positives through imprecise tracking of pointer aliasing, and it can miss leaks that appear only at the machine-code level. To catch these, we run a fixed-versus-random-secret timing distinguisher on the enclave binary: a statistical test of whether timing differs between one fixed secret and random secrets. The test runs on cores isolated in the manner of Interference-free Operating System, meaning pinned cores, an isolated last-level cache partition where available, and no co-scheduled work. This is where deterministic execution earns its place. ICER found that jittery operating-system timing misleads refinement loops, and its response was to relax the acceptance rule. That option is not available to a leakage test. Noise does not just slow the test down; it hides real leaks. We will measure directly how much isolation reduces the number of samples the distinguisher needs.

The fourth step is the loop policy. VERINA shows that models thrash under long feedback loops: 64 rounds of prover feedback lift proof success only to about 20%. Following the rollback idea in Fang et al., we cap the number of iterations. We keep the best candidate so far under a strict ordering: equivalence passes, then the number of static flags, then dynamic test statistics, then runtime. We roll back any edit that breaks equivalence. One candidate action is library substitution, meaning the model may replace hand-ported code with a call to an audited constant-time primitive. This makes the most obvious shortcut part of the method rather than a hidden competitor. Runtime is also reported, because constant-time rewriting can roughly double cost, as noted in Drucker et al..

Baselines

The naive reference point is AUTOTEE as published: its ports, with no leakage gate, run through our static and dynamic oracles purely for measurement. This tells us how often current LLM porting produces leaky enclave code. For this leak rate there is no reported result found on Lacuna, and establishing it is itself a contribution. For the reference functional quality of this baseline we use the reported transformation success of 91.8% (Java) and 84.3% (Python) for GPT-4o from AUTOTEE. Our method must stay within a few points of these figures while lowering the leak rate.

The strongest existing method for removing timing leaks without a model is rule-based rewriting: Constantine applied to AUTOTEE's IR output. It has a principled transformation, needs no model calls, and is the tool CtChecker evaluated. No numeric leak rate for Constantine output is reported in the file, so the threshold to beat must be measured ourselves. To count as beating it, our method must leave fewer residual static flags and dynamic leaks, at equal or lower runtime overhead, on the same functions and with the same secret labels.

A prompting baseline gives the same model the same iteration budget and an explicit instruction to write constant-time code, with no oracle feedback. This separates the value of the oracle from the value of simply asking.

The key ablation feeds back only a binary "leaks / does not leak" verdict instead of the localized dependence chain. Model, prompts, iteration cap, and token budget are all held equal. If localized feedback does not clearly beat binary feedback, the claim that the verifier works as a repair signal fails. A second ablation runs the dynamic test without core isolation to quantify what determinism contributes.

Why not just…?

Why not just run Constantine or a similar rewriter after porting? This is cheaper and deterministic. The file reports, however, that CtChecker still found timing vulnerabilities in Constantine-rewritten code, and rewriters struggle with aliasing and dynamically structured loops. Rewriters also apply generic flattening that pays the constant-time cost everywhere. A model guided by diagnostics can instead restructure only the flagged paths. The head-to-head baseline above settles which wins. If Constantine matches us on leaks and overhead, the honest conclusion is that the loop adds nothing beyond porting.

Why not just call an audited constant-time library for every sensitive function? This is a real threat for textbook primitives such as AES or RSA, which is why library substitution is an action inside our loop. AUTOTEE's 385 sensitive leaf functions, however, include serialization and custom handling logic that no library covers. We will report results separately for library-covered and uncovered functions. If nearly all gains come from substitution, the contribution shrinks to "teach the porter to call libraries," and we will say so.

Why not just prompt the model to write constant-time code? The finding in Do Users Write More Insecure Code with AI Assistants? that AI help degraded security while inflating confidence suggests that self-assessment is unreliable. The prompting baseline tests this directly under an equal budget.

Why not formally prove constant-time and equivalence instead? VERINA reports 4.9% pass@1 for o3 on proof generation and 3.2% end-to-end. Requiring proofs would reject almost every port. We use a sound static analysis rather than generated proofs, which keeps strong guarantees for the property we care about without asking the model to write proofs.

Proposed Experiments

The primary benchmark is AUTOTEE's dataset of 385 sensitive leaf functions, with its 37-function stability subset used for repeated-run variance. The positive-control benchmark is the BearSSL, Libgcrypt, mbedTLS, and OpenSSL modular-exponentiation suite from CtChecker. On that suite we inject known leaky variants and measure whether the loop repairs them. CtChecker's reported analysis speed of 24K lines in under a minute suggests the static oracle is cheap enough to call on every iteration. We will confirm this.

The headline metric is the fraction of functions that are simultaneously functionally equivalent, free of static flags in optimized IR, and pass the dynamic distinguisher. Secondary metrics are runtime overhead relative to the unhardened AUTOTEE port inside the enclave, iterations to acceptance, token cost, and static-flag counts on the positive controls. We will also report end-to-end call latency. AUTOTEE's 1.6x (RSA key generation) and 1255x (Python SHA256) overheads show that boundary crossings dominate for small functions, so constant-time cost must be shown relative to that baseline, not in isolation.

Three outcomes would be decisive. First, on the positive-control suite, the loop must remove injected leaks that Constantine leaves behind. Second, localized feedback must beat binary feedback by a clear margin at equal budget. Third, running the dynamic test without isolation must measurably reduce detection of leaks the isolated run catches. If the first two fail, the idea is wrong. If only the third fails, the determinism component can be dropped and the rest stands.