feat: (UNFINISH) 正则匹配检测测试

This commit is contained in:
tritium0041 2024-06-03 13:44:03 +08:00
parent da9b2b52ac
commit 1a71a72ddf
4 changed files with 35 additions and 10 deletions

View File

@ -12,7 +12,7 @@ def find_dangerous_functions(
r"\bexec\(": "high",
r"\bpopen\(": "medium",
r"\beval\(": "high",
r"\bsubprocess\.run\(": "medium",
r"\bsubprocess": "medium",
r"\b__getattribute__\(": "high",
r"\bgetattr\(": "medium",
r"\b__import__\(": "high",

View File

@ -4,7 +4,7 @@ import sys
def read_file_content(file_path: str) -> str:
try:
with open(file_path, "r", encoding="utf-8") as file:
with open(file_path, "r", encoding="utf-8",errors="ignore") as file:
return file.read()
except FileNotFoundError:
print("Error: File not found.")

View File

@ -1,5 +1,5 @@
from typing import Tuple
from git import Repo # type: ignore
from git import Repo
import random
from pathlib import Path
@ -20,7 +20,7 @@ def clone_repo(repo_url: str, clone_dir: str) -> None:
def inject_random_backdoor(
path: str, pickle: bool = False, pyc: bool = False, sample_rate: float = 0.1
) -> None:
) -> int:
"""
Insert random backdoor into the path.
@ -42,9 +42,10 @@ def inject_random_backdoor(
# sample files to inject backdoor
if random.random() < sample_rate:
injected_python_files.append(python_file)
injectedNum = len(injected_python_files)
print([str(i) for i in injected_python_files])
for python_file in injected_python_files:
with open(python_file, "r+") as f:
with open(python_file, "r+",errors="ignore") as f:
lines = f.readlines()
total_lines = len(lines)
inject_line_number = random.randint(0, total_lines)
@ -57,6 +58,7 @@ def inject_random_backdoor(
# Write the modified content back to the file
f.writelines(lines)
return injectedNum
# 示例1: 通过 os.system 执行命令

View File

@ -1,10 +1,33 @@
import unittest
import os
import shutil
from detection.utils import read_file_content
from .final_tests_util import *
from detection.Regexdetection import find_dangerous_functions
from detection.GPTdetection import detectGPT
class TestFinalTests(unittest.TestCase):
def setUp(self) -> None:
return super().setUp()
def test_final_tests(self):
self.assertTrue(True)
shutil.rmtree("./tmp/repo", ignore_errors=True)
clone_repo("https://github.com/TheAlgorithms/Python.git", "./tmp/repo")
sampleRate = 0.1
injectedNum = inject_random_backdoor("./tmp/repo",sample_rate=sampleRate)
project_path = Path("./tmp/repo")
all_python_files = list(project_path.rglob("*.py"))
filesNum = len(all_python_files)
trueRate = injectedNum / filesNum
detectedNum = 0
for file in all_python_files:
content = read_file_content(str(file))
results = find_dangerous_functions(content, ".py")
if len(results["high"]) > 0 or len(results["medium"]) > 0 or len(results["low"]) > 0:
print(str(file))
detectedNum += 1
shutil.rmtree("./tmp/repo",ignore_errors=True)
self.assertAlmostEquals(detectedNum / filesNum, trueRate, places=1)
if __name__ == "__main__":
unittest.main()