On Fixing Insecure AI-Generated Code through Model Fine-Tuning and Prompting Strategies

arXiv:2605.05867 · cs.SE · Submitted 2026-05-07 · Read on arXiv

Listen

Radio episode about this paper

Transcript

Introduction to the show: ident: Computer Science. The day in computer science: software, systems and theory on arXiv.

Tom: I'm Tom.

Jane: And I'm Jane, here with Lu, Meng and our in-house large language model, Lalam.

Tom: We're looking at the paper: "On Fixing Insecure AI-Generated Code through Model Fine-Tuning and Prompting Strategies".

Paper summary: Tom: So, this paper is about trying to fix insecure code that some models generate by using different fine-tuning and prompting methods across various programming languages and AI models.

Jane: It looks like they took a bunch of known security problems, those CWEs, and tested how effective these AI techniques were at reducing them.

Lu: The authors looked at ten specific scenarios from the MITRE CWE Top Twenty-five to see which strategies worked best for different weaknesses across Python, Java, JavaScript, and Go.

Meng: So what’s the main point of this whole thing when we look at the final results? Is there one single magic fix they found?

Lalam: It turns out that while different methods work better for different problems, there isn't one universal strategy that fixes every weakness in every model or language.

Tom: That’s a big deal because it means we can’t just pick one technique and assume our AI code is safe everywhere.

Jane: Exactly. They found that fine-tuning was the most powerful way to reduce vulnerabilities overall, but it wasn't perfect for everything they tested either.

Lu: And they showed that when you try to fix a complex problem, like improper input validation, the fix itself can sometimes introduce brand new problems from added sanitization code.

Meng: That sounds like exactly what happens when you deploy fixes on real traffic; you patch one thing and break another part of the system because of how the AI made it.

Tom: So it’s not just about getting a lower number on a security report; it's about understanding that the process of fixing code can actually complicate things.

Jane: Right, so the paper suggests we need to be much more careful when we use these refinement techniques on AI-generated code.

Lu: The authors are pushing for developers to integrate security analysis tools into their continuous integration pipelines to check the AI output before it goes live.

Meng: And they’re telling the people building these models that they need to focus their training and fine-tuning on making security a core part of what those models learn.

Tom: So this study confirms that treating secure code generation as a requirement for AI development tools isn't just an idea; it’s becoming a necessary step.

Jane: It really makes you think about how we design the systems we build around these powerful new language models.

Lu: The authors are laying out the groundwork for future research on how to make the mitigation process itself safer, not just cleaning up the code output.

Conclusion: Tom: So, to wrap up this whole discussion on fixing AI code security, we're looking at this paper titled "On Fixing Insecure AI-Generated Code through Model Fine-Tuning and Prompting Strategies" by the authors of this study.

Jane: Yeah, it’s basically a deep dive into how model fine-tuning and different prompting methods can actually harden code generated by these large language models against known security weaknesses, those CWEs.

Lu: The core idea they're pushing is that you can't just use one trick; the effectiveness changes depending on which specific weakness you’re trying to fix and which AI model you’re using.

Meng: It confirms what we saw in production: there isn't a single magic fix for every kind of code error generated by an AI.

Tom: That means developers can't just hand over the AI output and assume it’s safe; they have to be much more careful about the strategy they choose.

Jane: They suggest that while fine-tuning seems the most powerful tool for overall vulnerability reduction, you still need a solid plan for how you're applying those fixes because of those new weaknesses we saw earlier.

Lu: The authors are setting up the next phase of research: they want to focus on designing the mitigation process itself so that it’s safer, not just about cleaning up the code output after the fact.

Massey University · Wuhan University · Polytechnique Montréal

cs.SE

Submitted: 2026-05-07

Updated: 2026-12-02

Code: https://github.com/AliSoltanianFJ/CodeSecurity2025

Project page: https://www.ibm.com/think/topics/chain-of-thoughts

License: http://creativecommons.org/licenses/by/4.0/

Importance score: 86/100

The gist: This paper systematically investigates various strategies for hardening model-generated code against a defined set of Common Weakness Enumeration (CWEs).

