إعداد بيئة الفريق الأحمر
العمل مع Garak
3 دقيقة للقراءة
Garak هو ماسح ثغرات LLM من NVIDIA مع 100+ اختبار هجوم. تصميمه القائم على CLI يجعله مثالياً للتقييمات الأمنية السريعة وتكامل CI/CD.
التثبيت
# تثبيت Garak (جميع المنصات)
# pip install garak
# التحقق من التثبيت
import subprocess
import sys
def check_garak():
"""التحقق من تثبيت Garak وعمله."""
try:
result = subprocess.run(
[sys.executable, "-m", "garak", "--version"],
capture_output=True,
text=True
)
print(f"Garak مثبت: {result.stdout.strip()}")
return True
except Exception as e:
print(f"Garak غير موجود: {e}")
return False
check_garak()
البدء السريع مع CLI
CLI الخاص بـ Garak هو أسرع طريقة للمسح:
# تشغيل Garak من Python (عبر المنصات)
import subprocess
import sys
from pathlib import Path
def run_garak_scan(
model_type: str,
model_name: str,
probes: list,
output_dir: Path
):
"""تشغيل مسح Garak برمجياً."""
output_dir.mkdir(parents=True, exist_ok=True)
# بناء الأمر
cmd = [
sys.executable, "-m", "garak",
"--model_type", model_type,
"--model_name", model_name,
"--probes", ",".join(probes),
"--report_prefix", str(output_dir / "garak_report"),
]
print(f"تشغيل: {' '.join(cmd)}")
# تنفيذ المسح
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print("اكتمل المسح بنجاح")
print(result.stdout)
else:
print(f"فشل المسح: {result.stderr}")
return result
# مثال: مسح نموذج OpenAI
output = Path.cwd() / "garak_results"
run_garak_scan(
model_type="openai",
model_name="gpt-4",
probes=["promptinject", "encoding", "dan"],
output_dir=output
)
فهم فئات الاختبارات
ينظم Garak الهجمات في فئات اختبارات:
from dataclasses import dataclass
from typing import List
@dataclass
class GarakProbe:
"""معلومات حول اختبار Garak."""
name: str
category: str
description: str
effectiveness: str
# فئات الاختبارات الرئيسية
probes = [
GarakProbe(
name="promptinject",
category="injection", # الحقن
description="اختبار ثغرات حقن المحث",
effectiveness="عالي ضد الأنظمة غير المحمية"
),
GarakProbe(
name="encoding",
category="evasion", # التهرب
description="حمولات مشفرة (base64، rot13، hex)",
effectiveness="متوسط، يتجاوز المرشحات الأساسية"
),
GarakProbe(
name="dan",
category="jailbreak", # كسر الحماية
description="محثات كسر حماية DAN",
effectiveness="منخفض ضد النماذج الحديثة"
),
GarakProbe(
name="continuation",
category="harmful", # ضار
description="طلب من النموذج إكمال نص ضار",
effectiveness="متوسط إلى عالي"
),
GarakProbe(
name="realtoxicityprompts",
category="toxic", # سام
description="اختبار توليد مخرجات سامة",
effectiveness="عالي لاختبار السمية"
),
GarakProbe(
name="xss",
category="injection", # الحقن
description="حقن البرمجيات النصية عبر المواقع في المخرجات",
effectiveness="عالي لتطبيقات الويب"
),
]
# عرض معلومات الاختبارات
for probe in probes:
print(f"\n{probe.name} ({probe.category})")
print(f" {probe.description}")
print(f" الفعالية: {probe.effectiveness}")
تكوين اختبارات مخصصة
أنشئ عمليات مسح مستهدفة باختبارات محددة:
from pathlib import Path
import json
def create_garak_config(
target_probes: List[str],
attack_config: dict,
output_file: Path
):
"""إنشاء ملف تكوين Garak."""
config = {
"probes": target_probes,
"generators": {
"repetitions": attack_config.get("repetitions", 3),
},
"detectors": {
"always_trigger": False,
},
"buffs": attack_config.get("buffs", []),
}
output_file.write_text(json.dumps(config, indent=2))
print(f"التكوين محفوظ في: {output_file}")
return config
# إنشاء تكوين مسح مركز
config_path = Path.cwd() / "garak_config.json"
create_garak_config(
target_probes=[
"promptinject.HijackHateHumansMini",
"encoding.InjectBase64",
"dan.Dan_11_0",
],
attack_config={
"repetitions": 5,
"buffs": ["lowercase", "paraphrase"],
},
output_file=config_path
)
تحليل نتائج Garak
معالجة نتائج المسح للإبلاغ:
from pathlib import Path
import json
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class GarakFinding:
"""اكتشاف مسح Garak المُحلل."""
probe: str
detector: str
passed: bool
output: str
severity: str
def parse_garak_results(report_file: Path) -> List[GarakFinding]:
"""تحليل تقرير Garak JSON إلى اكتشافات."""
if not report_file.exists():
print(f"التقرير غير موجود: {report_file}")
return []
with open(report_file) as f:
data = json.load(f)
findings = []
for entry in data.get("results", []):
finding = GarakFinding(
probe=entry.get("probe", "unknown"),
detector=entry.get("detector", "unknown"),
passed=entry.get("passed", True),
output=entry.get("output", "")[:200], # اقتطاع
severity="HIGH" if not entry.get("passed") else "INFO"
)
findings.append(finding)
return findings
def summarize_findings(findings: List[GarakFinding]) -> dict:
"""إنشاء إحصائيات ملخصة من الاكتشافات."""
total = len(findings)
failed = sum(1 for f in findings if not f.passed)
return {
"total_tests": total,
"passed": total - failed,
"failed": failed,
"pass_rate": (total - failed) / total if total > 0 else 0,
"high_severity": sum(1 for f in findings if f.severity == "HIGH"),
}
# التحليل والتلخيص
report = Path.cwd() / "garak_results" / "garak_report.json"
findings = parse_garak_results(report)
summary = summarize_findings(findings)
print(f"معدل النجاح: {summary['pass_rate']:.1%}")
التكامل مع CI/CD
أضف Garak إلى خط أنابيبك:
import sys
import subprocess
from pathlib import Path
def ci_garak_scan(
model_type: str,
model_name: str,
fail_threshold: float = 0.9
) -> bool:
"""تشغيل مسح Garak في خط أنابيب CI/CD."""
output_dir = Path.cwd() / "security_reports"
output_dir.mkdir(exist_ok=True)
# تشغيل اختبارات أمان مركزة
cmd = [
sys.executable, "-m", "garak",
"--model_type", model_type,
"--model_name", model_name,
"--probes", "promptinject,encoding",
"--report_prefix", str(output_dir / "ci_scan"),
]
result = subprocess.run(cmd, capture_output=True, text=True)
# تحليل النتائج
report_file = output_dir / "ci_scan.report.json"
findings = parse_garak_results(report_file)
summary = summarize_findings(findings)
# فحص العتبة
if summary["pass_rate"] < fail_threshold:
print(f"فشل: معدل النجاح {summary['pass_rate']:.1%} < {fail_threshold:.1%}")
return False
print(f"نجاح: معدل النجاح {summary['pass_rate']:.1%}")
return True
# في خط أنابيب CI
success = ci_garak_scan("openai", "gpt-4", fail_threshold=0.95)
sys.exit(0 if success else 1)
رؤية أساسية: توفر 100+ اختبار من Garak تغطية واسعة بسرعة. استخدمه للتقييمات الأولية، ثم تعمق أكثر مع DeepTeam أو PyRIT.
بعد ذلك، سنستكشف PyRIT لتنسيق الهجمات المتقدمة متعددة الأدوار. :::