How Safe Is Safe Code Generation? Adversarial Prompts Test LLM DefensesHow Secure is Secure Code Generation? Adversarial Prompts Put LLM Defenses to the Test
The authors audit three secure code generation methods with adversarial prompts; the highest consensus safety and functionality rate on CodeSecEval is 15.5%.
- Secure code generation methods claim to avoid insecure code, but safety and functionality are often evaluated separately, and robustness under adversarial prompts is not uniformly measured. Studies cited in the introduction state that LLMs generate vulnerable code in 33% to 45% of tasks, and up to 70% for Java.
- The audit only modifies comments and docstrings, covering paraphrasing, clue inversion, minimal context, and dead code. Sven uses prefixes, SafeCoder uses instruction fine-tuning, and PromSec uses black-box prompt optimization. The judgment requires CodeQL, Bandit, GPT-4o, and unit tests to pass simultaneously.
- Without attacks, Sven, SafeCoder, and PromSec have consensus secure and functional rates of 7.0%, 10.2%, and 15.5% on CodeSecEval, while CodeQL rates are 66.3%, 64.8%, and 98.5%. Under StudentStyle, the consensus rates for the first two drop to 3.4% and 4.3%.
- The authors state that the unified audit only covers Python; extending to Java or C/C++ is out of scope. Section 8 suggests future joint evaluation, explicit threat models, and moving from syntactic patterns to semantic reasoning. The paper does not report the size of the GPT-4o spot-check subset.
- Evaluated models
- Salesforce/codegen-350M-multicodegen-2B-multicodegen-6B-multiCodeLlama-7BGPT-3.5 Turbo
- Benchmarks
- CodeSecEvalSecEval-BaseSecEvalPlusHumanEvalMBPPMMLUTruthfulQA
- Metrics
- security ratioPass@kSecure and Functionalnon-functional ratecode graph similarity
The researchers conducted a systematic adversarial audit of three safe code generation methods—SVEN, SafeCoder, and PromSec—and found that they are not robust under adversarial prompts. The audit used prompt perturbations such as rewriting, clue inversion, and context manipulation to simulate situations where developers inadvertently introduce or attackers deliberately exploit them, and evaluated both safety and functionality simultaneously using multiple analyzers and executable tests under consistent conditions. The results show that static analyzers overestimate safety by 7 to 21 times, 37% to 60% of so-called safe outputs cannot run, and the proportion of outputs that are both truly safe and usable under adversarial conditions drops to 3% to 17%. Based on this, the authors propose best practices for building and evaluating robust safe code generation methods.
Paper analysis
What problem does this paper attempt to solve?
The authors audit three secure code generation methods to see whether they remain both secure and executable after adversarial rewriting.
Core question: Do methods that claim to generate secure code still satisfy both safety and functionality when natural language context is rewritten?
- Scenario: The authors state that tools like Copilot, Codex, and Q Developer integrate code LLMs into development workflows. Studies cited in the introduction state that LLMs generate vulnerable code in 33% to 45% of tasks, up to 70% for Java. Methods like Sven, SafeCoder, and PromSec use vulnerability-aware training, prefix, or prompt optimization to reduce vulnerability rates.
- Existing gaps: The authors state there is no unified protocol; safety and functionality are often tested separately on different datasets; disappearance of static alerts does not mean unit tests pass. The authors also state it is unclear whether these methods learn safety reasoning or overfit to known vulnerability patterns.
- Threat model:
- Adversary: black-box adversary with query-only access to deployed secure code generation services (API or IDE plugin).
- Capabilities: Can construct adversarial inputs representing realistic distribution shifts; cannot access parameters, gradients, or internal structure.
- Goal: Bypass safety alignment, invalidate safety guarantees, and cause the model to generate insecure code, regardless of functional correctness.
- Input and consequences: Default manipulation of comments, docstrings, and issue text. The adversary themselves may not be harmed by insecure code; the authors discuss indirect contamination of service reputation, supply chain, and multi-tenant completions.
- This paper's approach: The authors state in the abstract that this is the first systematic adversarial audit of Sven, SafeCoder, and PromSec; they jointly measure safety and functionality under consistent conditions and propose practical recommendations for construction and evaluation.
What related research exists?
Related work includes secure code generation, separate functionality and security benchmarks, and adversarial attacks on code models.
Secure Code Generation
- Sven (He and Vechev, 2023): Uses continuous prefixes to bias the generation distribution toward secure or vulnerable behavior, evaluated with CodeQL on CWE scenarios.
- SafeCoder (He et al., 2024): Uses LoRA for secure instruction fine-tuning. The original training corpus is 465 examples covering 23 CWEs and 6 languages, plus general instruction data.
- PromSec and adjacent methods: PromSec (Nazzal et al., 2024) performs black-box prompt optimization; CodeGuard+ (Fu et al., 2024) uses constrained decoding. The authors state that HexaCoder, SecCoder, and PEFT-based fine-tuning were not included in the audit because they lack reproducible artifacts or are only incremental variants of core strategies.
Evaluation and Functionality–Security Trade-off
- Separate benchmarks: Functionality commonly uses benchmarks with unit tests (e.g., Chen et al., 2021), while security commonly uses SecurityEval (Siddiq and Santos, 2022) and relies on CodeQL. The authors state that such post-hoc aggregation cannot directly compare Sven and PromSec.
- Dai et al. (2025): The authors cite this survey, stating that existing methods often harm functional correctness due to security mechanisms.
- CodeSecEval and alternative benchmarks: The authors choose CodeSecEval from Wang et al. (2024) because it has both executable tests and security labels; they mention SecCodePLT (Yang et al., 2024) as an alternative not chosen.
Adversarial Attacks on Code LLMs
- Code perturbation: Semantics-preserving transformations such as variable renaming and dead code insertion are used to make models misjudge or generate incorrect code. This paper's SensitiveDeadCode uses DIP from Na et al. (2023).
- Prompts, context, and poisoning: Includes attribution-guided prompts for completion, adversarial suffix jailbreaks, disguise strategies, and training data poisoning and backdoors. The authors state that prompt defenses and adversarial training provide some resistance to black-box transfer attacks, but secure code generation methods still lack systematic evaluation against these practical threats.
- Baselines and datasets: The no-attack references are Original-sec and PromSec-Base. Phase 1 follows each method's original metrics and data: Sven uses CodeQL security rates on a custom set and Pass@k on HumanEval; SafeCoder adds MBPP, MMLU, and TruthfulQA; PromSec uses Bandit, SpotBugs, and custom Python/Java data. Phase 2 uniformly uses CodeSecEval.
The authors position this paper as an adversarial audit covering prefix control, instruction fine-tuning, black-box prompt optimization, and white-box/black-box assumptions, to fill the gap of joint evaluation and unquantified security alignment under distribution shift.
How does the paper address this problem?
Audit three methods with black-box natural language perturbations, and use consensus of multiple analyzers plus unit tests to determine secure and functional.
The authors use inference-time, black-box perturbations that only modify natural language context to stress Sven, SafeCoder, and PromSec, then use multiple analyzers plus executable tests for consensus judgment.
The Three Audited Methods
- Sven: White-box continuous prefix. A learned secure or vulnerable prefix is prepended to the input to shift the underlying model's output distribution. This run loads SVENsec/SVENvul with base models Salesforce/codegen-350M-multi, codegen-2B-multi, and codegen-6B-multi. Section 4.1 also mentions prefixes for InCoder and SantaCoder, as well as CodeGen (350M, 2.7B, 6.1B); the experimental section here lists the three checkpoints above. The original security evaluation uses CodeQL.
- SafeCoder: White-box instruction fine-tuning. This run uses fine-tuned CodeLlama-7B with LoRA (r=16, α=32). Section 4.1 states the original can also be deployed to StarCoder, Phi-2, Llama2, and Mistral; these checkpoints were not run here.
- PromSec: Black-box prompt optimization. Queries GPT-3.5-Turbo; if the code is insecure, it builds AST, CFG, and DFG, repairs with graph-guided GAN (gGAN), then back-derives a new prompt until CWE count is 0 or the maximum iteration threshold is reached. The paper does not give that threshold. The original evaluation uses Bandit (Python) and SpotBugs (Java).
Attack Vectors
Perturbations only modify comments or docstrings; tasks and tests are fixed, simulating context a developer might inadvertently write or an adversary might deliberately exploit. GPT-4o rewrites according to attack specifications; Appendix A.4 gives the full prompts, and Appendix A.2 gives examples.
- General: StudentStyle changes imperative comments into informal questions; InverseComment changes security-oriented guidance into the opposite guidance.
- Completion (Sven, SafeCoder): SparseComment keeps only one comment; SparseQuestion further changes that one into a short question.
- Repair (PromSec): SafeComment inserts security-oriented comments; VulComment inserts comments pointing out insecure practices; DeadCode injects non-executed or redundant fragments, with variants of appending at file end, embedding across multiple functions, and inserting at vulnerable positions per DIP; In-Context appends input-output examples.
Two-Phase Evaluation
- Phase 1: Follows each method's original protocol to see whether its reported security rate holds under perturbation. Sven and SafeCoder use security rate and Pass@k; PromSec uses vulnerability reduction, code graph similarity, fuzzing, and query count or time.
- Phase 2: Switches to CodeSecEval. There are 180 Python tasks and 44 vulnerability types. SecEval-Base has 67 completions from SecurityEval and CWE sources; SecEvalPlus has 113 generations from the 2023 CWE Top 25, excluding rare or Python-incompatible cases. Each item includes a natural language description, insecure implementation, reference secure solution, and unit tests. Sandbox timeout is 5 seconds for initialization and 10 seconds for testing.
- Consensus: CodeQL 2.15.4, Bandit 1.8.6, GPT-4o (temperature 0, with manual spot-checking on a random subset) and unit tests must all agree for it to count as secure and functional. The authors state that unit tests check both functional behavior and security properties. Because only Python has this kind of ground truth with tests, the unified audit is done only on Python.
Generation Configuration and Failure Counting
- Sven: temperature 0.4, top-p 0.95, up to 300 new tokens, 25 samples per prompt, seed 1. The authors state that under the released checkpoints, generation is identical across runs, so a single run is used.
- SafeCoder: temperature 0.4, top-p 0.95, up to 256 tokens, 100 samples per prompt, same global seed. Also treated as deterministic.
- PromSec: Even at temperature 0, GPT-3.5-Turbo remains stochastic; following the original design, one generation per prompt, no sampling distribution.
- Insertion position: Sven and SafeCoder insert into leading comments or docstrings; PromSec inserts into the problem description or inline comments before optimization.
- Failures: Refusals or empty outputs are counted in the denominator. Unified rates are normalized to 670 expected files, i.e., 67 completion prompts times 10 samples.
What experiments did the paper conduct?
On CodeSecEval, the three methods' consensus safety and functionality rates are 7.0%, 10.2%, and 15.5%; CodeQL is higher.
Experimental Setup
- Subjects: Sven's three CodeGen prefix checkpoints; SafeCoder's CodeLlama-7B; PromSec's queried GPT-3.5-Turbo. The Phase 1 Sven security rate figure covers three sizes; SafeCoder's adversarial table only has CodeLlama-7B.
- Data: Phase 1 uses each method's original datasets, including HumanEval, MBPP, MMLU, TruthfulQA, and a custom security set with no sample count given. Phase 2/3 rates are normalized to 670 expected files.
- Attacks: RQ1 uses the perturbations listed in Question 3. RQ3 only takes InverseComment and StudentStyle and requires all four judgment sources to agree.
- Metrics: Security rate or security ratio, Pass@k, per-analyzer security rate, consensus Secure and Functional, non-executable ratio, generation coverage. PromSec additionally reports code graph similarity and fuzzing pass count.
- Reviewers: CodeQL 2.15.4, Bandit 1.8.6, and GPT-4o at temperature 0. The paper states manual spot-checking on a random subset but does not report subset size or agreement.
- Replication: Sven and SafeCoder run once; PromSec generates once per prompt. The paper does not report confidence intervals.
Main Results
Swipe horizontally to read the table
Method CodeQL Secure Unit Test Secure Consensus Secure and Functional Non-executable Sven 66.3% 5.8% 7.0% 46.0% SafeCoder 64.8% 3.0% 10.2% 37.0% PromSec 98.5% 13.3% 15.5% 60.0% CodeSecEval, relative to expected files. CodeQL, unit test secure, and non-executable are from Table 5; consensus is from Table 6. Table 5 also has Bandit security rates: Sven 61.2%, SafeCoder 54.6%, PromSec 80.7%; GPT-4o at 7.0%, 10.1%, 20.6%.
- The authors state that static analyzers overestimate security: relative to unit test security rates, CodeQL is 7.4–21.6 times and Bandit is 6.1–18.2 times; the functional and secure rate is only 3.0%–13.3%. The abstract writes 7 to 21 times.
- The authors state that non-executable outputs are marked secure by static tools, and security interventions harm functionality, contradicting claims of joint optimization. The abstract writes that 37% to 60% of "secure" outputs are non-executable; the RQ2 summary writes that non-executable code accounts for 37.0%–60.0% of outputs. The corresponding cells in Table 6 are 46.0%, 37.0%, and 60.0%.
- The authors state that GPT-4o is more conservative (7.0%–20.6%) but still overestimates by 1.2–1.5 times. Per Table 5, SafeCoder's 10.1% relative to unit test 3.0% is not within this multiple range. The consensus rates in Table 6 are also higher than the unit test security rates in Table 5, which is inconsistent with the subset relationship of "must pass all analyzers and tests," and the paper does not explain this.
Perturbations Under Original Protocols (RQ1)
- Sven: On CodeGen-2B, SVENsec's Original-sec is 93.7%. The main text states InverseComment drops by 13% absolute, StudentStyle by 9%, and SparseQuestion by 2%; the RQ1 summary writes SVEN -13.1%. On SVENvul, Figure 3 shows InverseComment rising from 35.2% to 46.3% (+11.1%), and that sentence does not name the size; SparseQuestion, SparseComment, and StudentStyle increase by 14%, 4%, and 3%, respectively. The authors state that the prefix is not independent of the prompt, and minor wording can strengthen or weaken the prefix.
- SafeCoder: Table 2, CodeLlama-7B, Original-sec is 89.0%; InverseComment 80.6 (-8.4), StudentStyle 86.3 (-2.7), SparseQuestion 86.4 (-2.6), SparseComment 86.8 (-2.2). The main text writes the drops as 8%, 3%, 3%, and 2%, which is inconsistent with the table; the table takes precedence.
- PromSec: Table 4 baseline is 88%, and all listed perturbations rise, with the highest being DeadFunc200 at 98 (+10); the main text writes this setting as DeadCode200. The authors believe harder inputs trigger more repair iterations, giving the graph-guided analyzer more repair opportunities; they also state that relying only on Bandit may inflate security scores. The authors report code graph similarity of 0.89 and fuzzing pass of 20/20.
Two Attacks Under Unified Setting (RQ3)
- InverseComment: Table 7 unit test security rates are Sven 1.3%, SafeCoder 2.8%, PromSec 3.1%, and non-executable rates are 38.4%, 41.2%, 70.8%. PromSec's CodeQL is 99.4%. Table 8 consensus secure and functional is 9.3 (+2.3), 9.4 (-0.8), 17.6 (+2.1); generation coverage is 63.0%, 77.8%, 100%. The authors state that 17.6% is misleading because 70.8% is non-executable.
- StudentStyle: In Table 9, SafeCoder's CodeQL drops from 71.8% under InverseComment to 37.3%, Sven is 49.6%, and PromSec is 99.6%. Unit test security rates are 1.3%, 2.1%, and 4.8%, respectively; PromSec non-executable is 76.0%. Table 10 consensus is Sven 3.4 (-3.6), SafeCoder 4.3 (-5.9), PromSec 15.2 (-0.3); generation coverage is 55.5%, 45.7%, 100%. The main text writes PromSec consensus as 15.6%, which is inconsistent with Table 10's 15.2; the table takes precedence.
- Author interpretation: The authors state that the true secure and functional rate drops to 3.4%–17.6%; static analyzers are unreliable under adversarial load, e.g., PromSec's CodeQL is 99.6% with 76.0% non-executable. The RQ3 summary writes that Sven and SafeCoder generation rates are 45.7%–63.0%; in Table 8, SafeCoder under InverseComment is 77.8%, which is not in that range.
Other Ablations and Analyses
- Table 1, HumanEval, no adversarial perturbation: 350M pass@1 is LM 6.7, SVENsec 6.0, SVENvul 6.8; 2.7B is 14.0, 11.7, 12.5; 6.1B is 18.6, 16.9, 17.6. The checkpoints named in Section 5 are codegen-2B-multi and codegen-6B-multi.
- Table 3: SafeCoder's HumanEval Pass@1/10 is 35.9/54.7, MBPP is 35.1/48.5, MMLU 28.6, TruthfulQA 28.2. The table does not name the model.
- Table 6 generation coverage is Sven 79.4%, SafeCoder 73.4%, PromSec 100%; Vulnerable is 72.4%, 63.3%, 84.5%.
- Section 7.2 case studies (Appendix A.1 and A.3 have additional outputs): On CWE-252, PromSec's interface does not match the task requirement, causing a runtime attribute error, yet CodeQL, Bandit, and GPT-4o still mark it secure. On CWE-327, the output becomes a script and the test cannot find the specified function. On CWE-502, Sven baseline is CodeQL 0, Bandit 1, GPT-4o 1, and unit test fails; the authors state that under InverseComment the prefix does not override the inverted clue.
What are some points that can be further explored?
The authors state that the unified audit only covers Python and suggest future joint evaluation and semantic safety reasoning.
Limitations and future directions noted by the authors
- Language scope: The unified audit only covers Python. The authors state that extending the protocol to Java or C/C++ would require building new corpora with test suites, which is outside the scope of this adversarial robustness study (Section 4.3.2).
- New benchmarks: The authors suggest that future datasets should pair unsafe/safe references with tests, add semantically preserving perturbations, and extend beyond Python (Section 8, principle 3).
- Threat models: The authors suggest specifying adversary capabilities based on method assumptions: white-box considers training-time risks such as data poisoning and prefix hijacking; black-box considers inference-time threats such as prompt injection and semantically preserving paraphrases (Section 8, principle 1).
- Semantic reasoning: The authors state that current methods model surface syntax, while safety is a semantic, non-local property; future methods should move toward semantic reasoning and build benchmarks targeting invariants and information flow, not just CWE patterns (Section 8, principle 7).
- Evaluation practices: The authors suggest including adversarial testing in evaluations, using intersections of multiple analyzers rather than single-tool conclusions, and reporting distributions under each attack rather than only averages (Section 8, principles 2, 4, 5). The conclusion states that to trust generated code in the software supply chain, adversarial testing and joint safety–functionality evaluation should be standard.
- The paper does not have a separate Limitations section. Section 7 begins by saying it will discuss scope and limitations, then proceeds to case studies and practical recommendations in Section 8.
Experimental coverage
- The audited methods are Sven, SafeCoder, and PromSec. Three CodeGen prefix checkpoints and CodeLlama-7B are actually loaded; PromSec queries GPT-3.5-Turbo (Section 5).
- Perturbations for RQ1 include StudentStyle, InverseComment, SparseComment, SparseQuestion, and for PromSec SafeComment, VulComment, DeadCode10/50, DeadFunc200, SensitiveDeadCode, In-Context (Table 2, Table 4). RQ3 uses InverseComment and StudentStyle (Section 6.3).
- The unified metric is normalized to 67 completion prompts times 10 samples, totaling 670 expected files. CodeSecEval has 180 Python tasks and 44 vulnerability classes, of which SecEvalPlus has 113 (Section 4.3.2, Section 5).
- Analyzers are CodeQL 2.15.4, Bandit 1.8.6, GPT-4o at temperature 0, and CodeSecEval unit tests. The paper states that GPT-4o outputs were manually spot-checked on a random subset, but does not report the subset size, agreement, or number of repetitions.
- Sven and SafeCoder are run once on deterministic artifacts; PromSec generates once per prompt. The paper states there is no sampling distribution and no confidence intervals are reported (Section 5).
Summarize the main content of the paper
Under joint evaluation, the proportion of methods that are both safe and functional is low; after adversarial paraphrasing, Sven's consensus rate drops to 3.4%.
The authors audit Sven, SafeCoder, and PromSec to see whether, after rewriting comments and documentation, the generated code remains both safe and executable.
- Problem: Existing evaluations separate safety from functionality; a reduction in static alerts does not mean unit tests pass. The default adversary in deployment is black-box, with query-only access, using comments, docstrings, or issue text to induce the service to output insecure code.
- Approach: Perturbations keep tasks and tests unchanged. Completion side includes paraphrasing, clue inversion, and minimal context; repair side also includes safety-biased comments, unsafe hints, dead code, and example prompts. Unified evaluation uses CodeSecEval, requiring agreement among CodeQL, Bandit, GPT-4o, and unit tests for safety and functionality.
- No-attack joint results: Consensus safety and functionality rates are Sven 7.0%, SafeCoder 10.2%, PromSec 15.5%; CodeQL rates are 66.3%, 64.8%, 98.5%; non-executable rates are 46.0%, 37.0%, 60.0% (Table 5, Table 6).
- Adversarial results: On CodeGen-2B, SVENsec's no-attack safety rate is 93.7%, and the text states InverseComment drops by 13% absolute. SafeCoder on CodeLlama-7B drops from 89.0% to 80.6% (Table 2). Under StudentStyle, consensus rates are Sven 3.4%, SafeCoder 4.3%, PromSec 15.2% (Table 10). Under its original protocol, PromSec's safety rate in Table 4 does not drop but rises, up to 98%.
- Authors' conclusions: The authors state that these methods' safety behavior depends on prompt surface, not stable, generalizable alignment; static analyzers give higher safety rates than the proportion that is executable and passes all checks. The authors recommend that evaluations specify threat models, include adversarial testing, and use the intersection of safety and functionality rather than conclusions from a single static tool.