Constrained Decoding for Secure Code Generation

Yanjun Fu, Ethan Baker, Yizheng ChenarXiv 2024

Abstract

Code Large Language Models (Code LLMs) have been increasingly used by developers to boost productivity, but they often generate vulnerable code. Thus, there is an urgent need to ensure that code generated by Code LLMs is correct and secure. Previous research has primarily focused on generating secure code, overlooking the fact that secure code also needs to be correct. This oversight can lead to a false sense of security. Currently, the community lacks a method to measure actual progress in this area, and we need solutions that address both security and correctness of code generation. This paper introduces a new benchmark, CodeGuard+, along with two new metrics, to measure Code LLMs' ability to generate both secure and correct code. Using our new evaluation methods, we show that the state-of-the-art defense technique, prefix tuning, may not be as strong as previously believed, since it generates secure code but sacrifices functional correctness. We also demonstrate that different decoding methods significantly affect the security of Code LLMs. Furthermore, we explore a new defense direction: constrained decoding for secure code generation. We propose new constrained decoding techniques to generate secure code. Our results reveal that constrained decoding is more effective than prefix tuning to improve the security of Code LLMs, without requiring a specialized training dataset. Moreover, our evaluations over eight state-of-the-art Code LLMs show that constrained decoding has strong performance to improve the security of Code LLMs, and our technique outperforms GPT-4.

Introduction

Large Language Models (LLMs) like GitHub Copilot and CodeLlama have revolutionized software development. However, their widespread adoption is hindered by a critical "security-correctness" gap. Research indicates that up to 40% of LLM-generated code contains vulnerabilities such as SQL injection, buffer overflows, or improper input validation.

Current research faces two primary hurdles. First, there is an evaluation blind spot: existing benchmarks typically test either functional correctness (does the code work?) or security (is the code safe?), but rarely both. This can lead to misleading results where a model appears secure simply because it generates trivial or non-functional code. Second, existing defenses like prefix tuning often suffer from a performance trade-off, where attempts to improve security inadvertently degrade the model's ability to produce working code.

The CODEGUARD+ Benchmark

To address these limitations, we introduce CODEGUARD+, a comprehensive benchmark designed to evaluate the intersection of security and functional correctness. CODEGUARD+ expands significantly upon previous datasets, featuring 91 prompts that cover 34 distinct Common Weakness Enumerations (CWEs) across both C/C++ and Python.

Table 1: Overview of CODEGUARD+ prompts, including summaries, unit tests, and security constraints.

A key innovation of CODEGUARD+ is the inclusion of a full suite of unit tests for every prompt. This allows for the measurement of a new metric: secure-pass@k. This metric calculates the probability that a model generates a code snippet that is both functionally correct (passes all unit tests) and secure (passes vulnerability scanners). By requiring both criteria, we eliminate the "false sense of security" provided by non-functional but safe code.

Methodology: Constrained Decoding

Rather than treating LLMs as black boxes or requiring expensive retraining, we propose intervening in the decoding process—the stage where the model selects the next token in a sequence. We explore two primary techniques:

  1. Constrained Beam Sampling: This modifies standard beam search by enforcing security patterns during generation. The algorithm "force-feeds" positive security patterns (e.g., mandatory array bounds checks) and "blocks" tokens that lead to known vulnerable patterns (e.g., the use of sprintf in C).
  2. MUCOLA Adaptation: We adapted the MUCOLA (MUlti-COnstraint LAnguage) technique, which treats code generation as a mathematical optimization problem. It iteratively refines the entire output to satisfy security constraints.

Unlike prefix tuning, which requires a specialized training dataset of secure code, constrained decoding works "out of the box" on pre-trained models. The security rules are applied at inference time, allowing for better generalization to unseen vulnerabilities.

Key Results

Our evaluation across eight state-of-the-art Code LLMs demonstrates the superior performance of constrained decoding.

Figure 1: Performance of various Code LLMs using Nucleus Sampling vs. Constrained Decoding, compared against a GPT-4 baseline.

As shown in the results, constrained decoding consistently improves the secure-pass@1 score across all tested models. Notably, every open-source model tested (ranging from 2.7B to 34B parameters) outperformed the much larger, proprietary GPT-4 (which achieved a secure-pass@1 of 47.45%) when our decoding constraints were applied.

Furthermore, we found that previous state-of-the-art defenses like SVEN (based on prefix tuning) often achieved high security scores by sacrificing correctness. In contrast, our constrained decoding approach on CodeGen-2.7B achieved a 51.25% secure-pass@1 score, significantly outperforming SVEN’s 36.3%.

Discussion and Limitations

While constrained decoding offers a powerful and training-free path toward secure code generation, some challenges remain. Currently, security constraints must be manually specified by experts. Future work should focus on automatically mining these constraints from security documentation or existing "safe" libraries. Additionally, while effective, constrained decoding introduces computational overhead during inference, which may impact the latency of real-time developer tools.

Conclusion

Ensuring that AI-generated code is both secure and correct is paramount for the future of software engineering. By introducing the CODEGUARD+ benchmark and demonstrating the effectiveness of constrained decoding, this work provides a robust framework for measuring and improving the security of Code LLMs without compromising their utility.

Summary updated

BibTeX
@misc{fu2024constrained,
  author = {Yanjun Fu and Ethan Baker and Yizheng Chen},
  title = {{Constrained Decoding for Secure Code Generation}},
  year = {2024},
  eprint = {2405.00218},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2405.00218},
}
Figure