Key concepts

Common Weakness Enumeration (CWE)
A standardized list of common software vulnerabilities. These are like a catalog of known mistakes in coding practices, such as SQL injection or improper input validation. The study used these to test how well the AI-generated code was being secured.
Model Fine-Tuning (LoRA)
A technique where a large language model is specifically trained further on a smaller dataset of secure code examples. This process teaches the model to generate safer code patterns, which the research found was the most powerful method for fixing security issues.
Negative Example Prompting (NEP)
A refinement strategy where developers give the AI specific examples of insecure code and explicitly tell it what *not* to do. This helps guide the model away from generating known dangerous patterns, though its effectiveness varied depending on the model used.

Terminology

Summary

This paper systematically investigates various strategies for hardening model-generated code against a defined set of Common Weakness Enumeration (CWEs). p. 0

Where the paper says it

However, their effectiveness varies widely across models and settings. This paper presents a systematic investigation of strategies for hardening model-generated code against a list of Common Weakness Enumeration (CWE).

The study evaluates how effective fine-tuning and prompting approaches are in improving security across different models and programming languages. p. 8
Where the paper says it

On Fixing Insecure AI-Generated Code Suggestions 9 3. 3 Model and Language Selection This study evaluates the effectiveness of four refinement strategies, namely Negative Example Prompting, Chain-of-Thought Prompting, Fine-Tuning, and Meta Prompting, in improving the security of code generated by AI coding tools across multiple large language models and programming languages.

The analysis extends beyond simply quantifying the prevalence of weaknesses; it delves into the severity of identified CWEs, examines their co-occurrence, and critically assesses the unintended consequences that arise from remediation efforts. p. 0
Where the paper says it

We assess the extent to which these strategies improve security across models and programming languages, using fine-tuning and prompting approaches for model output refinement. Beyond the prevalence of security weaknesses, we analyse the severity of identified CWEs, their co-occurrence, and the unintended consequences of remediation (i.

A central finding is that security improvements are highly dependent on both the chosen strategy and the underlying model. p. 0
Where the paper says it

, whether fixing certain weaknesses introduces new weaknesses elsewhere in the same code). Our results show that security improvements are highly strategyand model-dependent.

While certain approaches successfully reduce specific classes of weaknesses, they frequently introduce new vulnerabilities as side effects of the proposed fixes. p. 0
Where the paper says it

Our results show that security improvements are highly strategyand model-dependent. Although some approaches reduce specific classes of weaknesses, they often introduce new weaknesses as side effects of the fixes.

Crucially, no single strategy proves universally effective in eliminating all weaknesses across every model and scenario, indicating that a universally bulletproof solution for secure AI-generated code does not exist.

The research employed 10 scenarios derived from the MITRE CWE Top 25. p. 1

Where the paper says it

Specifically, we assess whether prompting and fine-tuning techniques can reduce Common Weakness Enumerations (CWEs) at generation time, and whether they introduce unintended vulnerabilities. To this end, we use 10 scenarios derived from the MITRE CWE Top 25 Most Dangerous Software Weaknesses Corporation [8] descriptions to generate code samples using five distinct LLMs, chosen for their varying underlying architectures and strengths: including three general-purpose models (GPT-4.

Most Dangerous Software Weaknesses to generate code samples using five distinct Large Language Models (GPT-4. p. 1
Where the paper says it

Specifically, we assess whether prompting and fine-tuning techniques can reduce Common Weakness Enumerations (CWEs) at generation time, and whether they introduce unintended vulnerabilities. To this end, we use 10 scenarios derived from the MITRE CWE Top 25 Most Dangerous Software Weaknesses Corporation [8] descriptions to generate code samples using five distinct LLMs, chosen for their varying underlying architectures and strengths: including three general-purpose models (GPT-4.

1, Gemini 2. p. 1
Where the paper says it

To this end, we use 10 scenarios derived from the MITRE CWE Top 25 Most Dangerous Software Weaknesses Corporation [8] descriptions to generate code samples using five distinct LLMs, chosen for their varying underlying architectures and strengths: including three general-purpose models (GPT-4. 1, Gemini 2.

0 Flash, GPT-5, DeepSeek-R1-32B Distill, and o4-mini) across four programming languages (Python, Java, JavaScript, and Go). p. 6
Where the paper says it

1, Gemini 2. 0 Flash, o4-mini, DeepSeek R1 32B Distill, GPT-5) were used to generate the missing code for the partial code snippet of each scenario.

Four specific refinement strategies were tested: Negative Example Prompting (NEP), Chain-of-Thought (CoT) Prompting, Meta Prompting (MP), and model fine-tuning utilizing Low-Rank Adaptation (LoRA). p. 6
Where the paper says it

In Stage 3, four output refinement techniques were applied to guide the models toward producing more secure code. These techniques are grouped into two broad categories: Prompting-based Strategies: 1) Negative Example Prompting (NEP), 2) Chain-of-Thought (CoT) and 3) Meta Prompting (MP); Model Fine-tuning-based Strategy: Low-Rank Adaptation (LoRA).

