@intentsolutionsio/security-agent 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +16 -0
- package/LICENSE +21 -0
- package/README.md +57 -0
- package/agents/security-reviewer.md +64 -0
- package/package.json +38 -0
- package/skills/performing-security-code-review/SKILL.md +84 -0
- package/skills/performing-security-code-review/assets/README.md +7 -0
- package/skills/performing-security-code-review/assets/example_code_secure.py +225 -0
- package/skills/performing-security-code-review/assets/example_code_vulnerable.py +192 -0
- package/skills/performing-security-code-review/assets/report_template.md +76 -0
- package/skills/performing-security-code-review/references/README.md +4 -0
- package/skills/performing-security-code-review/scripts/README.md +7 -0
- package/skills/performing-security-code-review/scripts/code_analyzer.py +134 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "security-agent",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Specialized security review subagent",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Jeremy Longshore"
|
|
7
|
+
},
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"security",
|
|
11
|
+
"agent",
|
|
12
|
+
"code-review",
|
|
13
|
+
"vulnerability",
|
|
14
|
+
"agent-skills"
|
|
15
|
+
]
|
|
16
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 Jeremy Longshore & Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Security Agent Plugin
|
|
2
|
+
|
|
3
|
+
A specialized security review subagent for identifying vulnerabilities and providing security guidance.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
/plugin install security-agent@claude-code-plugins-plus
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
The security reviewer agent will automatically activate when you:
|
|
14
|
+
- Ask Claude to review code for security issues
|
|
15
|
+
- Request a security audit
|
|
16
|
+
- Mention security concerns in your prompt
|
|
17
|
+
|
|
18
|
+
**Manual invocation**:
|
|
19
|
+
```
|
|
20
|
+
@security-reviewer Please review this authentication code for security vulnerabilities
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## What It Reviews
|
|
24
|
+
|
|
25
|
+
- SQL injection vulnerabilities
|
|
26
|
+
- Cross-site scripting (XSS)
|
|
27
|
+
- Authentication/authorization flaws
|
|
28
|
+
- Input validation issues
|
|
29
|
+
- Cryptographic weaknesses
|
|
30
|
+
- Dependency vulnerabilities
|
|
31
|
+
- Secure coding practices
|
|
32
|
+
|
|
33
|
+
## Output
|
|
34
|
+
|
|
35
|
+
Provides structured security findings with:
|
|
36
|
+
- Severity ratings
|
|
37
|
+
- Specific code locations
|
|
38
|
+
- Impact assessment
|
|
39
|
+
- Remediation guidance
|
|
40
|
+
- Secure code examples
|
|
41
|
+
|
|
42
|
+
## Learning Objectives
|
|
43
|
+
|
|
44
|
+
This plugin demonstrates:
|
|
45
|
+
- Creating specialized subagents
|
|
46
|
+
- Defining agent capabilities
|
|
47
|
+
- Writing agent prompts
|
|
48
|
+
- Agent activation patterns
|
|
49
|
+
|
|
50
|
+
## Files
|
|
51
|
+
|
|
52
|
+
- `.claude-plugin/plugin.json` - Plugin manifest
|
|
53
|
+
- `agents/security-reviewer.md` - Agent definition
|
|
54
|
+
|
|
55
|
+
## License
|
|
56
|
+
|
|
57
|
+
MIT
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: security-reviewer
|
|
3
|
+
description: Security code review specialist
|
|
4
|
+
---
|
|
5
|
+
# Security Reviewer Agent
|
|
6
|
+
|
|
7
|
+
You are a specialized security code review agent with deep expertise in application security, vulnerability detection, and secure coding practices.
|
|
8
|
+
|
|
9
|
+
## Your Capabilities
|
|
10
|
+
|
|
11
|
+
- **Vulnerability Detection**: Identify security vulnerabilities including SQL injection, XSS, CSRF, authentication flaws, and authorization issues
|
|
12
|
+
- **Security Analysis**: Analyze code for security weaknesses, insecure dependencies, and configuration issues
|
|
13
|
+
- **Compliance Checking**: Verify code meets security standards (OWASP Top 10, CWE, etc.)
|
|
14
|
+
- **Remediation Guidance**: Provide specific, actionable recommendations for fixing security issues
|
|
15
|
+
|
|
16
|
+
## When to Activate
|
|
17
|
+
|
|
18
|
+
You should be invoked when:
|
|
19
|
+
- Reviewing code for security issues
|
|
20
|
+
- Conducting security audits
|
|
21
|
+
- Analyzing authentication/authorization logic
|
|
22
|
+
- Reviewing input validation and sanitization
|
|
23
|
+
- Examining cryptographic implementations
|
|
24
|
+
- Assessing API security
|
|
25
|
+
|
|
26
|
+
## Review Process
|
|
27
|
+
|
|
28
|
+
1. **Scan for Common Vulnerabilities**:
|
|
29
|
+
- SQL injection points
|
|
30
|
+
- Cross-site scripting (XSS) opportunities
|
|
31
|
+
- CSRF vulnerabilities
|
|
32
|
+
- Authentication/authorization flaws
|
|
33
|
+
- Insecure deserialization
|
|
34
|
+
- Sensitive data exposure
|
|
35
|
+
|
|
36
|
+
2. **Check Secure Coding Practices**:
|
|
37
|
+
- Input validation and sanitization
|
|
38
|
+
- Output encoding
|
|
39
|
+
- Parameterized queries
|
|
40
|
+
- Secure session management
|
|
41
|
+
- Proper error handling (no info leakage)
|
|
42
|
+
|
|
43
|
+
3. **Review Dependencies**:
|
|
44
|
+
- Known vulnerable packages
|
|
45
|
+
- Outdated dependencies
|
|
46
|
+
- License compliance
|
|
47
|
+
|
|
48
|
+
4. **Provide Recommendations**:
|
|
49
|
+
- Severity rating (Critical/High/Medium/Low)
|
|
50
|
+
- Specific code locations
|
|
51
|
+
- Remediation steps
|
|
52
|
+
- Example secure code
|
|
53
|
+
|
|
54
|
+
## Output Format
|
|
55
|
+
|
|
56
|
+
For each finding, provide:
|
|
57
|
+
- **Severity**: Critical/High/Medium/Low
|
|
58
|
+
- **Issue**: Description of the vulnerability
|
|
59
|
+
- **Location**: File and line numbers
|
|
60
|
+
- **Impact**: Potential consequences
|
|
61
|
+
- **Recommendation**: How to fix it
|
|
62
|
+
- **Example**: Secure code snippet
|
|
63
|
+
|
|
64
|
+
Always prioritize findings by severity and focus on exploitable vulnerabilities first.
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@intentsolutionsio/security-agent",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Specialized security review subagent",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"security",
|
|
7
|
+
"agent",
|
|
8
|
+
"code-review",
|
|
9
|
+
"vulnerability",
|
|
10
|
+
"agent-skills",
|
|
11
|
+
"claude-code",
|
|
12
|
+
"claude-plugin",
|
|
13
|
+
"tonsofskills"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/jeremylongshore/claude-code-plugins-plus-skills.git",
|
|
18
|
+
"directory": "plugins/examples/security-agent"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://tonsofskills.com/plugins/security-agent",
|
|
21
|
+
"bugs": "https://github.com/jeremylongshore/claude-code-plugins-plus-skills/issues",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"author": {
|
|
24
|
+
"name": "Jeremy Longshore"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"README.md",
|
|
31
|
+
".claude-plugin",
|
|
32
|
+
"skills",
|
|
33
|
+
"agents"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"postinstall": "node -e \"console.log(\\\"\\\\nā This npm package is a tracking/proof artifact. Install the plugin via:\\\\n ccpi install security-agent\\\\n or /plugin install security-agent@claude-code-plugins-plus in Claude Code\\\\n\\\")\""
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: performing-security-code-review
|
|
3
|
+
description: |
|
|
4
|
+
Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin. it analyzes code for potential vulnerabilities like sql injection, xss, authentication flaws, and insecure dependencies. AI assistant uses this skill wh... Use when assessing security or running audits. Trigger with phrases like 'security scan', 'audit', or 'vulnerability'.
|
|
5
|
+
allowed-tools: Read, Write, Edit, Grep, Glob, Bash(cmd:*)
|
|
6
|
+
version: 1.0.0
|
|
7
|
+
author: Jeremy Longshore <jeremy@intentsolutions.io>
|
|
8
|
+
license: MIT
|
|
9
|
+
compatible-with: claude-code, codex, openclaw
|
|
10
|
+
tags: [example, security, authentication, audit]
|
|
11
|
+
---
|
|
12
|
+
# Performing Security Code Review
|
|
13
|
+
|
|
14
|
+
## Overview
|
|
15
|
+
|
|
16
|
+
Conducts security-focused code reviews by scanning source files for common vulnerability patterns including SQL injection, XSS, authentication flaws, insecure dependencies, and secret exposure. Produces structured severity-rated reports with specific remediation guidance.
|
|
17
|
+
|
|
18
|
+
## Prerequisites
|
|
19
|
+
|
|
20
|
+
- Read access to all source files in the target project
|
|
21
|
+
- `grep` available on PATH for pattern matching
|
|
22
|
+
- Access to `package.json` or equivalent dependency manifest for dependency auditing
|
|
23
|
+
- Familiarity with OWASP Top 10 vulnerability categories
|
|
24
|
+
|
|
25
|
+
## Instructions
|
|
26
|
+
|
|
27
|
+
1. Identify the scope of the review: specific files, directories, or the entire codebase. Confirm the primary language(s) and framework(s) in use.
|
|
28
|
+
2. Scan for hardcoded secrets and credentials:
|
|
29
|
+
- Search for patterns matching API keys, tokens, passwords, AWS access keys (`AKIA...`), and private key headers (`BEGIN PRIVATE KEY`).
|
|
30
|
+
- Flag any `.env` files or configuration files containing plaintext secrets.
|
|
31
|
+
3. Analyze code for injection vulnerabilities:
|
|
32
|
+
- Identify raw SQL string concatenation (SQL injection risk).
|
|
33
|
+
- Locate unsanitized user input rendered in HTML (XSS risk).
|
|
34
|
+
- Check for `eval()`, `exec()`, or `Function()` calls with dynamic input (code injection risk).
|
|
35
|
+
4. Review authentication and authorization logic:
|
|
36
|
+
- Verify password hashing uses strong algorithms (bcrypt, argon2) rather than MD5/SHA1.
|
|
37
|
+
- Check for missing authentication on sensitive endpoints.
|
|
38
|
+
- Identify overly permissive CORS configurations.
|
|
39
|
+
5. Audit dependencies for known vulnerabilities:
|
|
40
|
+
- Run `npm audit` or equivalent package manager audit command.
|
|
41
|
+
- Cross-reference dependency versions against known CVE databases.
|
|
42
|
+
6. Check for insecure communication patterns:
|
|
43
|
+
- Flag HTTP URLs where HTTPS is expected.
|
|
44
|
+
- Identify disabled TLS certificate verification.
|
|
45
|
+
7. Compile findings into a structured report sorted by severity (Critical, High, Medium, Low), including the vulnerable code location, explanation, and remediation steps.
|
|
46
|
+
|
|
47
|
+
## Output
|
|
48
|
+
|
|
49
|
+
A structured security review report containing:
|
|
50
|
+
- Summary with total findings count by severity level
|
|
51
|
+
- Per-finding entries with: file path, line number, vulnerability type, severity, code snippet, explanation, and recommended fix
|
|
52
|
+
- Dependency audit results with CVE identifiers where applicable
|
|
53
|
+
- Overall risk assessment (Critical / High / Medium / Low / Clean)
|
|
54
|
+
|
|
55
|
+
## Error Handling
|
|
56
|
+
|
|
57
|
+
| Error | Cause | Solution |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| No source files found | Incorrect scope path or empty directory | Verify the target directory path and confirm it contains source files |
|
|
60
|
+
| Binary files in scan | Non-text files matched by search patterns | Exclude binary extensions and `node_modules/` from scans |
|
|
61
|
+
| Dependency manifest missing | No `package.json`, `requirements.txt`, or equivalent | Skip dependency audit; note in report that dependency analysis was not possible |
|
|
62
|
+
| Permission denied on files | Restricted file access | Request read permissions or narrow the review scope to accessible files |
|
|
63
|
+
| False positive on secret pattern | Benign string matching secret regex | Verify context before reporting; mark as potential false positive if the match appears in test fixtures or documentation |
|
|
64
|
+
|
|
65
|
+
## Examples
|
|
66
|
+
|
|
67
|
+
**SQL injection review:**
|
|
68
|
+
Trigger: "Review this database query code for SQL injection vulnerabilities."
|
|
69
|
+
Process: Scan all files containing SQL query construction. Identify string concatenation with user input (`"SELECT * FROM users WHERE id = " + userId`). Report as High severity with remediation: use parameterized queries or prepared statements.
|
|
70
|
+
|
|
71
|
+
**Dependency vulnerability scan:**
|
|
72
|
+
Trigger: "Check this project's dependencies for known security vulnerabilities."
|
|
73
|
+
Process: Run `npm audit` on the project. Parse output for vulnerabilities. Report each finding with CVE identifier, affected package, installed version, and patched version. Recommend `npm audit fix` or manual version pinning.
|
|
74
|
+
|
|
75
|
+
**Full codebase security audit:**
|
|
76
|
+
Trigger: "Run a security scan on this codebase."
|
|
77
|
+
Process: Execute all seven scan categories (secrets, injection, auth, dependencies, communication, dangerous commands, obfuscation). Produce a comprehensive report with findings grouped by category and sorted by severity.
|
|
78
|
+
|
|
79
|
+
## Resources
|
|
80
|
+
|
|
81
|
+
- [OWASP Top 10](https://owasp.org/www-project-top-ten/) -- industry-standard vulnerability classification
|
|
82
|
+
- [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) -- Node-specific security guidance
|
|
83
|
+
- [CWE/SANS Top 25](https://cwe.mitre.org/top25/) -- most dangerous software weaknesses
|
|
84
|
+
- `${CLAUDE_SKILL_DIR}/references/README.md` -- bundled reference materials
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Assets
|
|
2
|
+
|
|
3
|
+
Bundled resources for security-agent skill
|
|
4
|
+
|
|
5
|
+
- [ ] report_template.md: A Markdown template for generating security review reports with placeholders for findings, severity ratings, and remediation advice.
|
|
6
|
+
- [ ] example_code_vulnerable.py: Example code snippets demonstrating common vulnerabilities.
|
|
7
|
+
- [ ] example_code_secure.py: Corresponding secure code snippets demonstrating how to remediate the vulnerabilities.
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Example secure code snippets demonstrating how to remediate common vulnerabilities.
|
|
5
|
+
|
|
6
|
+
This module provides examples of secure coding practices to address various security concerns.
|
|
7
|
+
It includes functions demonstrating secure authentication, input validation, and more.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import os
|
|
13
|
+
import secrets
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
def secure_password_hashing(password: str, salt: bytes = None) -> tuple[str, str]:
|
|
17
|
+
"""
|
|
18
|
+
Hashes a password using a strong hashing algorithm (e.g., bcrypt or scrypt).
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
password: The password to hash.
|
|
22
|
+
salt: Optional salt to use. If None, a new salt is generated.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
A tuple containing the salt (as a hex string) and the hash (as a hex string).
|
|
26
|
+
"""
|
|
27
|
+
try:
|
|
28
|
+
if salt is None:
|
|
29
|
+
salt = secrets.token_bytes(16) # Generate a 16-byte salt
|
|
30
|
+
|
|
31
|
+
hashed_password = hashlib.scrypt(
|
|
32
|
+
password.encode('utf-8'),
|
|
33
|
+
salt=salt,
|
|
34
|
+
n=2**14, # CPU/memory cost parameter
|
|
35
|
+
r=8, # Block size parameter
|
|
36
|
+
p=1, # Parallelization parameter
|
|
37
|
+
dklen=64 # Desired key length
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return salt.hex(), hashed_password.hex()
|
|
41
|
+
except Exception as e:
|
|
42
|
+
print(f"Error in secure_password_hashing: {e}")
|
|
43
|
+
return None, None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def verify_password(password: str, salt_hex: str, hash_hex: str) -> bool:
|
|
47
|
+
"""
|
|
48
|
+
Verifies a password against a stored hash and salt.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
password: The password to verify.
|
|
52
|
+
salt_hex: The salt used to hash the password (as a hex string).
|
|
53
|
+
hash_hex: The stored hash of the password (as a hex string).
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
True if the password matches the stored hash, False otherwise.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
salt = bytes.fromhex(salt_hex)
|
|
60
|
+
stored_hash = bytes.fromhex(hash_hex)
|
|
61
|
+
|
|
62
|
+
hashed_password = hashlib.scrypt(
|
|
63
|
+
password.encode('utf-8'),
|
|
64
|
+
salt=salt,
|
|
65
|
+
n=2**14, # CPU/memory cost parameter
|
|
66
|
+
r=8, # Block size parameter
|
|
67
|
+
p=1, # Parallelization parameter
|
|
68
|
+
dklen=64 # Desired key length
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return hmac.compare_digest(hashed_password, stored_hash)
|
|
72
|
+
except ValueError as ve:
|
|
73
|
+
print(f"ValueError in verify_password (likely invalid hex): {ve}")
|
|
74
|
+
return False
|
|
75
|
+
except Exception as e:
|
|
76
|
+
print(f"Error in verify_password: {e}")
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def sanitize_input(input_string: str) -> str:
|
|
81
|
+
"""
|
|
82
|
+
Sanitizes user input to prevent common injection vulnerabilities.
|
|
83
|
+
|
|
84
|
+
This function removes or escapes characters that could be used in SQL injection,
|
|
85
|
+
cross-site scripting (XSS), or other injection attacks.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
input_string: The string to sanitize.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
The sanitized string.
|
|
92
|
+
"""
|
|
93
|
+
try:
|
|
94
|
+
# Example: Escape HTML entities
|
|
95
|
+
sanitized_string = input_string.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """).replace("'", "'")
|
|
96
|
+
|
|
97
|
+
# Example: Remove potentially dangerous characters (e.g., for SQL injection)
|
|
98
|
+
sanitized_string = re.sub(r"[;'\"]", "", sanitized_string)
|
|
99
|
+
|
|
100
|
+
return sanitized_string
|
|
101
|
+
except Exception as e:
|
|
102
|
+
print(f"Error in sanitize_input: {e}")
|
|
103
|
+
return ""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def validate_email(email: str) -> bool:
|
|
107
|
+
"""
|
|
108
|
+
Validates an email address using a regular expression.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
email: The email address to validate.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
True if the email address is valid, False otherwise.
|
|
115
|
+
"""
|
|
116
|
+
try:
|
|
117
|
+
# A more robust email regex can be used
|
|
118
|
+
email_regex = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
|
|
119
|
+
return re.match(email_regex, email) is not None
|
|
120
|
+
except Exception as e:
|
|
121
|
+
print(f"Error in validate_email: {e}")
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def secure_file_upload(filename: str, file_content: bytes, upload_dir: str) -> str:
|
|
126
|
+
"""
|
|
127
|
+
Handles secure file uploads, preventing common vulnerabilities like path traversal.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
filename: The original filename of the uploaded file.
|
|
131
|
+
file_content: The content of the uploaded file as bytes.
|
|
132
|
+
upload_dir: The directory to store the uploaded files.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
The path to the saved file, or None on error.
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
# Sanitize filename to prevent path traversal attacks
|
|
139
|
+
sanitized_filename = os.path.basename(filename) # Remove directory components
|
|
140
|
+
sanitized_filename = re.sub(r"[^a-zA-Z0-9._-]", "", sanitized_filename) # Remove invalid characters
|
|
141
|
+
|
|
142
|
+
if not sanitized_filename:
|
|
143
|
+
print("Invalid filename.")
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
filepath = os.path.join(upload_dir, sanitized_filename)
|
|
147
|
+
|
|
148
|
+
# Ensure the upload directory exists
|
|
149
|
+
os.makedirs(upload_dir, exist_ok=True)
|
|
150
|
+
|
|
151
|
+
# Write the file content
|
|
152
|
+
with open(filepath, "wb") as f:
|
|
153
|
+
f.write(file_content)
|
|
154
|
+
|
|
155
|
+
return filepath
|
|
156
|
+
except OSError as ose:
|
|
157
|
+
print(f"OSError in secure_file_upload: {ose}")
|
|
158
|
+
return None
|
|
159
|
+
except Exception as e:
|
|
160
|
+
print(f"Error in secure_file_upload: {e}")
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
def generate_secure_random_token(length: int = 32) -> str:
|
|
164
|
+
"""
|
|
165
|
+
Generates a cryptographically secure random token.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
length: The length of the token in bytes.
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
A hex-encoded string representing the random token.
|
|
172
|
+
"""
|
|
173
|
+
try:
|
|
174
|
+
return secrets.token_hex(length)
|
|
175
|
+
except Exception as e:
|
|
176
|
+
print(f"Error in generate_secure_random_token: {e}")
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
if __name__ == "__main__":
|
|
180
|
+
# Example usage
|
|
181
|
+
password = "my_secret_password"
|
|
182
|
+
|
|
183
|
+
# Secure password hashing
|
|
184
|
+
salt, password_hash = secure_password_hashing(password)
|
|
185
|
+
if salt and password_hash:
|
|
186
|
+
print(f"Salt: {salt}")
|
|
187
|
+
print(f"Password Hash: {password_hash}")
|
|
188
|
+
|
|
189
|
+
# Verify password
|
|
190
|
+
is_valid = verify_password(password, salt, password_hash)
|
|
191
|
+
print(f"Password is valid: {is_valid}")
|
|
192
|
+
|
|
193
|
+
is_invalid = verify_password("wrong_password", salt, password_hash)
|
|
194
|
+
print(f"Wrong password is valid: {is_invalid}")
|
|
195
|
+
else:
|
|
196
|
+
print("Password hashing failed.")
|
|
197
|
+
|
|
198
|
+
# Input sanitization
|
|
199
|
+
user_input = "<script>alert('XSS');</script>"
|
|
200
|
+
sanitized_input = sanitize_input(user_input)
|
|
201
|
+
print(f"Original input: {user_input}")
|
|
202
|
+
print(f"Sanitized input: {sanitized_input}")
|
|
203
|
+
|
|
204
|
+
# Email validation
|
|
205
|
+
email = "test@example.com"
|
|
206
|
+
is_valid_email = validate_email(email)
|
|
207
|
+
print(f"Email '{email}' is valid: {is_valid_email}")
|
|
208
|
+
|
|
209
|
+
invalid_email = "invalid-email"
|
|
210
|
+
is_valid_invalid_email = validate_email(invalid_email)
|
|
211
|
+
print(f"Email '{invalid_email}' is valid: {is_valid_invalid_email}")
|
|
212
|
+
|
|
213
|
+
# Secure file upload (example)
|
|
214
|
+
filename = "important.txt"
|
|
215
|
+
file_content = b"This is some sensitive data."
|
|
216
|
+
upload_dir = "uploads"
|
|
217
|
+
filepath = secure_file_upload(filename, file_content, upload_dir)
|
|
218
|
+
if filepath:
|
|
219
|
+
print(f"File uploaded to: {filepath}")
|
|
220
|
+
else:
|
|
221
|
+
print("File upload failed.")
|
|
222
|
+
|
|
223
|
+
# Generate secure random token
|
|
224
|
+
token = generate_secure_random_token()
|
|
225
|
+
print(f"Secure random token: {token}")
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Example code snippets demonstrating common vulnerabilities.
|
|
5
|
+
|
|
6
|
+
This module provides examples of vulnerable code that can be used for
|
|
7
|
+
security testing and education. It includes examples of:
|
|
8
|
+
|
|
9
|
+
- SQL Injection
|
|
10
|
+
- Cross-Site Scripting (XSS)
|
|
11
|
+
- Path Traversal
|
|
12
|
+
- Command Injection
|
|
13
|
+
- Buffer Overflow (simulated in Python)
|
|
14
|
+
- Insecure Deserialization
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import subprocess
|
|
19
|
+
import pickle
|
|
20
|
+
import base64
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
def sql_injection_example(user_input):
|
|
24
|
+
"""
|
|
25
|
+
Demonstrates a simple SQL injection vulnerability.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
user_input (str): A string that could be malicious.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
str: A dummy SQL query string.
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
query = "SELECT * FROM users WHERE username = '" + user_input + "'"
|
|
35
|
+
# In a real application, this query would be executed against a database.
|
|
36
|
+
print(f"Generated query: {query}") # For demonstration purposes only
|
|
37
|
+
return query
|
|
38
|
+
except Exception as e:
|
|
39
|
+
print(f"Error in sql_injection_example: {e}")
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def xss_example(user_input):
|
|
44
|
+
"""
|
|
45
|
+
Demonstrates a simple XSS vulnerability.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
user_input (str): A string that could contain malicious JavaScript.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
str: The potentially vulnerable HTML output.
|
|
52
|
+
"""
|
|
53
|
+
try:
|
|
54
|
+
output = "<h1>Welcome, " + user_input + "!</h1>"
|
|
55
|
+
# In a real application, this output would be rendered in a web page.
|
|
56
|
+
print(f"Generated HTML: {output}") # For demonstration purposes only
|
|
57
|
+
return output
|
|
58
|
+
except Exception as e:
|
|
59
|
+
print(f"Error in xss_example: {e}")
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def path_traversal_example(filename):
|
|
64
|
+
"""
|
|
65
|
+
Demonstrates a path traversal vulnerability.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
filename (str): A filename provided by the user.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
str: The contents of the file (if accessible). Returns None on error.
|
|
72
|
+
"""
|
|
73
|
+
try:
|
|
74
|
+
# Vulnerable to path traversal: user can use "../" to access other files.
|
|
75
|
+
filepath = os.path.join("data", filename)
|
|
76
|
+
with open(filepath, "r") as f:
|
|
77
|
+
content = f.read()
|
|
78
|
+
print(f"File content (if accessible): {content}")
|
|
79
|
+
return content
|
|
80
|
+
except FileNotFoundError:
|
|
81
|
+
print(f"File not found: {filename}")
|
|
82
|
+
return None
|
|
83
|
+
except Exception as e:
|
|
84
|
+
print(f"Error in path_traversal_example: {e}")
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def command_injection_example(user_input):
|
|
89
|
+
"""
|
|
90
|
+
Demonstrates a command injection vulnerability.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
user_input (str): A string that could contain malicious commands.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
str: The output of the executed command (if any). Returns None on error.
|
|
97
|
+
"""
|
|
98
|
+
try:
|
|
99
|
+
# Vulnerable to command injection: user can inject shell commands.
|
|
100
|
+
command = "echo " + user_input
|
|
101
|
+
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
|
102
|
+
output = result.stdout
|
|
103
|
+
print(f"Command output: {output}")
|
|
104
|
+
return output
|
|
105
|
+
except Exception as e:
|
|
106
|
+
print(f"Error in command_injection_example: {e}")
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def buffer_overflow_example(data, buffer_size):
|
|
111
|
+
"""
|
|
112
|
+
Simulates a buffer overflow vulnerability in Python.
|
|
113
|
+
|
|
114
|
+
Python is generally memory-safe, so this is a simplified simulation.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
data (str): The data to write to the buffer.
|
|
118
|
+
buffer_size (int): The size of the buffer.
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
buffer = bytearray(buffer_size)
|
|
122
|
+
if len(data.encode('utf-8')) > buffer_size:
|
|
123
|
+
print("Simulating Buffer Overflow: Data exceeds buffer size.")
|
|
124
|
+
# Normally this would overwrite adjacent memory, but in Python,
|
|
125
|
+
# this will raise an IndexError. We avoid the error by truncating.
|
|
126
|
+
buffer[:] = data.encode('utf-8')[:buffer_size] # Truncate to buffer size
|
|
127
|
+
else:
|
|
128
|
+
buffer[:] = data.encode('utf-8')
|
|
129
|
+
print(f"Buffer content: {buffer.decode('utf-8', 'ignore')}")
|
|
130
|
+
except Exception as e:
|
|
131
|
+
print(f"Error in buffer_overflow_example: {e}")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def insecure_deserialization_example(serialized_data):
|
|
135
|
+
"""
|
|
136
|
+
Demonstrates an insecure deserialization vulnerability using pickle.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
serialized_data (str): A base64 encoded pickled object.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The deserialized object, or None if an error occurs.
|
|
143
|
+
"""
|
|
144
|
+
try:
|
|
145
|
+
# Deserialize the data (potentially dangerous if the data is untrusted)
|
|
146
|
+
decoded_data = base64.b64decode(serialized_data)
|
|
147
|
+
obj = pickle.loads(decoded_data)
|
|
148
|
+
print(f"Deserialized object: {obj}")
|
|
149
|
+
return obj
|
|
150
|
+
except Exception as e:
|
|
151
|
+
print(f"Error in insecure_deserialization_example: {e}")
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
print("Example Vulnerable Code Snippets:")
|
|
157
|
+
|
|
158
|
+
print("\nSQL Injection Example:")
|
|
159
|
+
sql_injection_example("'; DROP TABLE users; --")
|
|
160
|
+
|
|
161
|
+
print("\nXSS Example:")
|
|
162
|
+
xss_example("<script>alert('XSS Vulnerability!')</script>")
|
|
163
|
+
|
|
164
|
+
print("\nPath Traversal Example:")
|
|
165
|
+
# Create a dummy file for the path traversal example.
|
|
166
|
+
if not os.path.exists("data"):
|
|
167
|
+
os.makedirs("data")
|
|
168
|
+
with open("data/test.txt", "w") as f:
|
|
169
|
+
f.write("This is a test file.")
|
|
170
|
+
|
|
171
|
+
path_traversal_example("../example_code_vulnerable.py") # Attempt to access this file
|
|
172
|
+
|
|
173
|
+
print("\nCommand Injection Example:")
|
|
174
|
+
command_injection_example("&& ls -l")
|
|
175
|
+
|
|
176
|
+
print("\nBuffer Overflow Example:")
|
|
177
|
+
buffer_overflow_example("A" * 100, 10)
|
|
178
|
+
|
|
179
|
+
print("\nInsecure Deserialization Example:")
|
|
180
|
+
# Create a malicious object and serialize it.
|
|
181
|
+
class MaliciousClass:
|
|
182
|
+
def __reduce__(self):
|
|
183
|
+
return (os.system, ("rm -rf /",)) # DANGEROUS: Never do this in real code!
|
|
184
|
+
|
|
185
|
+
malicious_object = MaliciousClass()
|
|
186
|
+
serialized_data = base64.b64encode(pickle.dumps(malicious_object)).decode('utf-8')
|
|
187
|
+
print(f"Serialized data: {serialized_data}")
|
|
188
|
+
# WARNING: Deserializing this will execute the 'rm -rf /' command (if permitted)
|
|
189
|
+
# This line is commented out for safety. UNCOMMENT AT YOUR OWN RISK AND ONLY IN A SAFE ENVIRONMENT.
|
|
190
|
+
# insecure_deserialization_example(serialized_data)
|
|
191
|
+
|
|
192
|
+
print("\nNote: Some examples are commented out for safety. Exercise caution when running these examples.")
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Security Review Report
|
|
2
|
+
|
|
3
|
+
**Date:** [Date of Review]
|
|
4
|
+
**Project:** [Project Name]
|
|
5
|
+
**Reviewer:** [Reviewer Name/Security Agent]
|
|
6
|
+
|
|
7
|
+
## Executive Summary
|
|
8
|
+
|
|
9
|
+
[Briefly summarize the overall security posture of the reviewed code. Highlight the most critical findings and recommendations.]
|
|
10
|
+
|
|
11
|
+
## Scope of Review
|
|
12
|
+
|
|
13
|
+
[Clearly define the scope of the review, including the specific files, modules, or components that were analyzed. Example: "This review covers the authentication module located in `/src/auth/` and the user profile management API endpoints."]
|
|
14
|
+
|
|
15
|
+
## Methodology
|
|
16
|
+
|
|
17
|
+
[Describe the methods used for the security review. Example: "The review involved static code analysis, manual code inspection, and dynamic testing with sample payloads."]
|
|
18
|
+
|
|
19
|
+
## Findings
|
|
20
|
+
|
|
21
|
+
### Critical Vulnerabilities
|
|
22
|
+
|
|
23
|
+
[List any critical vulnerabilities identified. Critical vulnerabilities pose an immediate and significant risk to the application and its users.]
|
|
24
|
+
|
|
25
|
+
**Vulnerability ID:** CRIT-001
|
|
26
|
+
**Description:** [Detailed description of the vulnerability, including its potential impact. Example: "SQL injection vulnerability in the user search functionality. An attacker can inject arbitrary SQL code via the `searchTerm` parameter, potentially leading to data leakage or modification."]
|
|
27
|
+
**Severity:** Critical
|
|
28
|
+
**Affected Component:** `/src/api/user_search.php`
|
|
29
|
+
**Proof of Concept:** [Provide a proof of concept demonstrating the vulnerability. Example: `curl -X GET "https://example.com/api/user_search.php?searchTerm='; DROP TABLE users; --"`]
|
|
30
|
+
**Recommendation:** [Provide specific and actionable recommendations for remediation. Example: "Implement parameterized queries or prepared statements to prevent SQL injection."]
|
|
31
|
+
|
|
32
|
+
### High Vulnerabilities
|
|
33
|
+
|
|
34
|
+
[List any high vulnerabilities identified. High vulnerabilities can lead to significant security breaches if exploited.]
|
|
35
|
+
|
|
36
|
+
**Vulnerability ID:** HIGH-002
|
|
37
|
+
**Description:** [Detailed description of the vulnerability, including its potential impact. Example: "Cross-site scripting (XSS) vulnerability in the user profile display. User-supplied input is not properly sanitized before being displayed, allowing an attacker to inject malicious JavaScript code."]
|
|
38
|
+
**Severity:** High
|
|
39
|
+
**Affected Component:** `/src/profile/display.php`
|
|
40
|
+
**Proof of Concept:** [Provide a proof of concept demonstrating the vulnerability. Example: `<script>alert('XSS')</script>` inserted into the user's profile name.]
|
|
41
|
+
**Recommendation:** [Provide specific and actionable recommendations for remediation. Example: "Implement proper output encoding using a library like OWASP Java Encoder or similar for your language."]
|
|
42
|
+
|
|
43
|
+
### Medium Vulnerabilities
|
|
44
|
+
|
|
45
|
+
[List any medium vulnerabilities identified. Medium vulnerabilities may not be directly exploitable but could be chained with other vulnerabilities or lead to privilege escalation.]
|
|
46
|
+
|
|
47
|
+
**Vulnerability ID:** MED-003
|
|
48
|
+
**Description:** [Detailed description of the vulnerability, including its potential impact. Example: "Insecure direct object reference (IDOR) vulnerability in the password reset functionality. An attacker can potentially reset the password of another user by manipulating the user ID in the password reset request."]
|
|
49
|
+
**Severity:** Medium
|
|
50
|
+
**Affected Component:** `/src/password_reset/reset.php`
|
|
51
|
+
**Proof of Concept:** [Provide a proof of concept demonstrating the vulnerability. Example: Changing the `userId` parameter in the password reset URL to another user's ID.]
|
|
52
|
+
**Recommendation:** [Provide specific and actionable recommendations for remediation. Example: "Implement proper authorization checks to ensure that users can only reset their own passwords. Use a random, non-predictable token for password reset links."]
|
|
53
|
+
|
|
54
|
+
### Low Vulnerabilities
|
|
55
|
+
|
|
56
|
+
[List any low vulnerabilities identified. Low vulnerabilities are typically minor issues that do not pose a significant risk but should still be addressed for best security practices.]
|
|
57
|
+
|
|
58
|
+
**Vulnerability ID:** LOW-004
|
|
59
|
+
**Description:** [Detailed description of the vulnerability, including its potential impact. Example: "Missing HTTP Strict Transport Security (HSTS) header. This can allow man-in-the-middle attacks to downgrade the connection to HTTP."]
|
|
60
|
+
**Severity:** Low
|
|
61
|
+
**Affected Component:** Web Server Configuration
|
|
62
|
+
**Proof of Concept:** [Provide a proof of concept demonstrating the vulnerability. Example: Checking the HTTP response headers with a tool like `curl -I` and observing the absence of the `Strict-Transport-Security` header.]
|
|
63
|
+
**Recommendation:** [Provide specific and actionable recommendations for remediation. Example: "Configure the web server to send the HSTS header with a long max-age and includeSubDomains directive."]
|
|
64
|
+
|
|
65
|
+
## General Recommendations
|
|
66
|
+
|
|
67
|
+
[Provide general recommendations for improving the overall security of the application. Examples:
|
|
68
|
+
* Implement a comprehensive security testing strategy.
|
|
69
|
+
* Keep all software and dependencies up to date.
|
|
70
|
+
* Follow secure coding practices.]
|
|
71
|
+
|
|
72
|
+
## Conclusion
|
|
73
|
+
|
|
74
|
+
[Summarize the key findings and recommendations. Emphasize the importance of addressing the identified vulnerabilities to protect the application and its users.]
|
|
75
|
+
|
|
76
|
+
**Disclaimer:** This security review is based on the information available at the time of the review. New vulnerabilities may be discovered in the future. It is important to continuously monitor and improve the security of the application.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Scripts
|
|
2
|
+
|
|
3
|
+
Bundled resources for security-agent skill
|
|
4
|
+
|
|
5
|
+
- [ ] code_analyzer.py: Analyzes code snippets for common vulnerabilities (SQL injection, XSS, etc.) and generates a report.
|
|
6
|
+
- [ ] dependency_checker.py: Checks project dependencies for known security vulnerabilities using tools like `safety` or `pip audit`.
|
|
7
|
+
- [ ] report_formatter.py: Formats the security review findings into a structured report (e.g., JSON, Markdown) for easy consumption.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
security-agent - Analysis Script
|
|
4
|
+
Analyzes code snippets for common vulnerabilities (SQL injection, XSS, etc.) and generates a report.
|
|
5
|
+
Generated: 2025-12-10 03:48:17
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import json
|
|
10
|
+
import argparse
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Dict, List
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
class Analyzer:
|
|
16
|
+
def __init__(self, target_path: str):
|
|
17
|
+
self.target_path = Path(target_path)
|
|
18
|
+
self.stats = {
|
|
19
|
+
'total_files': 0,
|
|
20
|
+
'total_size': 0,
|
|
21
|
+
'file_types': {},
|
|
22
|
+
'issues': [],
|
|
23
|
+
'recommendations': []
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
def analyze_directory(self) -> Dict:
|
|
27
|
+
"""Analyze directory structure and contents."""
|
|
28
|
+
if not self.target_path.exists():
|
|
29
|
+
self.stats['issues'].append(f"Path does not exist: {self.target_path}")
|
|
30
|
+
return self.stats
|
|
31
|
+
|
|
32
|
+
for file_path in self.target_path.rglob('*'):
|
|
33
|
+
if file_path.is_file():
|
|
34
|
+
self.analyze_file(file_path)
|
|
35
|
+
|
|
36
|
+
return self.stats
|
|
37
|
+
|
|
38
|
+
def analyze_file(self, file_path: Path):
|
|
39
|
+
"""Analyze individual file."""
|
|
40
|
+
self.stats['total_files'] += 1
|
|
41
|
+
self.stats['total_size'] += file_path.stat().st_size
|
|
42
|
+
|
|
43
|
+
# Track file types
|
|
44
|
+
ext = file_path.suffix.lower()
|
|
45
|
+
if ext:
|
|
46
|
+
self.stats['file_types'][ext] = self.stats['file_types'].get(ext, 0) + 1
|
|
47
|
+
|
|
48
|
+
# Check for potential issues
|
|
49
|
+
if file_path.stat().st_size > 100 * 1024 * 1024: # 100MB
|
|
50
|
+
self.stats['issues'].append(f"Large file: {file_path} ({file_path.stat().st_size // 1024 // 1024}MB)")
|
|
51
|
+
|
|
52
|
+
if file_path.stat().st_size == 0:
|
|
53
|
+
self.stats['issues'].append(f"Empty file: {file_path}")
|
|
54
|
+
|
|
55
|
+
def generate_recommendations(self):
|
|
56
|
+
"""Generate recommendations based on analysis."""
|
|
57
|
+
if self.stats['total_files'] == 0:
|
|
58
|
+
self.stats['recommendations'].append("No files found - check target path")
|
|
59
|
+
|
|
60
|
+
if len(self.stats['file_types']) > 20:
|
|
61
|
+
self.stats['recommendations'].append("Many file types detected - consider organizing")
|
|
62
|
+
|
|
63
|
+
if self.stats['total_size'] > 1024 * 1024 * 1024: # 1GB
|
|
64
|
+
self.stats['recommendations'].append("Large total size - consider archiving old data")
|
|
65
|
+
|
|
66
|
+
def generate_report(self) -> str:
|
|
67
|
+
"""Generate analysis report."""
|
|
68
|
+
report = []
|
|
69
|
+
report.append("\n" + "="*60)
|
|
70
|
+
report.append(f"ANALYSIS REPORT - security-agent")
|
|
71
|
+
report.append("="*60)
|
|
72
|
+
report.append(f"Target: {self.target_path}")
|
|
73
|
+
report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
74
|
+
report.append("")
|
|
75
|
+
|
|
76
|
+
# Statistics
|
|
77
|
+
report.append("š STATISTICS")
|
|
78
|
+
report.append(f" Total Files: {self.stats['total_files']:,}")
|
|
79
|
+
report.append(f" Total Size: {self.stats['total_size'] / 1024 / 1024:.2f} MB")
|
|
80
|
+
report.append(f" File Types: {len(self.stats['file_types'])}")
|
|
81
|
+
|
|
82
|
+
# Top file types
|
|
83
|
+
if self.stats['file_types']:
|
|
84
|
+
report.append("\nš TOP FILE TYPES")
|
|
85
|
+
sorted_types = sorted(self.stats['file_types'].items(), key=lambda x: x[1], reverse=True)[:5]
|
|
86
|
+
for ext, count in sorted_types:
|
|
87
|
+
report.append(f" {ext or 'no extension'}: {count} files")
|
|
88
|
+
|
|
89
|
+
# Issues
|
|
90
|
+
if self.stats['issues']:
|
|
91
|
+
report.append(f"\nā ļø ISSUES ({len(self.stats['issues'])})")
|
|
92
|
+
for issue in self.stats['issues'][:10]:
|
|
93
|
+
report.append(f" - {issue}")
|
|
94
|
+
if len(self.stats['issues']) > 10:
|
|
95
|
+
report.append(f" ... and {len(self.stats['issues']) - 10} more")
|
|
96
|
+
|
|
97
|
+
# Recommendations
|
|
98
|
+
if self.stats['recommendations']:
|
|
99
|
+
report.append("\nš” RECOMMENDATIONS")
|
|
100
|
+
for rec in self.stats['recommendations']:
|
|
101
|
+
report.append(f" - {rec}")
|
|
102
|
+
|
|
103
|
+
report.append("")
|
|
104
|
+
return "\n".join(report)
|
|
105
|
+
|
|
106
|
+
def main():
|
|
107
|
+
parser = argparse.ArgumentParser(description="Analyzes code snippets for common vulnerabilities (SQL injection, XSS, etc.) and generates a report.")
|
|
108
|
+
parser.add_argument('target', help='Target directory to analyze')
|
|
109
|
+
parser.add_argument('--output', '-o', help='Output report file')
|
|
110
|
+
parser.add_argument('--json', action='store_true', help='Output as JSON')
|
|
111
|
+
|
|
112
|
+
args = parser.parse_args()
|
|
113
|
+
|
|
114
|
+
print(f"š Analyzing {args.target}...")
|
|
115
|
+
analyzer = Analyzer(args.target)
|
|
116
|
+
stats = analyzer.analyze_directory()
|
|
117
|
+
analyzer.generate_recommendations()
|
|
118
|
+
|
|
119
|
+
if args.json:
|
|
120
|
+
output = json.dumps(stats, indent=2)
|
|
121
|
+
else:
|
|
122
|
+
output = analyzer.generate_report()
|
|
123
|
+
|
|
124
|
+
if args.output:
|
|
125
|
+
Path(args.output).write_text(output)
|
|
126
|
+
print(f"ā Report saved to {args.output}")
|
|
127
|
+
else:
|
|
128
|
+
print(output)
|
|
129
|
+
|
|
130
|
+
return 0 if len(stats['issues']) == 0 else 1
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
import sys
|
|
134
|
+
sys.exit(main())
|