feat: add skill-security-auditor as default example skill (#1479)
Some checks failed
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 4s
CodeQL Advanced / Analyze (actions) (push) Failing after 4s
CodeQL Advanced / Analyze (python) (push) Failing after 3s
Test / Run Python Tests (push) Failing after 30s
Pre-commit / pre-commit (push) Failing after 36s

Co-authored-by: Tao Sun <168447269+fengju0213@users.noreply.github.com>
This commit is contained in:
statxc 2026-03-18 12:43:12 +02:00 committed by GitHub
parent 14139d7e19
commit 31828e68b8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 1409 additions and 0 deletions

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025-2026 Eigent.ai
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,218 @@
---
name: skill-security-auditor
description: "Security auditing for code, configs, and infrastructure. Use when the user wants to audit or improve security: scan for vulnerabilities (SQL injection, XSS, command injection, path traversal), detect hardcoded secrets and credentials, review auth and authorization, check dependencies for known CVEs, audit config files for insecure defaults, or generate security reports. Trigger on \"security audit\", \"vulnerability scan\", \"code review for security\", \"find secrets\", \"check for vulnerabilities\", \"OWASP\", \"CVE\", or questions about code security."
license: Complete terms in LICENSE.txt
---
# Security Auditor Guide
## Overview
This guide covers security auditing workflows for source code, dependencies, and configurations. For detailed vulnerability patterns and detection rules, see references/vulnerability-patterns.md. For secrets detection patterns, see references/secrets-patterns.md.
## Quick Start
Run the bundled scan script against a project directory:
```bash
python scripts/scan_project.py /path/to/project
```
This performs a lightweight scan for common issues: hardcoded secrets, dangerous function calls, and insecure patterns. For deeper analysis, follow the workflows below.
### Testing the scripts
```bash
python scripts/scan_project.py /path/to/some/project --format text
python scripts/scan_secrets.py /path/to/some/project --format text
```
## Audit Workflow
### 1. Reconnaissance
Before auditing, understand the project:
```bash
# Identify languages, frameworks, and entry points
find . -type f -name "*.py" -o -name "*.js" -o -name "*.ts" -o -name "*.go" -o -name "*.java" | head -20
cat package.json pyproject.toml requirements.txt go.mod pom.xml 2>/dev/null
```
Key questions:
- What frameworks are used? (Express, Django, Flask, Spring, etc.)
- Where are the entry points? (routes, controllers, API handlers)
- How is authentication handled?
- What external services are called?
- Is user input accepted? Where?
### 2. Secrets Detection
Scan for hardcoded credentials, API keys, and tokens. See references/secrets-patterns.md for the full pattern list.
```bash
python scripts/scan_secrets.py /path/to/project
```
Common patterns to check:
- API keys and tokens in source files
- Database connection strings with embedded passwords
- Private keys or certificates committed to the repo
- `.env` files or config files with plaintext secrets
- Secrets in CI/CD configuration files
### 3. Vulnerability Scanning
#### OWASP Top 10 Checklist
| # | Category | What to Look For |
|---|----------|-----------------|
| A01 | Broken Access Control | Missing auth checks, IDOR, privilege escalation |
| A02 | Cryptographic Failures | Weak algorithms, plaintext storage, missing TLS |
| A03 | Injection | SQL, NoSQL, OS command, LDAP, XSS |
| A04 | Insecure Design | Missing rate limits, business logic flaws |
| A05 | Security Misconfiguration | Debug mode, default credentials, verbose errors |
| A06 | Vulnerable Components | Outdated dependencies with known CVEs |
| A07 | Auth Failures | Weak passwords, missing MFA, session issues |
| A08 | Data Integrity Failures | Insecure deserialization, unsigned updates |
| A09 | Logging Failures | Missing audit logs, sensitive data in logs |
| A10 | SSRF | Unvalidated URLs in server-side requests |
#### Language-Specific Checks
**Python**
```python
# Dangerous: SQL injection
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
# Safe: Parameterized query
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# Dangerous: Command injection
os.system(f"ping {hostname}")
# Safe: Use subprocess with list args
subprocess.run(["ping", hostname], capture_output=True)
# Dangerous: Path traversal
open(f"/data/{user_input}")
# Safe: Validate and resolve path
path = pathlib.Path("/data") / user_input
path.resolve().relative_to(pathlib.Path("/data").resolve())
```
**JavaScript/TypeScript**
```javascript
// Dangerous: XSS via innerHTML
element.innerHTML = userInput;
// Safe: Use textContent or sanitize
element.textContent = userInput;
// Dangerous: Prototype pollution
Object.assign(target, JSON.parse(userInput));
// Safe: Validate input structure
const parsed = JSON.parse(userInput);
if (typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error();
const sanitized = Object.fromEntries(
Object.entries(parsed).filter(([k]) => !k.startsWith('__'))
);
// Dangerous: eval or Function constructor
eval(userInput);
// Safe: Never use eval with user input
```
**Go**
```go
// Dangerous: SQL injection
db.Query("SELECT * FROM users WHERE id = " + id)
// Safe: Parameterized query
db.Query("SELECT * FROM users WHERE id = $1", id)
// Dangerous: Path traversal
http.ServeFile(w, r, filepath.Join(baseDir, r.URL.Path))
// Safe: Clean and validate path
cleaned := filepath.Clean(r.URL.Path)
full := filepath.Join(baseDir, cleaned)
if !strings.HasPrefix(full, baseDir) { http.Error(...) }
```
### 4. Dependency Audit
Check for known vulnerabilities in project dependencies:
```bash
# Python
pip audit
safety check -r requirements.txt
# Node.js
npm audit
npx auditjs ossi
# Go
govulncheck ./...
# General (if Trivy is available)
trivy fs --scanners vuln /path/to/project
```
Review the output and categorize by severity (critical, high, medium, low). Critical and high severity findings should be addressed before deployment.
### 5. Configuration Review
Check for insecure defaults in configuration files:
```yaml
# Common misconfigurations to flag:
DEBUG: true # Debug mode in production
ALLOWED_HOSTS: ["*"] # Unrestricted host access
CORS_ALLOW_ALL_ORIGINS: true # Open CORS policy
SECRET_KEY: "default" # Default or weak secret key
SSL_VERIFY: false # Disabled TLS verification
```
Check infrastructure configs:
- Dockerfiles: Running as root, exposing unnecessary ports
- CI/CD: Secrets in plaintext, overly permissive permissions
- Cloud configs: Public S3 buckets, open security groups
### 6. Authentication and Authorization Review
Key areas to verify:
- Password hashing uses strong algorithms (bcrypt, argon2, scrypt)
- Sessions have appropriate timeouts and rotation
- JWT tokens are validated properly (algorithm, expiry, signature)
- API endpoints enforce authorization checks
- Role-based access control is consistently applied
- Rate limiting is in place for login and sensitive endpoints
## Report Format
When generating a security audit report, use this structure:
```markdown
# Security Audit Report
## Summary
- **Project**: [name]
- **Date**: [date]
- **Scope**: [what was audited]
- **Risk Level**: [Critical/High/Medium/Low]
## Findings
### [SEVERITY] Finding Title
- **Category**: [OWASP category]
- **Location**: [file:line]
- **Description**: [what the issue is]
- **Impact**: [what could happen if exploited]
- **Recommendation**: [how to fix]
## Statistics
- Total findings: [count]
- Critical: [count] | High: [count] | Medium: [count] | Low: [count]
```
## Next Steps
- For detailed vulnerability patterns and code examples, see references/vulnerability-patterns.md
- For secrets detection regex patterns, see references/secrets-patterns.md

View file

@ -0,0 +1,152 @@
# Secrets Detection Patterns
Regex patterns and rules for detecting hardcoded secrets, credentials, and sensitive data in source code.
## Table of Contents
- [API Keys and Tokens](#api-keys-and-tokens)
- [Cloud Provider Credentials](#cloud-provider-credentials)
- [Database Connection Strings](#database-connection-strings)
- [Private Keys and Certificates](#private-keys-and-certificates)
- [Generic Patterns](#generic-patterns)
- [Files to Always Check](#files-to-always-check)
- [False Positive Reduction](#false-positive-reduction)
## API Keys and Tokens
| Service | Pattern | Example |
|---------|---------|---------|
| AWS Access Key | `AKIA[0-9A-Z]{16}` | AKIAIOSFODNN7EXAMPLE |
| AWS Secret Key | `(?i)aws_secret_access_key\s*=\s*\S{40}` | |
| GitHub Token | `gh[ps]_[A-Za-z0-9_]{36,}` | ghp_xxxxxxxxxxxx |
| GitHub Fine-grained | `github_pat_[A-Za-z0-9_]{22,}` | |
| GitLab Token | `glpat-[A-Za-z0-9\-]{20,}` | |
| Slack Token | `xox[baprs]-[A-Za-z0-9\-]{10,}` | |
| Slack Webhook | `https://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+` | |
| Stripe Secret | `sk_live_[A-Za-z0-9]{24,}` | |
| Stripe Publishable | `pk_live_[A-Za-z0-9]{24,}` | |
| Twilio | `SK[0-9a-fA-F]{32}` | |
| SendGrid | `SG\.[A-Za-z0-9\-_]{22}\.[A-Za-z0-9\-_]{43}` | |
| Mailgun | `key-[0-9a-zA-Z]{32}` | |
| Google API Key | `AIza[0-9A-Za-z\-_]{35}` | |
| Google OAuth | `[0-9]+-[0-9A-Za-z_]{32}\.apps\.googleusercontent\.com` | |
| Heroku API Key | `[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}` | |
| npm Token | `npm_[A-Za-z0-9]{36}` | |
| PyPI Token | `pypi-[A-Za-z0-9\-_]{50,}` | |
## Cloud Provider Credentials
### AWS
```
# Access Key ID
AKIA[0-9A-Z]{16}
# Secret Access Key (in config context)
(?i)(aws_secret_access_key|aws_secret_key)\s*[=:]\s*[A-Za-z0-9/+=]{40}
# Session Token
(?i)aws_session_token\s*[=:]\s*\S+
```
### GCP
```
# Service account key file indicators
"type"\s*:\s*"service_account"
"private_key"\s*:\s*"-----BEGIN
# OAuth client secret
(?i)client_secret\s*[=:]\s*\S+
```
### Azure
```
# Storage account key
(?i)(AccountKey|account_key)\s*[=:]\s*[A-Za-z0-9+/=]{86,}
# Connection strings
(?i)(DefaultEndpointsProtocol|AccountName|AccountKey)=[^;\s]+
```
## Database Connection Strings
```
# Generic with embedded password
(?i)(mysql|postgres|postgresql|mongodb|redis|mssql|sqlserver)://[^:]+:[^@]+@
# Django DATABASE_URL
(?i)DATABASE_URL\s*=\s*\S+://\S+:\S+@
# JDBC with password
(?i)jdbc:[a-z]+://[^;]+password=[^;\s]+
```
## Private Keys and Certificates
```
# RSA private key
-----BEGIN RSA PRIVATE KEY-----
# Generic private key
-----BEGIN PRIVATE KEY-----
# EC private key
-----BEGIN EC PRIVATE KEY-----
# OpenSSH private key
-----BEGIN OPENSSH PRIVATE KEY-----
# PGP private key
-----BEGIN PGP PRIVATE KEY BLOCK-----
# Certificate (not a secret, but may indicate key nearby)
-----BEGIN CERTIFICATE-----
```
## Generic Patterns
These catch secrets not covered by service-specific patterns:
```
# Assignment patterns with secret-like variable names
(?i)(password|passwd|pwd|secret|token|api_key|apikey|api_secret|access_key|auth_token|credentials)\s*[=:]\s*['"][^'"]{8,}['"]
# Bearer tokens in code
(?i)bearer\s+[A-Za-z0-9\-._~+/]+=*
# Base64 encoded secrets (high entropy, 20+ chars)
(?i)(secret|key|token|password)\s*[=:]\s*['"][A-Za-z0-9+/]{20,}={0,2}['"]
# Hex-encoded secrets (32+ chars)
(?i)(secret|key|token)\s*[=:]\s*['"][0-9a-fA-F]{32,}['"]
```
## Files to Always Check
**High priority** (most likely to contain secrets):
```
.env, .env.*, .env.local, .env.production
config.json, config.yaml, config.yml, config.toml
settings.py, settings.json
application.properties, application.yml
docker-compose.yml, docker-compose.*.yml
.aws/credentials, .boto
.netrc, .npmrc, .pypirc
id_rsa, id_ecdsa, id_ed25519, *.pem, *.key
```
**Check .gitignore coverage**: Ensure these files are listed in `.gitignore`. If they are tracked by git, flag as a finding.
**Git history**: Secrets may have been committed and later removed. Check with:
```bash
git log --all --diff-filter=D -- "*.env" "*.pem" "*.key"
git log --all -p -S "AKIA" -- . # Search for AWS keys in history
```
## False Positive Reduction
Skip matches that are likely not real secrets:
- Values containing only placeholder text: `example`, `changeme`, `TODO`, `xxx`, `your_`, `placeholder`, `dummy`, `test`, `sample`
- Values from documentation or comments on the same line as `example`, `e.g.`, `doc`, `TODO`
- Values in test files matching `*_test.*`, `test_*.*`, `*.spec.*`, `**/test/**`, `**/tests/**`, `**/__tests__/**`
- Environment variable references: `${VAR}`, `$VAR`, `%VAR%`, `os.environ`, `process.env`
- Empty or whitespace-only values

View file

@ -0,0 +1,260 @@
# Vulnerability Patterns Reference
Detailed patterns for identifying security vulnerabilities across languages and frameworks.
## Table of Contents
- [Injection Vulnerabilities](#injection-vulnerabilities)
- [Authentication and Session Issues](#authentication-and-session-issues)
- [Cryptographic Weaknesses](#cryptographic-weaknesses)
- [Insecure Deserialization](#insecure-deserialization)
- [Server-Side Request Forgery](#server-side-request-forgery)
- [File Operations](#file-operations)
- [Framework-Specific Patterns](#framework-specific-patterns)
## Injection Vulnerabilities
### SQL Injection
**Vulnerable patterns** (string concatenation or f-strings in queries):
```
# Python
execute(f"...{var}...")
execute("..." + var + "...")
execute("...%s..." % var)
# JavaScript
query(`...${var}...`)
query("..." + var + "...")
# Go
db.Query("..." + var + "...")
fmt.Sprintf("SELECT ... %s", var) passed to Query()
# Java
statement.execute("..." + var + "...")
```
**Safe alternatives**: Parameterized queries, prepared statements, ORM query builders.
### NoSQL Injection
**Vulnerable patterns**:
```javascript
// MongoDB: user input directly in query object
db.collection.find({ user: req.body.user, pass: req.body.pass })
// Attacker sends: { "pass": { "$gt": "" } }
```
**Safe alternative**: Validate input types, use `$eq` explicitly, sanitize with libraries like `mongo-sanitize`.
### Command Injection
**Vulnerable functions by language**:
```
Python: os.system(), os.popen(), subprocess.call(shell=True), subprocess.Popen(shell=True)
Node.js: child_process.exec(), child_process.execSync()
Go: exec.Command("sh", "-c", userInput)
Java: Runtime.exec(userInput)
PHP: exec(), system(), passthru(), shell_exec(), backticks
Ruby: system(), exec(), backticks, %x{}
```
**Safe alternative**: Use subprocess with list arguments (no shell), validate and allowlist input values.
### LDAP Injection
**Vulnerable pattern**:
```python
ldap.search_s(base, scope, f"(uid={username})")
```
**Safe alternative**: Escape special characters `()*\` and null bytes in user input.
### XSS (Cross-Site Scripting)
**Vulnerable sinks**:
```
JavaScript: innerHTML, outerHTML, document.write(), eval(), v-html, dangerouslySetInnerHTML
Template: |safe, {% autoescape off %}, !=, !{}, {!! !!}
```
**Safe alternatives**: Use `textContent`, template auto-escaping, CSP headers, DOMPurify for required HTML.
## Authentication and Session Issues
### Weak Password Storage
**Vulnerable**:
```python
# Plaintext or weak hashing
hashlib.md5(password.encode()).hexdigest()
hashlib.sha256(password.encode()).hexdigest()
```
**Safe**:
```python
# Use adaptive hashing with salt
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
```
### JWT Vulnerabilities
**Common issues**:
- Accepting `alg: "none"`
- Using symmetric algorithms (HS256) with public keys
- Not validating expiry (`exp`) or issuer (`iss`)
- Storing sensitive data in payload (JWT is base64, not encrypted)
**Verification checklist**:
```python
# Ensure algorithm is explicitly specified
jwt.decode(token, key, algorithms=["RS256"]) # explicit algorithm
jwt.decode(token, key) # VULNERABLE: accepts any algorithm
```
### Session Management
**Issues to flag**:
- Session IDs in URLs
- Missing `HttpOnly`, `Secure`, `SameSite` flags on session cookies
- No session timeout or rotation after authentication
- Predictable session identifiers
## Cryptographic Weaknesses
### Insecure Algorithms
**Deprecated/broken** (flag if found):
```
Hash: MD5, SHA1 (for security purposes)
Cipher: DES, 3DES, RC4, Blowfish
Mode: ECB mode for any block cipher
RSA: Key size < 2048 bits
```
**Acceptable**:
```
Hash: SHA-256, SHA-384, SHA-512, BLAKE2
Cipher: AES-128/256-GCM, ChaCha20-Poly1305
RSA: 2048+ bits with OAEP padding
ECDSA: P-256 or P-384 curves
```
### Hardcoded Cryptographic Material
**Flag if found in source**:
- Encryption keys, IV/nonce values
- Private keys (RSA, ECDSA, Ed25519)
- Salt values for password hashing
## Insecure Deserialization
**Vulnerable functions by language**:
```
Python: pickle.loads(), yaml.load() (without SafeLoader), marshal.loads()
Java: ObjectInputStream.readObject(), XMLDecoder
PHP: unserialize()
Ruby: Marshal.load(), YAML.load()
Node.js: node-serialize, js-yaml.load() (with dangerous schema)
```
**Safe alternatives**: Use JSON for data exchange, use safe loaders (`yaml.safe_load()`), validate and type-check deserialized data.
## Server-Side Request Forgery
**Vulnerable pattern**:
```python
# User controls the URL
requests.get(user_provided_url)
urllib.request.urlopen(user_provided_url)
```
**Mitigations**:
- Validate URLs against an allowlist of domains/IPs
- Block requests to internal/private IP ranges (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x)
- Disable redirects or validate redirect targets
- Use a network-level firewall for outbound requests
## File Operations
### Path Traversal
**Vulnerable pattern**:
```python
# User controls filename
open(os.path.join(base_dir, user_filename))
```
**Safe pattern**:
```python
import pathlib
base = pathlib.Path(base_dir).resolve()
target = (base / user_filename).resolve()
if not str(target).startswith(str(base)):
raise ValueError("Path traversal detected")
```
### Unrestricted File Upload
**Checklist**:
- Validate file type by content (magic bytes), not just extension
- Enforce maximum file size limits
- Store uploads outside the web root
- Generate random filenames, do not use user-supplied names
- Scan uploads for malware when possible
## Framework-Specific Patterns
### Django
```python
# Dangerous: raw SQL
Model.objects.raw(f"SELECT * FROM t WHERE id = {user_id}")
# Safe: ORM or parameterized raw
Model.objects.filter(id=user_id)
Model.objects.raw("SELECT * FROM t WHERE id = %s", [user_id])
# Check settings.py
DEBUG = True # Must be False in production
ALLOWED_HOSTS = ['*'] # Must be restricted
CSRF_COOKIE_SECURE = False # Must be True with HTTPS
SESSION_COOKIE_SECURE = False # Must be True with HTTPS
```
### Flask
```python
# Dangerous: XSS via Markup
from markupsafe import Markup
return Markup(f"<p>{user_input}</p>")
# Safe: Use templates with auto-escaping
return render_template("page.html", data=user_input)
# Check for debug mode
app.run(debug=True) # Must be False in production
```
### Express.js
```javascript
// Missing security headers - use helmet
const helmet = require('helmet');
app.use(helmet());
// Missing CSRF protection on state-changing routes
// Missing rate limiting on auth endpoints
// Missing input validation (use express-validator or zod)
```
### Spring Boot
```java
// Dangerous: SpEL injection
parser.parseExpression(userInput).getValue();
// Check application.properties
server.error.include-stacktrace=always // Leaks internals
management.endpoints.web.exposure.include=* // Exposes actuator
```

View file

@ -0,0 +1,326 @@
#!/usr/bin/env python3
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
"""Scan a project directory for common security issues.
Usage:
python scan_project.py /path/to/project [--format json|text]
Checks for:
- Hardcoded secrets and credentials
- Dangerous function calls (eval, exec, os.system, etc.)
- Insecure configuration patterns
- Missing security files (.gitignore, etc.)
"""
import argparse
import json
import re
import sys
from pathlib import Path
DANGEROUS_FUNCTIONS = {
".py": [
(r"\beval\s*\(", "eval() can execute arbitrary code"),
(r"\bexec\s*\(", "exec() can execute arbitrary code"),
(r"\bos\.system\s*\(", "os.system() is vulnerable to command injection"),
(r"\bos\.popen\s*\(", "os.popen() is vulnerable to command injection"),
(
r"subprocess\.\w+\(.*shell\s*=\s*True",
"subprocess with shell=True is vulnerable to command injection",
),
(r"\bpickle\.loads?\s*\(", "pickle.load() can execute arbitrary code during deserialization"),
(r"\byaml\.load\s*\([^)]*\)", "yaml.load() without SafeLoader can execute arbitrary code"),
(r'\.execute\s*\(\s*f["\']', "f-string in SQL execute() is vulnerable to SQL injection"),
(r"\.execute\s*\([^)]*%", "string formatting in SQL execute() is vulnerable to SQL injection"),
(r"\bmarkupsafe\.Markup\s*\(\s*f", "Markup() with f-string is vulnerable to XSS"),
],
".js": [
(r"\beval\s*\(", "eval() can execute arbitrary code"),
(r"\bnew\s+Function\s*\(", "Function constructor can execute arbitrary code"),
(r"\.innerHTML\s*=", "innerHTML assignment is vulnerable to XSS"),
(r"\bdocument\.write\s*\(", "document.write() is vulnerable to XSS"),
(r"child_process\.exec\s*\(", "child_process.exec() is vulnerable to command injection"),
],
".ts": [
(r"\beval\s*\(", "eval() can execute arbitrary code"),
(r"\bnew\s+Function\s*\(", "Function constructor can execute arbitrary code"),
(r"\.innerHTML\s*=", "innerHTML assignment is vulnerable to XSS"),
(r"dangerouslySetInnerHTML", "dangerouslySetInnerHTML is vulnerable to XSS"),
],
".go": [
(r'exec\.Command\s*\(\s*"sh"', "Shell execution is vulnerable to command injection"),
(r'db\.Query\s*\([^)]*\+', "String concatenation in SQL query is vulnerable to injection"),
(r'fmt\.Sprintf\s*\("SELECT', "String formatting in SQL query is vulnerable to injection"),
],
".java": [
(r"Runtime\.getRuntime\(\)\.exec\s*\(", "Runtime.exec() is vulnerable to command injection"),
(r"ObjectInputStream.*readObject", "Deserialization can execute arbitrary code"),
(r'Statement.*execute\s*\([^)]*\+', "String concatenation in SQL is vulnerable to injection"),
(r"parseExpression\s*\(.*\)\.getValue", "SpEL expression evaluation can execute arbitrary code"),
],
}
SECRET_PATTERNS = [
(r"AKIA[0-9A-Z]{16}", "AWS Access Key ID"),
(r"gh[ps]_[A-Za-z0-9_]{36,}", "GitHub Token"),
(r"glpat-[A-Za-z0-9\-]{20,}", "GitLab Token"),
(r"xox[baprs]-[A-Za-z0-9\-]{10,}", "Slack Token"),
(r"sk_live_[A-Za-z0-9]{24,}", "Stripe Secret Key"),
(r"SG\.[A-Za-z0-9\-_]{22}\.[A-Za-z0-9\-_]{43}", "SendGrid API Key"),
(r"AIza[0-9A-Za-z\-_]{35}", "Google API Key"),
(r"npm_[A-Za-z0-9]{36}", "npm Token"),
(r"pypi-[A-Za-z0-9\-_]{50,}", "PyPI Token"),
(r"-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----", "Private Key"),
]
CONFIG_ISSUES = [
(r"DEBUG\s*[=:]\s*[Tt]rue", "Debug mode enabled"),
(r"ALLOWED_HOSTS\s*=\s*\[\s*['\"]?\*['\"]?\s*\]", "Unrestricted ALLOWED_HOSTS"),
(r"CORS_ALLOW_ALL_ORIGINS\s*=\s*True", "CORS allows all origins"),
(r"SSL_VERIFY\s*[=:]\s*[Ff]alse", "TLS verification disabled"),
(r"verify\s*=\s*False", "TLS verification disabled"),
(r"NODE_TLS_REJECT_UNAUTHORIZED\s*[=:]\s*['\"]?0", "TLS verification disabled"),
]
SKIP_DIRS = {
".git", "node_modules", "__pycache__", ".venv", "venv",
".env", "dist", "build", ".tox", ".mypy_cache",
".pytest_cache", "vendor", ".bundle",
}
SKIP_EXTENSIONS = {
".pyc", ".pyo", ".so", ".dylib", ".dll", ".exe",
".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg",
".woff", ".woff2", ".ttf", ".eot", ".mp3", ".mp4",
".zip", ".tar", ".gz", ".jar", ".war",
}
MAX_FILE_SIZE = 1_000_000 # 1 MB
def should_skip(path: Path, root: Path) -> bool:
"""Return True if path should be skipped (e.g. .git, node_modules)."""
return any(part in SKIP_DIRS for part in path.relative_to(root).parts)
def scan_file(filepath: Path) -> list:
"""Scan a single file for secrets, dangerous calls, and config issues.
Args:
filepath: Path to the file to scan.
Returns:
List of finding dicts with type, severity, file, line, rule, snippet.
"""
findings = []
extension = filepath.suffix.lower()
if extension in SKIP_EXTENSIONS:
return findings
try:
if filepath.stat().st_size > MAX_FILE_SIZE:
return findings
content = filepath.read_text(encoding="utf-8", errors="ignore")
except (OSError, UnicodeDecodeError):
return findings
lines = content.splitlines()
# Check for secrets
for line_num, line in enumerate(lines, 1):
for pattern, label in SECRET_PATTERNS:
if re.search(pattern, line):
findings.append({
"type": "secret",
"severity": "critical",
"file": str(filepath),
"line": line_num,
"rule": label,
"snippet": line.strip()[:120],
})
# Check for dangerous functions
patterns = DANGEROUS_FUNCTIONS.get(extension, [])
for line_num, line in enumerate(lines, 1):
stripped = line.lstrip()
if stripped.startswith("#") or stripped.startswith("//"):
continue
for pattern, desc in patterns:
if re.search(pattern, line):
findings.append({
"type": "vulnerability",
"severity": "high",
"file": str(filepath),
"line": line_num,
"rule": desc,
"snippet": line.strip()[:120],
})
# Check for config issues
for line_num, line in enumerate(lines, 1):
for pattern, desc in CONFIG_ISSUES:
if re.search(pattern, line):
findings.append({
"type": "config",
"severity": "medium",
"file": str(filepath),
"line": line_num,
"rule": desc,
"snippet": line.strip()[:120],
})
return findings
def check_project_structure(project_dir: Path) -> list:
"""Check project root for .gitignore and sensitive files.
Args:
project_dir: Path to the project root.
Returns:
List of finding dicts for missing .gitignore or sensitive files.
"""
findings = []
gitignore = project_dir / ".gitignore"
if not gitignore.exists():
findings.append({
"type": "config",
"severity": "medium",
"file": str(project_dir),
"line": 0,
"rule": "Missing .gitignore file",
"snippet": "",
})
else:
content = gitignore.read_text(encoding="utf-8", errors="ignore")
for sensitive in [".env", "*.pem", "*.key"]:
if sensitive not in content:
findings.append({
"type": "config",
"severity": "medium",
"file": str(gitignore),
"line": 0,
"rule": f".gitignore missing pattern: {sensitive}",
"snippet": "",
})
# Check for sensitive files that should not be committed
sensitive_files = [".env", ".env.local", ".env.production"]
for name in sensitive_files:
target = project_dir / name
if target.exists():
findings.append({
"type": "secret",
"severity": "high",
"file": str(target),
"line": 0,
"rule": f"Sensitive file present: {name}",
"snippet": "",
})
return findings
def scan_project(project_dir) -> tuple:
"""Scan a project directory for security issues.
Args:
project_dir: Path or path string to the project root.
Returns:
Tuple of (list of findings, number of files scanned).
"""
root = Path(project_dir).resolve()
if not root.is_dir():
print(f"Error: {project_dir} is not a directory", file=sys.stderr)
sys.exit(1)
all_findings = check_project_structure(root)
scanned = 0
for filepath in root.rglob("*"):
if not filepath.is_file():
continue
if should_skip(filepath, root):
continue
all_findings.extend(scan_file(filepath))
scanned += 1
return all_findings, scanned
def format_text(findings, scanned):
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
findings.sort(key=lambda f: severity_order.get(f["severity"], 99))
counts = {}
for f in findings:
counts[f["severity"]] = counts.get(f["severity"], 0) + 1
lines = [
f"Scanned {scanned} files, found {len(findings)} issue(s)",
f" Critical: {counts.get('critical', 0)}",
f" High: {counts.get('high', 0)}",
f" Medium: {counts.get('medium', 0)}",
f" Low: {counts.get('low', 0)}",
"",
]
for f in findings:
loc = f"{f['file']}:{f['line']}" if f["line"] else f["file"]
lines.append(f"[{f['severity'].upper()}] {f['rule']}")
lines.append(f" Location: {loc}")
if f["snippet"]:
lines.append(f" Code: {f['snippet']}")
lines.append("")
return "\n".join(lines)
def format_json(findings, scanned):
counts = {}
for f in findings:
counts[f["severity"]] = counts.get(f["severity"], 0) + 1
return json.dumps({
"scanned_files": scanned,
"total_findings": len(findings),
"summary": counts,
"findings": findings,
}, indent=2)
def main():
parser = argparse.ArgumentParser(description="Scan a project for security issues")
parser.add_argument("path", help="Project directory to scan")
parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format")
args = parser.parse_args()
findings, scanned = scan_project(args.path)
if args.format == "json":
print(format_json(findings, scanned))
else:
print(format_text(findings, scanned))
sys.exit(1 if findings else 0)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,251 @@
#!/usr/bin/env python3
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
"""Scan a project directory for hardcoded secrets and credentials.
Usage:
python scan_secrets.py /path/to/project [--format json|text] [--include-tests]
Focused scanner for secrets, API keys, tokens, and credentials.
Uses pattern matching with false-positive reduction.
"""
import argparse
import json
import re
import sys
from pathlib import Path
PATTERNS = [
# Cloud provider keys
("AWS Access Key ID", r"AKIA[0-9A-Z]{16}"),
("AWS Secret Key", r"(?i)(aws_secret_access_key|aws_secret_key)\s*[=:]\s*['\"]?[A-Za-z0-9/+=]{40}"),
("GCP Service Account", r'"type"\s*:\s*"service_account"'),
("Azure Storage Key", r"(?i)(AccountKey|account_key)\s*[=:]\s*[A-Za-z0-9+/=]{86,}"),
# VCS and CI tokens
("GitHub Token", r"gh[ps]_[A-Za-z0-9_]{36,}"),
("GitHub Fine-grained PAT", r"github_pat_[A-Za-z0-9_]{22,}"),
("GitLab Token", r"glpat-[A-Za-z0-9\-]{20,}"),
("npm Token", r"npm_[A-Za-z0-9]{36}"),
("PyPI Token", r"pypi-[A-Za-z0-9\-_]{50,}"),
# SaaS tokens
("Slack Token", r"xox[baprs]-[A-Za-z0-9\-]{10,}"),
("Slack Webhook", r"https://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+"),
("Stripe Secret Key", r"sk_live_[A-Za-z0-9]{24,}"),
("Stripe Publishable Key", r"pk_live_[A-Za-z0-9]{24,}"),
("Twilio API Key", r"SK[0-9a-fA-F]{32}"),
("SendGrid API Key", r"SG\.[A-Za-z0-9\-_]{22}\.[A-Za-z0-9\-_]{43}"),
("Mailgun API Key", r"key-[0-9a-zA-Z]{32}"),
("Google API Key", r"AIza[0-9A-Za-z\-_]{35}"),
# Private keys
("RSA Private Key", r"-----BEGIN RSA PRIVATE KEY-----"),
("Generic Private Key", r"-----BEGIN PRIVATE KEY-----"),
("EC Private Key", r"-----BEGIN EC PRIVATE KEY-----"),
("OpenSSH Private Key", r"-----BEGIN OPENSSH PRIVATE KEY-----"),
("PGP Private Key", r"-----BEGIN PGP PRIVATE KEY BLOCK-----"),
# Database connection strings
("Database URL with Password", r"(?i)(mysql|postgres|postgresql|mongodb|redis|mssql)://[^:]+:[^@\s]+@"),
# Generic secret assignments
("Hardcoded Password", r'(?i)(password|passwd|pwd)\s*[=:]\s*["\'][^"\']{8,}["\']'),
("Hardcoded Secret", r'(?i)(secret_key|api_secret|auth_token|access_token)\s*[=:]\s*["\'][^"\']{8,}["\']'),
("Hardcoded API Key", r'(?i)(api_key|apikey)\s*[=:]\s*["\'][^"\']{8,}["\']'),
]
FALSE_POSITIVE_INDICATORS = [
"example", "changeme", "placeholder", "your_", "xxx",
"dummy", "sample", "todo", "fixme", "replace_",
"INSERT_", "<your", "${", "$(", "os.environ",
"process.env", "getenv", "config.get",
]
SKIP_DIRS = {
".git", "node_modules", "__pycache__", ".venv", "venv",
"dist", "build", "vendor", ".bundle",
".tox", ".mypy_cache", ".pytest_cache",
}
TEST_DIRS = {"test", "tests", "__tests__", "spec", "specs"}
TEST_FILE_PATTERNS = [
r"_test\.\w+$",
r"test_\w+\.\w+$",
r"\.spec\.\w+$",
r"\.test\.\w+$",
]
SKIP_EXTENSIONS = {
".pyc", ".pyo", ".so", ".dylib", ".dll", ".exe",
".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg",
".woff", ".woff2", ".ttf", ".eot",
".zip", ".tar", ".gz", ".jar",
".mp3", ".mp4", ".pdf",
}
MAX_FILE_SIZE = 1_000_000
def should_skip(path: Path, root: Path) -> bool:
"""Return True if path should be skipped (e.g. .git, node_modules)."""
return any(part in SKIP_DIRS for part in path.relative_to(root).parts)
def is_test_file(filepath: Path) -> bool:
"""Return True if filepath is under a test directory or matches test patterns."""
parts = set(filepath.parts)
if parts & TEST_DIRS:
return True
name = filepath.name
return any(re.search(pat, name) for pat in TEST_FILE_PATTERNS)
def is_false_positive(line: str) -> bool:
"""Return True if line looks like a placeholder or env reference, not a secret."""
lower = line.lower()
return any(indicator in lower for indicator in FALSE_POSITIVE_INDICATORS)
def scan_file(filepath: Path, root: Path, include_tests: bool = False) -> list:
"""Scan a single file for hardcoded secrets.
Args:
filepath: Path to the file to scan.
root: Project root directory for relative path calculation.
include_tests: If False, skip files in test dirs or matching test patterns.
Returns:
List of finding dicts with type, file, line, snippet.
"""
findings = []
if filepath.suffix.lower() in SKIP_EXTENSIONS:
return findings
if should_skip(filepath, root):
return findings
if not include_tests and is_test_file(filepath):
return findings
try:
if filepath.stat().st_size > MAX_FILE_SIZE:
return findings
content = filepath.read_text(encoding="utf-8", errors="ignore")
except (OSError, UnicodeDecodeError):
return findings
lines = content.splitlines()
for line_num, line in enumerate(lines, 1):
if is_false_positive(line):
continue
for label, pattern in PATTERNS:
if re.search(pattern, line):
findings.append({
"type": label,
"file": str(filepath),
"line": line_num,
"snippet": line.strip()[:120],
})
return findings
def scan_project(project_dir, include_tests: bool = False) -> tuple:
"""Scan a project directory for hardcoded secrets.
Args:
project_dir: Path or path string to the project root.
include_tests: If True, include test files in the scan.
Returns:
Tuple of (list of findings, number of files scanned).
"""
root = Path(project_dir).resolve()
if not root.is_dir():
print(f"Error: {project_dir} is not a directory", file=sys.stderr)
sys.exit(1)
all_findings = []
scanned = 0
for filepath in root.rglob("*"):
if not filepath.is_file():
continue
results = scan_file(filepath, root, include_tests)
all_findings.extend(results)
scanned += 1
return all_findings, scanned
def format_text(findings, scanned):
type_counts = {}
for f in findings:
type_counts[f["type"]] = type_counts.get(f["type"], 0) + 1
lines = [
f"Scanned {scanned} files, found {len(findings)} potential secret(s)",
"",
]
if type_counts:
lines.append("By type:")
for t, c in sorted(type_counts.items(), key=lambda x: -x[1]):
lines.append(f" {t}: {c}")
lines.append("")
for f in findings:
lines.append(f"[{f['type']}] {f['file']}:{f['line']}")
lines.append(f" {f['snippet']}")
lines.append("")
return "\n".join(lines)
def format_json(findings, scanned):
type_counts = {}
for f in findings:
type_counts[f["type"]] = type_counts.get(f["type"], 0) + 1
return json.dumps({
"scanned_files": scanned,
"total_findings": len(findings),
"by_type": type_counts,
"findings": findings,
}, indent=2)
def main():
parser = argparse.ArgumentParser(description="Scan for hardcoded secrets")
parser.add_argument("path", help="Project directory to scan")
parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format")
parser.add_argument("--include-tests", action="store_true", help="Include test files in scan")
args = parser.parse_args()
findings, scanned = scan_project(args.path, args.include_tests)
if args.format == "json":
print(format_json(findings, scanned))
else:
print(format_text(findings, scanned))
sys.exit(1 if findings else 0)
if __name__ == "__main__":
main()