The study addressed three primary research questions: RQ1 concerned the extent to which different LLMs generate security weaknesses across multiple languages and models; RQ2 assessed the effectiveness of various output refinement strategies in mitigating common software weaknesses (CWEs); and RQ3 investigated whether these refinement strategies introduce new weaknesses during the mitigation process, noting how this variation occurs across models. p. 2

Where the paper says it

To guide this study, we formulate three research questions: RQ1: To what extent do different LLMs generate security weaknesses in AI-generated code across multiple programming languages and models? RQ2: How effective are various model output refinement strategies, including prompting techniques and model fine-tuning, at mitigating common software weaknesses (CWEs) in AIgenerated code?

Key findings revealed several important insights. p. 1

Where the paper says it

The security risks of AI-generated code are becoming increasingly apparent, hence it is important to address and mitigate these issues. To address these security risks, researchers have proposed several mitigation strategies.

Model fine-tuning emerged as the most potent method for vulnerability elimination, achieving an average reduction of approximately 80% compared to the next best technique (meta prompting). p. 2
Where the paper says it

RQ1 focuses on understanding baseline weakness patterns across models and languages, RQ2 evaluates the effectiveness of mitigation strategies, and RQ3 examines potential unintended consequences, including the introduction of new weaknesses. Our results show that: (1) Model fine-tuning is the most effective method for eliminating vulnerability, reducing it by approximately 80% on average compared to the second-best method (meta prompting).

However, performance varied by CWE; all methods demonstrated peak effectiveness against CWE-89 SQL Injection, where they could successfully remove the weakness in 100% of cases. p. 2
Where the paper says it

(2) All methods perform best against CWE-89 SQL Injection (i. , they can effectively remove the CWE in 100% of cases).

Conversely, addressing more complex issues like CWE-20 Improper Input Validation and CWE-770 Missing Rate Limiting proved significantly more challenging due to the inherent complexity of correct input validation and rate limiting implementations. p. 2
Where the paper says it

, they can effectively remove the CWE in 100% of cases). At the same time, other vulnerabilities, such as CWE-20 Improper Input Validation and CWE-770 Missing Rate Limiting, are more difficult to address because correctly validating user input and implementing rate limiting are complex.

Furthermore, model performance in vulnerability removal was language-dependent, with results indicating greater overall reduction in CWEs within Python compared to the other languages tested. p. 2
Where the paper says it

(3) Models’ performance in removing vulnerabilities can also depend on the programming language. They reduce overall CWEs in Python more than in the other languages.

A significant concern identified is that applying prompting or fine-tuning strategies can introduce new vulnerabilities; specifically, some fixes for CWE-20 often result in new weaknesses stemming from added input sanitization or validation code. p. 2
Where the paper says it

They reduce overall CWEs in Python more than in the other languages. (4) There are potential ramifications of fixing the code suggestions with prompting and finetuning strategies, as some vulnerability fixes introduce new vulnerabilities (especially those associated with CWE-20, often as a side effect of added input sanitisation or validation code).

In conclusion, the paper asserts that while refinement techniques consistently enhance the security of AI-generated code—either by lowering the total count of CWEs or reducing the proportion of higher-severity ones—their efficacy is contingent upon model and language context. p. 2

Where the paper says it

RQ2: How effective are various model output refinement strategies, including prompting techniques and model fine-tuning, at mitigating common software weaknesses (CWEs) in AIgenerated code? RQ3: Do model output refinement strategies introduce new weaknesses while attempting to mitigate existing ones, and how does this vary across models?

Fine-tuning was established as the most effective technique for vulnerability reduction, whereas Meta Prompting proved to be the strongest among prompting methods. p. 2
Where the paper says it

RQ1 focuses on understanding baseline weakness patterns across models and languages, RQ2 evaluates the effectiveness of mitigation strategies, and RQ3 examines potential unintended consequences, including the introduction of new weaknesses. Our results show that: (1) Model fine-tuning is the most effective method for eliminating vulnerability, reducing it by approximately 80% on average compared to the second-best method (meta prompting).

The authors advise developers to integrate security analysis tools into continuous integration pipelines to vet AI-generated code prior to deployment, and urge LLM creators to prioritize security-aligned training and fine-tuning methodologies. p. 1
Where the paper says it

The risks of security weaknesses in AI-generated code are further exacerbated by evidence that some developers may trust AI tools’ outputs without fully reviewing the code they generate [7]. Furthermore, even when developers do review AI-generated code, a prior study by Klemmer et al.

The overarching takeaway is that treating secure code generation as a foundational requirement for LLM-based development tools is essential. p. 2
Where the paper says it

2 Background and Related Work This section discusses the background of AI-based code generation and reviews previous work on security issues in AI-generated code. First, we introduce the concept of code generation using large language models (LLM) and its increasing adoption in software development in Section 2.

Green — the paper says it, and the page is printed. Red — no passage carries it, so treat that sentence as unverified. The same check runs on your own text: check a summary against its source, $5.

Improvements for AI systems

  1. Improve security by using fine-tuning with Low-Rank Adaptation (LoRA) for model weights to adjust its weights by further training on a specific set of secure code examples to improve its security.

  2. Enhance prompt engineering through Meta Prompting, which generates a task-specific instruction designed to maximise the security of the code it can for a coding task, providing detailed guidance that directs reasoning toward secure coding practices.

  3. Implement Chain-of-Thought (CoT) Prompting to guide LLMs through explicit intermediate reasoning and produce secure versions of code by emphasizing validating all user input, preventing buffer overflows, mitigating cross-site scripting and insecure deserialization risks.

  4. Deploy Negative Example Prompting (NEP) to reduce CWE severity by showing the model insecure code samples in the prompt to guide it to learn from them and reduce security weaknesses in subsequent code generations, although results showed it can eliminate certain CWEs in specific contexts.

  5. Integrate CodeQL static analysis into continuous integration pipelines to assess the security of AI-generated code before deployment, allowing developers to use refinement techniques and analysis tools together for a more secure workflow.

Abstract

The security of AI-generated code remains a major obstacle to its widespread adoption. Although code generation models achieve strong performance on functional benchmarks, their outputs frequently contain bugs and security weaknesses that undermine their trustworthiness. Prior work has explored a range of approaches to mitigate security issues in AI-generated code, e.g., using static analysis-guided generation and prompt engineering. However, their effectiveness varies widely across models and settings. This paper presents a systematic investigation of strategies for hardening model-generated code against a list of Common Weakness Enumeration (CWE). We assess the extent to which these strategies improve security across models and programming languages, using fine-tuning and prompting approaches for model output refinement. Beyond the prevalence of security weaknesses, we analyse the severity of identified CWEs, their co-occurrence, and the unintended consequences of remediation (i.e., whether fixing certain weaknesses introduces new weaknesses elsewhere in the same code). Our results show that security improvements are highly strategy- and model-dependent. Although some approaches reduce specific classes of weaknesses, they often introduce new weaknesses as side effects of the fixes. Moreover, no strategy consistently eliminates weaknesses across all models and scenarios, highlighting the absence of a universally effective "bulletproof" solution for secure AI-generated code.

Sources

Related papers