Skip to main content

dfyx-code-security-review

Expert-level code security audit skill using deep data flow analysis and business logic understanding for white-box static analysis across 9 languages

معلومات المصدر

المستودع
reason-machines/security-skills
آخر نشاط في المصدر
٨ يونيو ٢٠٢٦ في ١٥:٥٣
لغة SKILL.md المكتشفة
الإنجليزية
النجوم
١٢
التفرعات
١

خيارات التثبيت

يُحدَّد Prompt الذي يراجع المصدر أولًا بشكل افتراضي. يمكنك التبديل إلى أمر مباشر أو تنزيل نسخة محلية.

مراجعة ملفات المصدر

اقرأ SKILL.md وأي ملفات مرافقة يعرضها SkillsMP قبل أن تقرر التثبيت.

عرض SKILL.md

SKILL.md
تعليمات المصدر · معاينة للقراءة فقط
name
dfyx-code-security-review
description
Expert-level code security audit skill using deep data flow analysis and business logic understanding for white-box static analysis across 9 languages
triggers
["audit this codebase for security vulnerabilities","perform a security code review","find security issues in this project","analyze code for OWASP vulnerabilities","check for injection flaws and authentication issues","run a deep security audit","scan for SQL injection and RCE vulnerabilities","review code security following OWASP Top 10"]
# dfyx-code-security-review > Skill by [ara.so](https://ara.so) — Security Skills collection. A professional code security audit skill designed for AI coding agents, implementing a five-phase standardized audit protocol with dual-track analysis (Sink-driven, Control-driven, Config-driven) to systematically discover and validate security vulnerabilities in source code. ## Overview **dfyx_code_security_review** provides expert-level white-box static analysis capabilities covering: - **9 Languages**: Java, Python, Go, PHP, JavaScript/Node.js, C/C++, .NET/C#, Ruby, Rust - **10 Security Dimensions**: Injection, Authentication, Authorization, Deserialization, File Operations, SSRF, Cryptography, Configuration, Business Logic, Supply Chain - **14 Frameworks**: Spring Boot, Django, Flask, FastAPI, Express, Koa, Gin, Laravel, Rails, ASP.NET Core, Rust Web, NestJS/Fastify, MyBatis, ProcessWire ## Installation Clone the repository and integrate with your AI coding agent: ```bash # Clone the project git clone https://github.com/EastSword/skill-dfyx_code_security_review.git # For Claude Code cp -r skill-dfyx_code_security_review ~/.claude/skills/ # Install Python dependencies (optional, for standalone scripts) cd skill-dfyx_code_security_review pip install -r requirements.txt ``` ## Core Methodology ### Five-Phase Audit Protocol ``` Phase 1: Reconnaissance & Mapping (10%) ├─ Technology stack identification ├─ Architecture diagram generation └─ Attack surface enumeration Phase 2: Parallel Pattern Matching (30%) ├─ Sink-driven scanning (dangerous functions) ├─ Control-driven scanning (missing security controls) └─ Config-driven scanning (misconfigurations) Phase 3: Deep Taint Tracking & Practical Testing (40%) ├─ Data flow analysis ├─ Path-sensitive analysis └─ POC generation and verification Phase 4: Validation & Attack Chain Construction (15%) ├─ Vulnerability validation ├─ Attack chain analysis └─ Exploitability assessment Phase 5: Structured Reporting (5%) ├─ Vulnerability documentation ├─ Remediation guidance └─ Risk prioritization ``` ### Dual-Track Audit Model | Track | Dimensions | Method | Target | |-------|-----------|--------|--------| | **Sink-driven** | D1 Injection, D4 Deserialization, D5 File Ops, D6 SSRF | Grep dangerous functions → Trace data flow → Verify no protection | Existing dangerous code | | **Control-driven** | D3 Authorization, D9 Business Logic | Enumerate endpoints → Verify security controls exist → Missing = Vulnerability | Missing security controls | | **Config-driven** | D2 Authentication, D7 Crypto, D8 Config, D10 Supply Chain | Search configs → Compare security baseline | Misconfigurations | ## Security Dimensions | # | Dimension | Coverage | |---|-----------|----------| | D1 | Injection | SQL/Command/LDAP/SSTI/SpEL/JNDI/XPath/XML injection | | D2 | Authentication | Token/Session/JWT/Filter chain vulnerabilities | | D3 | Authorization | CRUD consistency, IDOR, horizontal privilege escalation | | D4 | Deserialization | Java/Python/PHP gadget chains, unsafe deserialization | | D5 | File Operations | Upload/download/path traversal vulnerabilities | | D6 | SSRF | URL injection, protocol bypass | | D7 | Cryptography | Key management, weak algorithms, improper KDF | | D8 | Configuration | Actuator exposure, CORS, error disclosure | | D9 | Business Logic | Race conditions, mass assignment, state machine flaws | | D10 | Supply Chain | Dependency CVEs, outdated packages | ## Scan Modes | Mode | Use Case | Scope | Time | |------|----------|-------|------| | **Quick** | CI/CD, small projects | Critical vulns, secrets, dependency CVEs | 5-10 min | | **Standard** | Regular audits | OWASP Top 10, auth/authz, crypto | 30-60 min | | **Deep** | Critical projects, pentest prep | Full coverage, attack chains, business logic | 1-3 hours | ## Usage Patterns ### Basic Audit Request Trigger an audit using natural language: ``` "Audit this codebase for security vulnerabilities" "Perform a deep security review of this Spring Boot project" "Find SQL injection and authentication issues" ``` The agent will respond with: ``` [MODE] deep [RECON] 874 files, Spring Boot 1.5 + Shiro 1.6 + JPA + Freemarker [PLAN] 5 Agents, D1-D10 coverage, estimated 125 turns [SCOPE] Focus areas: Authentication, SQL Injection, Deserialization Confirm to start audit? (yes/no) ``` ### Code Examples #### SQL Injection Detection (Java) **Vulnerable Code:** ```java // UserController.java @GetMapping("/user/search") public List<User> searchUser(@RequestParam String username) { String sql = "SELECT * FROM users WHERE username = '" + username + "'"; return jdbcTemplate.query(sql, new UserRowMapper()); } ``` **Detection Process:** ``` 1. [SINK] Identified dangerous sink: jdbcTemplate.query() 2. [SOURCE] Traced user input: @RequestParam username 3. [DATAFLOW] username → sql concatenation → jdbcTemplate.query() 4. [VALIDATION] No PreparedStatement, no input validation 5. [VULNERABILITY] SQL Injection (Critical) ``` **Remediation:** ```java // Fixed version @GetMapping("/user/search") public List<User> searchUser(@RequestParam String username) { String sql = "SELECT * FROM users WHERE username = ?"; return jdbcTemplate.query(sql, new Object[]{username}, new UserRowMapper()); } ``` #### Command Injection Detection (Python) **Vulnerable Code:** ```python # utils.py import subprocess def ping_host(host): cmd = f"ping -c 4 {host}" result = subprocess.call(cmd, shell=True) return result ``` **Detection Process:** ``` 1. [SINK] Identified dangerous sink: subprocess.call(shell=True) 2. [SOURCE] Traced user input: host parameter 3. [DATAFLOW] host → f-string interpolation → subprocess.call() 4. [VALIDATION] No input sanitization, shell=True enables injection 5. [VULNERABILITY] Command Injection (Critical) ``` **Remediation:** ```python # Fixed version import subprocess import shlex def ping_host(host): # Validate host format if not re.match(r'^[a-zA-Z0-9.-]+$', host): raise ValueError("Invalid host format") # Use list instead of shell result = subprocess.call(['ping', '-c', '4', host]) return result ``` #### Authorization Bypass Detection (Node.js) **Vulnerable Code:** ```javascript // routes/api.js router.get('/admin/users', (req, res) => { // Missing authorization check const users = db.getAllUsers(); res.json(users); }); router.delete('/admin/user/:id', (req, res) => { // Missing authorization check db.deleteUser(req.params.id); res.json({success: true}); }); ``` **Detection Process:** ``` 1. [CONTROL] Enumerated admin endpoints: /admin/users, /admin/user/:id 2. [CHECK] Searched for middleware: auth.isAdmin, requireAdmin 3. [MISSING] No authorization middleware found 4. [VALIDATION] Direct access possible without admin role 5. [VULNERABILITY] Missing Authorization (High) ``` **Remediation:** ```javascript // Fixed version const requireAdmin = (req, res, next) => { if (!req.user || req.user.role !== 'admin') { return res.status(403).json({error: 'Forbidden'}); } next(); }; router.get('/admin/users', requireAdmin, (req, res) => { const users = db.getAllUsers(); res.json(users); }); router.delete('/admin/user/:id', requireAdmin, (req, res) => { db.deleteUser(req.params.id); res.json({success: true}); }); ``` #### Deserialization Vulnerability (Java) **Vulnerable Code:** ```java // DataProcessor.java public Object processData(String base64Data) { byte[] data = Base64.getDecoder().decode(base64Data); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(data) ); return ois.readObject(); // Unsafe deserialization } ``` **Detection Process:** ``` 1. [SINK] Identified dangerous sink: ObjectInputStream.readObject() 2. [SOURCE] Traced user input: base64Data parameter 3. [DATAFLOW] base64Data → Base64 decode → readObject() 4. [GADGET] Checked classpath for known gadget chains (Commons-Collections) 5. [VULNERABILITY] Unsafe Deserialization → RCE (Critical) ``` **Remediation:** ```java // Fixed version using safe alternatives public Map<String, Object> processData(String jsonData) { ObjectMapper mapper = new ObjectMapper(); // Use JSON instead of Java serialization return mapper.readValue(jsonData, new TypeReference<Map<String, Object>>(){}); } // OR use whitelist if serialization is required public Object processData(String base64Data) { byte[] data = Base64.getDecoder().decode(base64Data); ValidatingObjectInputStream vois = new ValidatingObjectInputStream( new ByteArrayInputStream(data) ); // Whitelist allowed classes vois.accept(SafeClass.class, AnotherSafeClass.class); return vois.readObject(); } ``` #### Path Traversal Detection (PHP) **Vulnerable Code:** ```php // download.php <?php $file = $_GET['file']; $path = "/var/www/uploads/" . $file; if (file_exists($path)) { header('Content-Type: application/octet-stream'); readfile($path); } ?> ``` **Detection Process:** ``` 1. [SINK] Identified file operation: readfile() 2. [SOURCE] Traced user input: $_GET['file'] 3. [DATAFLOW] $_GET['file'] → concatenation → readfile() 4. [VALIDATION] No path sanitization, allows "../" sequences 5. [ATTACK] Payload: ?file=../../../etc/passwd 6. [VULNERABILITY] Path Traversal (High) ``` **Remediation:** ```php // Fixed version <?php function sanitizeFilename($filename) { // Remove directory traversal sequences $filename = str_replace(['../', '..\\'], '', $filename); // Only allow alphanumeric, dash, underscore, dot $filename = preg_replace('/[^a-zA-Z0-9._-]/', '', $filename); return basename($filename); } $file = sanitizeFilename($_GET['file']); $path = "/var/www/uploads/" . $file; // Verify file is within allowed directory $realpath = realpath($path); if ($realpath && strpos($realpath, '/var/www/uploads/') === 0 && file_exists($realpath)) { header('Content-Type: application/octet-stream'); readfile($realpath); } else { http_response_code(404); echo "File not found"; } ?> ``` ## Standalone Script Usage For command-line execution: ```bash # Full scan python scripts/code_scan.py /path/to/project --mode deep --output results.json # Quick scan (CI/CD) python scripts/code_scan.py /path/to/project --mode quick # Focus on specific dimensions python scripts/code_scan.py /path/to/project --dimensions D1,D2,D3 # Secret detection only python scripts/secret_finder.py /path/to/project # Dependency vulnerability check python scripts/dependency_analyzer.py /path/to/project # Generate report python scripts/report_generator.py --input results.json --output report.md ``` ### Python API Usage ```python from scripts.code_scan import SecurityScanner from scripts.data_flow_analyzer import DataFlowAnalyzer # Initialize scanner scanner = SecurityScanner(project_path='/path/to/project', mode='deep') # Run scan results = scanner.scan() # Analyze specific vulnerability dfa = DataFlowAnalyzer(project_path='/path/to/project') flow = dfa.trace_taint( source='request.getParameter("id")', sink='jdbcTemplate.query(sql)', file='UserController.java' ) # Generate report scanner.generate_report(results, output_file='security_report.md') ``` ## Configuration ### Environment Variables ```bash # Set audit mode
عرض على GitHub
ملف SKILL.md هذا كبير جدا، لذلك يعرض SkillsMP القسم الاول فقط هنا. عرض على GitHub