Writing Security Rules

Learn how to write custom security rules using Code Pathfinder's intuitive Python DSL. Detect vulnerabilities with simple, expressive code.

What are Rules?

Rules are patterns that Code Pathfinder looks for in your codebase to detect security vulnerabilities, bad practices, or policy violations. Each rule defines:

  • What to look for - Function calls, data flows, variable patterns
  • Where it's dangerous - Sources of untrusted data, unsafe sinks
  • How to report it - Severity, CWE/OWASP classification

Example: A rule to detect SQL injection might look for user input (like request.GET) flowing into database queries (like execute()) without proper sanitization.

Why Python DSL?

Writing rules in Python offers major advantages over traditional approaches like regex or YAML:

  • Intuitive syntax - Write rules that read like natural language
  • Type safety - Python type hints catch errors before runtime
  • Powerful patterns - Detect complex vulnerabilities with dataflow analysis
  • Reusable components - Share common patterns across rules
  • Easy testing - Use standard Python testing tools like pytest

Architecture

Code Pathfinder uses a three-tier architecture that separates rule authoring from execution:

1. Python DSL (You write here)
↓ Simple, expressive rule syntax
2. JSON IR (Intermediate format)
↓ Language-agnostic representation
3. Go Executor (High-performance engine)
→ Analyzes your codebase

This design means you write simple Python code, but benefit from Go's speed and performance during analysis.

Quick Example

Here's a complete rule that detects dangerous eval() calls:

from codepathfinder import rule, calls

@rule(
    id="dangerous-eval",
    severity="critical",
    cwe="CWE-94"
)
def detect_eval():
    """Detects dangerous eval() calls that could execute arbitrary code"""
    return calls("eval")

That's it! This rule will:

  • Find all eval() function calls in your code
  • Report them as critical severity issues
  • Reference CWE-94 (Code Injection)

To run it:

pathfinder scan --rules detect_eval.py --project /path/to/your/code

✓ Works on first try: Copy the code above, save it as detect_eval.py, and run the scan command. It will immediately find all eval() calls in your project.

Next Steps

Ready to write your first rule? Follow our step-by-step guide: