> For the complete documentation index, see [llms.txt](https://dizzzzy.gitbook.io/notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dizzzzy.gitbook.io/notebook/vulnerability-detection/python-code/py-vulnerability-detection1-paper-reproduction.md).

# Py Vulnerability Detection1-Paper Reproduction

论文复现

<figure><img src="https://3730186196-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrCG00nTO3O6DVWijfDnr%2Fuploads%2F3Rt5I5fucvBTahx7Fwmm%2Fimage.png?alt=media&amp;token=db80ead0-c497-4304-8b02-cad74ca1d481" alt=""><figcaption></figcaption></figure>

## DetectVul: A statement-level code vulnerability detection for Python <a href="#screen-reader-main-title" id="screen-reader-main-title"></a>

{% embed url="<https://www.sciencedirect.com/science/article/abs/pii/S0167739X24004680>" %}

{% embed url="<https://github.com/hchautran/DetectVul/tree/main>" %}

本文旨在介绍一种新颖的架构，该架构旨在避免图提取的需要，同时仍在 Python 的语句级 SVD 任务上实现卓越的性能。为此，在提出的架构中，我们用灵活的类似 BERT 的架构替换 GNN 模型来学习代码片段或函数中语句之间的复杂关系，从而消除了对图的依赖。具体来说，该模型由两个基于 BERT 的模型构成，分别用作特征提取器和分类器。这个想法背后的动机是，Transformer 的编码器块的架构是图神经网络 (GNN) 的一个特例，其中节点是全局互连的，每个编码器块中的自注意力层无需明确定义图结构即可形成数据驱动的图。这类似于 GNN 的消息传递机制，其中在图中的每一对节点之间建立可训练的加权连接。此外，这种方法将检测模型从预定义的图结构中解放出来，使其能够利用来自现实世界开源项目的大量数据来在节点之间形成更有意义的结构信息，从而提高性能。

替代GNN的Transformer架构：灵活性来源：Transformer的编码器（encoder block）在结构上与GNN类似，因为编码器的自注意力机制（self-attention）允许每个节点（代码中的语句）与所有其他节点相互关联。无显式图需求：这种全局互联机制本质上可以看作数据驱动的图构造，避免了显式的图提取步骤。消息传递机制的对应性：在GNN中，消息传递通过图的边进行，节点共享信息。在Transformer中，使用自注意力机制，通过可训练的权重矩阵实现“节点间的信息传递”。

双BERT模型设计：**一个BERT模型作为特征提取器，学习代码片段中语句之间的复杂关系。另一个BERT模型作为分类器，用于检测和预测漏洞位置**。

语句类型增强：漏洞通常集中在某些特定类型的语句（如条件语句、赋值语句或循环语句）。**为每个语句引入其类型信息**（可能是附加标记或特定嵌入），以增强模型对不同语句的区分能力，从而更准确地检测漏洞。以下是一组训练数据的附加标签和label：

```
'lines': ['@integration_synonym_api...\n', 'FUNC_2(VAR_2)\n', "FUNC_3(VAR_2, 'VENIZIA', VAR_7='1')\n", "FUNC_3(VAR_2, 'VENEZIA', VAR_7='2')\n", "FUNC_3(VAR_2, 'VANSEA', VAR_7='3')\n", "FUNC_3(VAR_2, 'WENSO', VAR_7='4')\n", "FUNC_5(VAR_4, VAR_5, VAR_11='VENIZIA', VAR_10=[{'name': '----VENIZIA'}, {\n    'name': 'VENEZIA'}])\n"], 
'raw_lines': ['@integration_synonym_api...\n', 'clean_database(solr)\n', "seed_database_with(solr, 'VENIZIA', id='1')\n", "seed_database_with(solr, 'VENEZIA', id='2')\n", "seed_database_with(solr, 'VANSEA', id='3')\n", "seed_database_with(solr, 'WENSO', id='4')\n", "verify_results(client, jwt, query='VENIZIA', expected=[{'name':\n    '----VENIZIA'}, {'name': 'VENEZIA'}])\n"], 
'label': [0, 0, 0, 0, 0, 0, 0], 
'type': ['Condition', "Expr'", "Expr'", "Expr'", "Expr'", "Expr'", "Expr'"]
```

论文的模型在hugging face：<https://huggingface.co/DetectVul>

````python
```python
class DetectBERT(nn.Module):
    #结合预训练的嵌入模型和 BERT 分类器
    def __init__(self, embs_model_ckt:str, num_labels:int, num_hidden_layers=6, max_lines=1024, heads=12 ,func_cls=False):
        super(DetectBERT, self).__init__()
        self.embs_model, self.tokenizer = get_model_and_tokenizer(embs_model_ckt)
        #BERT1：self.embs_model用预训练的bert模型提取特征
        print(device)
        self.embs_model = self.embs_model.to(device)
        config = BertConfig(
            vocab_size=1,
            num_attention_heads=heads,
            hidden_size=self.embs_model.config.hidden_size,
            num_hidden_layers=num_hidden_layers,
            max_position_embeddings=max_lines,
            num_labels=num_labels,
            
        )
        self.func_cls = func_cls
        #BERT2： self.model使用上一步特征进行行级分类，完成最终预测。
        self.model = BertForLineClassification(config=config).to(device)
```
````

<figure><img src="https://3730186196-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrCG00nTO3O6DVWijfDnr%2Fuploads%2FOOEyoAQsuFm9fJNaZirW%2Fimage.png?alt=media&amp;token=5345d876-20b8-403c-ae8c-b37569e7c20f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3730186196-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrCG00nTO3O6DVWijfDnr%2Fuploads%2FGmHSxhsgeGlCpOSGSZri%2Fimage.png?alt=media&amp;token=4b928cca-4799-47ea-8779-debaf9479eb6" alt=""><figcaption></figcaption></figure>

## PyVulDet-NER: Python source code vulnerability detection with named entity recognition <a href="#screen-reader-main-title" id="screen-reader-main-title"></a>

{% embed url="<https://www.sciencedirect.com/science/article/pii/S0167404824001032?via%3Dihub>" %}
