Fraunhofer's SCS-Code Catches AI Writing Vulnerable Code and Steers It Secure
Researchers at Fraunhofer show code models internally 'know' when they are writing vulnerable code, and a single vector addition can flip the outcome.
ProTakeaways
- Fraunhofer AISEC shows CodeLLMs internally represent the concept of insecure code as a linear direction, extractable with 50 contrastive samples.
- Cosine similarity analysis reveals models often 'know' a token is insecure while generating it, particularly around layer 15.
- SCS-Code adds a security concept vector to residual-stream activations at inference with essentially zero compute overhead.
- On CodeGuard+, a hybrid of SCS-Code with constrained decoding hits 85.9 pass@1 and 61.6 sec-pass@1 on Llama3.1-8B.
- Method stacks with existing defenses like SafeCoder and outperforms them without collapsing functional correctness.
- Vulnerability subtypes cluster separately in later layers, hinting at real-time CWE-specific detection systems.
A team at Fraunhofer AISEC has published a study arguing that the security problem in AI-generated code is not really an ignorance problem, but a routing problem. Their paper, Security-by-Design for LLM-Based Code Generation, shows that code models often represent the concept of an insecure snippet inside their own activations while they are actively generating it, and then output the buggy code anyway. Building on that finding, the authors propose SCS-Code, a lightweight steering method that pushes the residual stream toward the secure region of concept space at inference time.
The vulnerability problem nobody has really cracked
Copilot-style assistants are now deeply embedded in production workflows, but the security track record is poor. Roughly 40% of code written by Copilot contains code vulnerabilities, and for some scenarios such as API usage, even state-of-the-art CodeLLM-generated code has a vulnerability ratio of 62%. Existing defenses fall into three camps, each with meaningful drawbacks:
- Fine-tuning approaches like SVEN and SafeCoder require curated security datasets and expensive retraining.
- Constrained decoding (CodeGuard+) enforces manually written keyword rules during sampling, which only cover predefined cases.
- Prompt optimization methods like PromSec run heavy per-sample optimization loops that make real-time completion infeasible.
Recent work comparing all of the mentioned approaches in parallel notes that they show limited effectiveness in improving secure code generation. The Fraunhofer team argues this is because all of them treat the model as a black box, relying on heuristics rather than an understanding of what is actually happening inside during generation.
Reading the model's mind mid-generation
The core mechanism borrows from mechanistic interpretability work on the Linear Representation Hypothesis, which posits that high-level concepts are stored as directions in activation space. The authors build a contrastive dataset from CyberNative's Code Vulnerability DPO pairs and compute a code-security direction using difference-in-means: average the residual-stream activations for secure code, subtract the average for insecure code, and you get a vector v_sec.

Projecting activations onto the second principal component shows a striking pattern across model layers. A clear separability appears in layer 15 between secure and insecure samples, showing that the concept can be measured along a linear subspace in the representation space of the underlying LLM. Early and late layers, by contrast, show no such separation, consistent with prior findings that those layers mostly handle token-level bookkeeping.
The uncomfortable finding comes from measuring cosine similarity between each generated token's activation and v_sec. On a password-hashing example, the tokens with the most negative alignment to the security direction land precisely on the MD5 call, while bcrypt tokens light up positively. The model is, in a measurable sense, aware it is writing the vulnerable version while writing it.
How SCS-Code actually steers
Once the concept vector is extracted, steering is essentially free. At a chosen layer l, during every forward pass, the method modifies activations as:
a_l(x) <- a_l(x) + alpha * v_sec
That is it. No retraining, no gradient updates, no prompt engineering. The full recipe reduces to three steps:
- Extract
v_secfrom a contrastive dataset of secure/insecure code pairs at every layer. - Identify the layer where the steering effect is strongest by seeing which layer flips model choices most often on a validation set.
- Add
alpha * v_secto that layer's residual stream during inference, applied context-aware to both prompt and generated tokens.
Two practical details matter. First, only about 50 contrastive samples are needed for the vector to converge, which is trivial compared to fine-tuning corpora. Second, the sweet-spot layer sits around layers 12 to 15 for most tested models, corresponding to where the concept becomes linearly separable. Interestingly, the authors observed that negative steering is easier than positive steering, meaning it takes less effort to push a model toward vulnerable code than toward secure code.
Subconcepts inside the security direction
Beyond a single secure/insecure axis, the residual stream also encodes specific vulnerability categories. Using PCA and t-SNE on activations from insecure samples only, the authors show distinct clusters for eval() misuse, insecure deserialization, improper memory handling, and improper input validation. Interestingly, the emergence of such lower-level concepts happens later in the model's internal residual stream than the development of general code security concepts, around layers 20 to 25. That opens the door to real-time vulnerability classifiers that read the model's internals as it generates.

Benchmark results
The team evaluated on two benchmarks: CWEval, spanning five languages and over 100 tasks, and CodeGuard+, spanning 34 CWEs across C/C++ and Python. Six models were tested including Llama2, Llama3.1, Mistral, CodeLlama, DeepSeek-Coder-V2-Lite, and StarCoder2.
On CodeGuard+ with Llama3.1-8B, SCS-Code lifts pass@1 from 75.9 to 78.8 and sec-pass@1 from 49.7 to 52.9. A hybrid combining SCS-Code with constrained decoding hits 85.9 pass@1 and 61.6 sec-pass@1, the best on the board. On DeepSeek-Coder-V2-Lite, the hybrid reaches 67.8 on sec@1_pass and a 77.4 security rate.
The comparison against SafeCoder is stark. SafeCoder baselines exhibit high Security Rates but at substantial cost to functional correctness, whereas SCS-Code balances both objectives more effectively. On CodeLlama-7B, SafeCoder drops pass@1 to 8.8 on CWEval versus 40.5 for the vanilla model, while SCS-Code holds functional correctness at 38.9 and still improves security. The Secure Code Prefix baseline exhibits similar patterns, sometimes producing comment-only outputs that are trivially secure but non-functional.
What is actually new here
The headline is a benchmark win, but the deeper contribution is methodological. Prior secure-coding work stacked heuristics on top of black-box models. This paper offers evidence that:
- Code security is represented linearly inside CodeLLMs, not as scattered emergent behavior.
- Vulnerability subtypes have their own directions in later layers, which could enable per-CWE steering or detection.
- The intervention is modular: because it is just a residual-stream addition, it stacks on top of existing defenses like SafeCoder or constrained decoding.
Limitations and when to reach for it
SCS-Code is not magic. The authors flag that there is often a tradeoff between functional correctness and security, and that steering with large magnitudes degrades output quality in both directions. Concepts stored in superposition mean the extracted vector likely bleeds into unrelated behaviors, and the team even shows an example where aggressive positive steering biases open-ended text generation toward safety-and-compliance phrasing. Concept extraction quality also depends on dataset construction, with longer samples like Java code introducing more noise.
For teams building code assistants where security matters, the value proposition is concrete: near-zero inference overhead, no fine-tuning, no prompt engineering, and it composes with whatever secure-coding pipeline is already in place. Code accompanying the paper is available in an anonymous repository covering concept extraction and steering across the six evaluated architectures.