SecCoder: Towards Generalizable and Robust Secure Code Generation

Boyu Zhang, Tianyu Du, Junkai Tong, Xuhong Zhang, Kingsum Chow, Sheng Cheng, Xun Wang, Jianwei Yin

Abstract

Large language models (LMs) for code generation frequently produce insecure snippets because they are trained on massive, unvetted open-source repositories. Existing security alignment methods, such as fine-tuning, often struggle with generalizability to unseen vulnerabilities and lack robustness against adversarial attacks. We introduce SecCoder, a training-free approach that utilizes retrieval-augmented in-context learning (ICL) to guide LMs toward generating secure code. By prepending semantically relevant, safe code demonstrations to user prompts, SecCoder significantly enhances the security of generated code across various model families and sizes. Experimental results show that SecCoder improves security rates by an average of 7.20% over state-of-the-art fine-tuning methods while preserving the model's original functional coding utility.

Introduction

Code-generating LMs like GitHub Copilot and CodeGen have revolutionized software development. However, their reliance on open-source training data means they often replicate security vulnerabilities found in the wild. Studies indicate that up to 40% of LM-generated code may contain Common Weakness Enumerations (CWEs).

Current defenses primarily involve fine-tuning models on secure datasets. While effective for seen vulnerabilities, these methods often fail to generalize to novel security flaws and are susceptible to adversarial "poisoning" attacks. Furthermore, fine-tuning can degrade a model's general functional performance unless complex regularization techniques are employed. SecCoder addresses these challenges by treating security as an in-context learning task, requiring no changes to the underlying model weights.

The SecCoder Framework

SecCoder implements a four-stage pipeline designed to provide the LM with a "safe demonstration" that informs its generation process.

The SecCoder pipeline: from input prompt to secure code generation via dense retrieval and in-context learning.
  1. Expansion: A curated database of verified, secure code snippets is maintained as a reference.
  2. Demonstration Selection: For a given user prompt, a pre-trained dense retriever (INSTRUCTOR) identifies the most semantically similar secure code snippet from the database using cosine similarity. Dense retrieval is chosen over lexical methods (like BM25) for its superior ability to match underlying vulnerability patterns.
  3. Integration: The retrieved secure snippet is concatenated to the user's prompt, serving as a contextual guide.
  4. Secure Code Generation: The LM processes the augmented prompt. By observing the secure patterns in the demonstration, the model is naturally biased toward generating secure completions.

Experimental Evaluation

The authors evaluated SecCoder using a diverse set of benchmarks:

  • Security Performance: A dataset covering 9 CWEs across C/C++ and Python (He and Vechev, 2023).
  • Functional Correctness: The HumanEval benchmark to ensure coding utility is preserved.
  • Model Diversity: Testing across CodeGen (350M to 6.1B), SantaCoder (1.3B), and InCoder (6.7B).

Key Results

SecCoder demonstrates significant improvements in both security and robustness without sacrificing functional correctness.

Security performance comparison of SecCoder against baselines across different model families and sizes.
  • Superior Generalization: SecCoder outperformed the fine-tuned SVEN baseline by 7.20% on unseen test cases. This suggests that seeing a single relevant example is more effective for generalization than weight-based alignment.
  • Adversarial Robustness: In scenarios where models were intentionally attacked to generate vulnerable code, SecCoder recovered security by an average of 7.74%, acting as a robust defense layer.
  • Preserved Utility: Pass@k scores on HumanEval remained stable, confirming that SecCoder does not interfere with the model's fundamental ability to solve programming tasks.
  • Scalability: Performance gains scaled positively with both the size of the retriever and the size of the code LM, with the 6.1B CodeGen model reaching an 80.41% security rate.

Conclusion

SecCoder provides a powerful, training-free alternative to model fine-tuning for secure code generation. By leveraging retrieval-augmented in-context learning, it achieves better generalization and robustness while maintaining functional utility. As a model-agnostic "plug-and-play" solution, SecCoder is highly compatible with existing LMs and offers a scalable path toward safer AI-assisted software development. Future work will explore extending context windows to incorporate multiple demonstrations and improving performance for lower-level languages like C++.

Summary updated

BibTeX
@inproceedings{zhang2024seccoder,
  author = {Boyu Zhang and Tianyu Du and Junkai Tong and Xuhong Zhang and Kingsum Chow and Sheng Cheng and Xun Wang and Jianwei Yin},
  title = {{SecCoder: Towards Generalizable and Robust Secure Code Generation}},
  booktitle = {Conference on Empirical Methods in Natural Language Processing},
  year = {2024},
  doi = {10.18653/v1/2024.emnlp-main.806},
}
Figure