Metadata-Version: 2.4
Name: wp-security-rules
Version: 0.1.0
Summary: WordPress plugin security rules: Semgrep taint rules, 219 triage regex patterns, and CWE / severity / CVSS / remediation classification.
Project-URL: Homepage, https://github.com/rahulreddykarne/wp-security-rules
Project-URL: Source, https://github.com/rahulreddykarne/wp-security-rules
Project-URL: Issues, https://github.com/rahulreddykarne/wp-security-rules/issues
Author: Rahul Karne
License-Expression: MIT
License-File: LICENSE
Keywords: cvss,cwe,php,sast,security,semgrep,static-analysis,vulnerability,wordpress
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: PHP
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: semgrep
Requires-Dist: semgrep>=1.50; (sys_platform != 'win32') and extra == 'semgrep'
Description-Content-Type: text/markdown

# wp-security-rules

[![PyPI](https://img.shields.io/pypi/v/wp-security-rules.svg)](https://pypi.org/project/wp-security-rules/)
[![Python](https://img.shields.io/pypi/pyversions/wp-security-rules.svg)](https://pypi.org/project/wp-security-rules/)
[![CI](https://github.com/rahulreddykarne/wp-security-rules/actions/workflows/ci.yml/badge.svg)](https://github.com/rahulreddykarne/wp-security-rules/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

Security rules for reviewing WordPress plugins, in three layers:

1. **Semgrep taint rules.** 12 rules that follow user input (`$_GET`, `$_POST`, `$_REQUEST`, `$_COOKIE`, `$_FILES`, `WP_REST_Request` parameters, …) through variables and string building into dangerous sinks, and understand WordPress sanitizers such as `$wpdb->prepare()`, `esc_html()`, `absint()` and `sanitize_file_name()`. Every rule ships with annotated test cases.
2. **219 regex patterns.** Fast, line-based triage patterns across 19 categories, usable from Python, `grep -iE` or `rg -i`, with no other tooling needed.
3. **Classification.** Map any finding to a CWE id, severity, CVSS v3.1 vector and WordPress-specific remediation advice.

Pure Python, zero dependencies. Semgrep is only needed if you want to run the Semgrep rules.

## Install

```bash
pip install wp-security-rules
pip install "wp-security-rules[semgrep]"   # also installs the Semgrep CLI (Linux/macOS)
```

## Semgrep rules

| Rule id | Finds | CWE |
|---|---|---|
| `wordpress-sql-injection` | input in `$wpdb->query/get_results/get_var/get_row/get_col` without `prepare()` | CWE-89 |
| `wordpress-xss` | input reaching `echo`, `print`, `printf`, `wp_die()` unescaped | CWE-79 |
| `wordpress-command-injection` | input in `exec`, `system`, `shell_exec`, `passthru`, `popen`, `proc_open`, backticks | CWE-78 |
| `wordpress-code-injection` | input in `eval`, `assert`, `create_function`, `call_user_func`, dynamic calls | CWE-94 |
| `wordpress-preg-replace-eval-modifier` | `preg_replace()` with the `/e` modifier | CWE-94 |
| `wordpress-file-inclusion` | input in `include` / `require` | CWE-98 |
| `wordpress-path-traversal` | input in `readfile`, `fopen`, `file_put_contents`, `unlink`, `copy`, `rename`, … | CWE-22 |
| `wordpress-object-injection` | input in `unserialize()` / `maybe_unserialize()` | CWE-502 |
| `wordpress-ssrf` | input as the URL of `wp_remote_*`, cURL, `file_get_contents` | CWE-918 |
| `wordpress-open-redirect` | input in `wp_redirect()` or a `Location:` header | CWE-601 |
| `wordpress-privilege-escalation` | input as an option name, user id, role, capability or user-meta key | CWE-269 |
| `wordpress-unsafe-file-upload` | `move_uploaded_file()` in a function with no file-type check | CWE-434 |

Run them on a plugin:

```bash
semgrep --config "$(wp-security-rules semgrep-path)" path/to/plugin
```

Or copy them into your own rules repository or CI:

```bash
wp-security-rules export-semgrep ./semgrep-rules/wordpress
```

From Python:

```python
from wp_security_rules import run_semgrep, semgrep_rules_dir

results = run_semgrep("path/to/plugin")        # parsed Semgrep JSON
for r in results["results"]:
    print(r["check_id"], r["path"], r["start"]["line"])
```

> Semgrep does not run natively on Windows. Use WSL, or Docker:
> `docker run --rm -v "$PWD:/src" semgrep/semgrep semgrep --config /src/rules /src/plugin`

**On real code:** across 34 popular WordPress.org plugins (16,696 PHP files, including WooCommerce, Jetpack, Elementor and Yoast SEO), the pack reports 126 findings, about 4 per plugin. These are leads for manual review in well-maintained code, not confirmed vulnerabilities.

The rules are validated with `semgrep --validate` and tested with `semgrep --test` against vulnerable (`// ruleid:`) and safe (`// ok:`) samples in [`tests/semgrep/`](tests/semgrep). CI runs both on every push.

## Regex patterns

```python
from wp_security_rules import scan_directory, scan_text, VULNERABILITY_PATTERNS, CATEGORIES

for m in scan_directory("path/to/plugin", categories=["SQLi", "RCE", "Unserialize"]):
    print(m.severity, m.cwe, f"{m.file}:{m.line}", m.pattern)
    print("   ", m.snippet)

scan_text("<?php echo $_GET['q'];")
# [PatternMatch(pattern='XSS - Direct Echo User Input', category='XSS', severity='MEDIUM',
#               cwe='CWE-79', file='<string>', line=1, column=7, snippet="<?php echo $_GET['q'];")]

len(VULNERABILITY_PATTERNS)   # 219
CATEGORIES   # ('Auth', 'CSRF', 'Crypto', 'Info', 'LFI', 'POP Chain', 'Path', 'Privesc', 'RCE',
             #  'REST', 'RFI', 'Redirect', 'SQLi', 'SSRF', 'Unserialize', 'Upload', 'WP', 'XSS', 'XXE')
```

Command line (exit code 1 when anything matches, so it can gate CI):

```bash
wp-security-rules scan path/to/plugin --min-severity HIGH
wp-security-rules scan path/to/plugin --category SQLi --category XSS --json
```

The patterns are deliberately broad. They are for finding code worth reading, and will produce false positives. Use the Semgrep rules when you need data-flow precision.

## Classification

```python
from wp_security_rules import classify, get_cwe_id, get_severity, get_cvss_vector, get_remediation

classify("SQLi - Direct wpdb Query")
# {'type': 'SQLi - Direct wpdb Query', 'cwe': 'CWE-89', 'cwe_name': 'SQL Injection',
#  'severity': 'CRITICAL', 'cvss_vector': 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H',
#  'remediation': '**SQL Injection Remediation:**\n1. Use $wpdb->prepare() ...'}

get_cwe_id("wordpress-ssrf")                              # 'CWE-918'
get_cvss_vector({"type": "XSS", "authenticated": True})   # 'CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N'
```

```console
$ wp-security-rules classify path traversal
CWE:      CWE-22 Path Traversal
Severity: HIGH
CVSS:     CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N
...
```

Keywords are matched as whole words, and specific vulnerability names take precedence over generic words. So `"XSS - Wp_kses Bypass"` is classified as XSS rather than authentication bypass, and `"Source code disclosure"` is not mistaken for remote code execution.

## Limitations

- The Semgrep rules are intraprocedural taint rules. Input that flows through a helper function in another file, or through the database (second-order injection), is not tracked. A sanitizer applied in the wrong context (for example `esc_html()` inside a JavaScript string) is still treated as safe.
- Capability and nonce checks are not modelled by the taint rules. An authenticated, capability-checked admin form that writes `$_POST` into an option will still be reported. For entry-point and authorization analysis, see [`wp-attack-surface`](https://pypi.org/project/wp-attack-surface/).
- CVSS vectors are heuristic starting points. Score each confirmed vulnerability yourself.

## Origin

Extracted from the static-analysis stages of the ARKA WordPress plugin vulnerability scanner. The Semgrep rules were rewritten in taint mode for this release.

## License

[MIT](LICENSE)
