Skip to content

How to Create Custom Firewall Rules

This guide shows you how to create sophisticated firewall rules using Peakhour's Wirefilter expression language to implement precise security policies for your applications.

Before you begin: Understand Wirefilter language and have reviewed JavaScript challenges for challenge-based actions.

Understanding Firewall Rule Structure

Firewall rules in Peakhour use Wirefilter syntax to create flexible, powerful security policies that evaluate incoming requests against multiple criteria.

Rule Components

Every firewall rule consists of:

  • Name: Descriptive identifier for the rule
  • Expression: Wirefilter condition that defines when the rule matches
  • Action: What happens when the expression evaluates to true (allow, deny, challenge, log)
  • Priority: Rule evaluation order (lower numbers = higher priority)
  • Status: Whether the rule is active or disabled

Rule Evaluation Flow

  1. Request arrives at Peakhour edge servers
  2. Context enrichment adds geolocation, bot detection, fingerprinting data
  3. Rules evaluated in priority order (ascending by position number)
  4. First match wins - matching rule's action is executed
  5. Action applied - request allowed, blocked, challenged, or logged

Set Up Basic Firewall Rules

Create Your First Rule

  1. Navigate to Rules > Firewall
  2. Click Create New Rule
  3. Configure basic settings:
Name: Block High-Risk Countries
Expression: ip.geoip.country in {"CN", "RU", "KP"}
Action: deny
Reason: Blocked high-risk geographic regions
Priority: 10

Test Rule Syntax

Use the rule validation system to ensure your expression is correct:

// Valid expression examples
ip.src eq 203.0.113.42
http.request.uri.path starts_with "/admin"
user_agent.bot == true and bot.verified == false

Verify Rule Activation

Confirm your rule is active: 1. Check Status: Rule shows as "Enabled" 2. Review Priority: Positioned correctly in rule list 3. Test: Use rule simulator or monitor real traffic

Master Wirefilter Expression Language

Basic Syntax and Operators

Comparison Operators

// Equality
ip.src eq 192.168.1.1
http.request.method == "GET"

// Inequality  
ip.geoip.country ne "US"
http.response.code != 200

// Numeric comparison
ip.geoip.asnum gt 15169
len(http.user_agent) < 50

// String operations
http.host contains "admin"
http.user_agent starts_with "Mozilla"
http.request.uri.path ends_with ".php"

Logical Operators

// AND conditions
ssl == true and ip.geoip.country eq "US"

// OR conditions  
http.request.method in {"GET", "HEAD"} or user_agent.bot == true

// NOT conditions
not (ip.src in $trusted_ips) and user_agent.bot == false

// Complex grouping
(ip.geoip.country in {"CN", "RU"} or ip.src in $suspicious_ips) and 
not (http.user_agent contains "googlebot")

Available Request Fields

HTTP Request Fields

http.host                    // Host header value
http.request.method          // GET, POST, PUT, etc.
http.request.uri            // Full URI with query parameters
http.request.uri.path       // Path portion only
http.request.uri.query      // Query string only
http.request.version        // HTTP version
http.user_agent             // User-Agent header
http.referer                // Referer header
ssl                         // TLS connection boolean

Network and Location Fields

ip.src                      // Client IP address
ip.geoip.country           // Two-letter country code
ip.geoip.asnum             // AS number (integer)

Bot Detection Fields

user_agent.bot             // Is detected as bot (boolean)
user_agent.bot.type        // Bot type: google, bing, facebook, etc.
user_agent.mobile          // Mobile device detection
user_agent.software        // Software classification
user_agent.type            // General type classification
bot.verified               // Bot verification status
bot.verification_state     // Verification state

Device Fingerprinting Fields

fingerprint.http           // HTTP fingerprint
fingerprint.http2          // HTTP/2 fingerprint
fingerprint.ml             // Machine learning scores
fingerprint.tcp            // TCP fingerprint
fingerprint.tls            // TLS fingerprint
fingerprint.tls.ja4        // JA4 TLS fingerprint
fingerprint.tls.v3         // TLS fingerprint with sorted ciphers

Peakhour-Specific Fields

peakhour.req.session       // Session identifier
peakhour.server.name       // Edge server name
peakhour.client.proxy      // Behind proxy detection
peakhour.waf.exposed_password  // WAF password detection

Built-in Functions

String Functions

starts_with(http.request.uri.path, "/api/")
ends_with(http.host, ".example.com")  
lower(http.host) eq "example.com"
len(http.user_agent) gt 500
concat("prefix-", ip.src)
to_string(ip.geoip.asnum)

Pattern Matching

// Wildcard matching
matches(http.request.uri, "*/admin/*")
matches(http.user_agent, "*bot*")

// Note: Use matches() for simple patterns, not full regex

Create Geographic Access Controls

Country-Based Blocking

Block or allow specific countries:

Block High-Risk Countries

Name: Block Sanctioned Countries
Expression: ip.geoip.country in {"CN", "RU", "IR", "KP"}
Action: deny
Reason: Traffic from high-risk countries

Allow Only Specific Regions

Name: Geo-Restrict to North America
Expression: ip.geoip.country not in {"US", "CA", "MX"}
Action: deny  
Reason: Service limited to North America

Challenge International Traffic

Name: Challenge Non-US Traffic
Expression: ip.geoip.country ne "US" and not (ip.src in $trusted_ips)
Action: challenge
Reason: International traffic verification

AS Number Restrictions

Control access based on network providers:

Block Hosting Providers

Name: Block Common Hosting ASNs
Expression: ip.geoip.asnum in {16509, 14618, 15169} 
Action: challenge
Reason: Challenge cloud hosting traffic

Allow Corporate Networks

Name: Allow Corporate ASN
Expression: ip.geoip.asnum in {7018, 209}
Action: allow
Reason: Trusted corporate networks

Combined Geographic Rules

Create sophisticated geographic policies:

Name: Advanced Geographic Control
Expression: (ip.geoip.country in {"CN", "RU"} and ip.geoip.asnum in $hosting_asns) or 
           (ip.geoip.country in {"BR", "IN"} and not user_agent.bot)
Action: challenge
Reason: High-risk geographic and network combination

Implement Bot Management Rules

Verified Bot Rules

Handle legitimate crawlers properly:

Allow Verified Search Engines

Name: Allow Verified Search Bots
Expression: user_agent.bot == true and 
           user_agent.bot.type in {"google", "bing", "yahoo"} and
           bot.verified == true
Action: allow
Reason: Verified search engine crawlers

Challenge Unverified Bots

Name: Challenge Unverified Bots  
Expression: user_agent.bot == true and bot.verified == false
Action: challenge
Reason: Unverified bot activity

User Agent Analysis

Create rules based on user agent patterns:

Block Obvious Scrapers

Name: Block Common Scraping Tools
Expression: lower(http.user_agent) contains "curl" or
           lower(http.user_agent) contains "wget" or  
           lower(http.user_agent) contains "python-requests"
Action: deny
Reason: Automated scraping tools

Challenge Suspicious Agents

Name: Challenge Suspicious User Agents
Expression: len(http.user_agent) < 20 or
           not contains(http.user_agent, "Mozilla") or
           http.user_agent eq ""
Action: challenge  
Reason: Unusual user agent characteristics

Advanced Bot Detection

Combine multiple signals for sophisticated bot detection:

Name: Advanced Bot Challenge
Expression: (user_agent.mobile == false and user_agent.software ne "browser") or
           (user_agent.bot == false and len(http.user_agent) < 50) or
           (http.user_agent contains "bot" and bot.verified == false)
Action: challenge
Reason: Multiple bot indicators detected

Protect Application Endpoints

Admin Area Protection

Secure administrative interfaces:

Restrict Admin Access

Name: Admin IP Restriction
Expression: starts_with(http.request.uri.path, "/admin") and 
           not (ip.src in $admin_ips)
Action: deny
Reason: Admin access restricted to authorized IPs

Challenge Admin Login Attempts

Name: Challenge Admin Logins
Expression: http.request.uri.path eq "/admin/login" and 
           http.request.method eq "POST" and
           not (ip.src in $office_networks)
Action: challenge
Reason: Admin login security verification

API Endpoint Security

Protect API endpoints with targeted rules:

API Rate Control

Name: API Traffic Control  
Expression: starts_with(http.request.uri.path, "/api/") and
           not (http.user_agent contains "MyApp" or ip.src in $api_whitelist)
Action: challenge
Reason: Unauthorized API access attempt

Block API Abuse

Name: Block API Scraping
Expression: starts_with(http.request.uri.path, "/api/") and
           (user_agent.bot == true or http.user_agent contains "python") and
           not (ip.src in $trusted_apis)
Action: deny
Reason: API scraping prevention

File Upload Protection

Secure file upload endpoints:

Name: Upload Endpoint Security
Expression: http.request.uri.path contains "/upload" and 
           http.request.method eq "POST" and
           (ip.geoip.country in $high_risk_countries or user_agent.bot == true)
Action: challenge
Reason: File upload security verification

Use Lists for Scalable Rules

Create and Use IP Lists

Manage IP addresses efficiently with lists:

  1. Create IP List

  2. Navigate to Rules > Lists

  3. Create new IP List named trusted_office_ips
  4. Add IP ranges:

    203.0.113.0/24
    198.51.100.0/24
    192.0.2.0/24
    

  5. Use in Rules

    Name: Office Network Access
    Expression: ip.src in $trusted_office_ips
    Action: allow
    Reason: Trusted office networks
    

String Lists for Domains and Paths

Create Domain List

// Create string list: blocked_domains
// Contents: malicious.com, spam.example, attacker.net

Name: Block Malicious Referrers
Expression: http.referer contains $blocked_domains
Action: deny
Reason: Malicious referrer domains

Path-Based Lists

// Create string list: protected_paths  
// Contents: /admin, /config, /backup, /.env

Name: Protect Sensitive Paths
Expression: http.request.uri.path in $protected_paths
Action: challenge
Reason: Accessing sensitive paths

Built-in Reputation Lists

Leverage Peakhour's threat intelligence:

// Block known attack sources
ip.src in $webattacks

// Block malware sources
ip.src in $malware  

// Block Tor exit nodes
ip.src in $tor

// Challenge datacenter IPs
ip.src in $datacenter

Advanced Rule Patterns

Multi-Condition Security Rules

Create comprehensive security policies:

Complete Attack Prevention

Name: Comprehensive Attack Block
Expression: (ip.src in $webattacks or ip.src in $malware) or
           (ip.geoip.country in {"CN", "RU"} and user_agent.bot == false) or
           (http.request.uri.path contains "admin" and not ssl) or
           (len(http.user_agent) < 10 and http.request.method eq "POST")
Action: deny
Reason: Multiple attack indicators

Business Logic Protection

Implement application-specific security:

E-commerce Protection

Name: Checkout Security
Expression: http.request.uri.path contains "/checkout" and
           (ip.geoip.country in $fraud_countries or
            user_agent.bot == true or
            not ssl)
Action: challenge
Reason: Transaction security verification

Content Protection

Name: Premium Content Access
Expression: http.request.uri.path starts_with "/premium/" and
           not (http.request.headers["Authorization"] exists and
                ip.src in $subscriber_networks)
Action: deny  
Reason: Premium content requires authorization

Conditional Logging

Monitor specific traffic patterns:

Security Monitoring

Name: Log Suspicious Activity
Expression: (starts_with(http.request.uri.path, "/admin") or
           http.request.uri.path contains "wp-admin" or
           http.request.uri.path contains "phpmyadmin") and
           not (ip.src in $admin_ips)
Action: log
Reason: Administrative access monitoring

Test and Validate Rules

Use Rule Simulation

Test rules before deployment:

  1. Navigate to Rules > Test Rules
  2. Enter test parameters:
    IP Address: 203.0.113.42
    Country: US
    User Agent: Mozilla/5.0...
    Path: /admin/login
    Method: POST
    
  3. Review which rules match and their actions

Monitor Rule Performance

Track rule effectiveness:

  1. Analytics Dashboard: Review rule hit rates and actions
  2. False Positives: Monitor legitimate traffic being blocked
  3. Rule Timing: Ensure complex rules don't impact performance
  4. Coverage Gaps: Identify attack patterns not caught by rules

Gradual Deployment

Implement rules safely:

Phase 1 - Log Mode

Name: Test New Rule
Expression: suspicious_pattern
Action: log  // Start with logging only
Reason: Testing new detection pattern

Phase 2 - Challenge Mode

// After confirming pattern validity
Action: challenge  // Escalate to challenging

Phase 3 - Block Mode

// After validating minimal false positives
Action: deny  // Final blocking implementation

Optimize Rule Performance

Rule Ordering Best Practices

Optimize evaluation order:

  1. Most Specific First: Place targeted rules at higher priority
  2. High-Volume Patterns: Put frequently-matching rules early
  3. Expensive Operations Last: Place complex fingerprinting rules lower
  4. Allow Rules First: Put allow rules before more restrictive ones

Example Priority Structure

Priority 1:  Allow trusted IPs (quick allow)
Priority 5:  Block known attacks (high confidence blocks)  
Priority 10: Geographic restrictions (medium complexity)
Priority 20: Bot detection rules (requires analysis)
Priority 30: Complex pattern matching (expensive)

Expression Optimization

Write efficient expressions:

Inefficient

// Multiple separate conditions
http.user_agent contains "bot" or 
http.user_agent contains "crawler" or
http.user_agent contains "spider" or
http.user_agent contains "scraper"

Efficient

// Use lists or combined patterns
http.user_agent contains $bot_keywords
// or
lower(http.user_agent) matches "*bot*"

Monitor Resource Usage

Track rule performance impact:

  • Evaluation Time: Complex rules with many conditions
  • Memory Usage: Large lists or complex fingerprinting
  • Network Calls: Bot verification and reputation checks
  • Overall Latency: Total rule processing time per request

Troubleshooting Common Issues

Expression Syntax Errors

Problem: Rule validation fails Solutions:

  • Check operator spelling (eq not ==)
  • Ensure proper quotation of strings
  • Verify field names match available fields
  • Balance parentheses in complex expressions

Rules Not Matching

Problem: Expected traffic not caught by rules Solutions:

  • Use rule simulator with actual request data
  • Check rule priority ordering
  • Verify field values are as expected
  • Test with simplified expressions first

Performance Issues

Problem: Rules causing latency Solutions:

  • Simplify complex expressions
  • Move expensive rules to lower priority
  • Use lists instead of long OR conditions
  • Monitor rule evaluation times

False Positives

Problem: Legitimate traffic being blocked Solutions:

  • Add allow rules for legitimate patterns
  • Use challenge instead of deny actions
  • Implement more specific targeting
  • Create exception lists for known good sources

Security Best Practices

Defense in Depth

  • Layer multiple rule types (geographic, bot, behavioral)
  • Use progressive actions (log → challenge → deny)
  • Implement both positive and negative security models
  • Regular review and update of rule effectiveness

Principle of Least Privilege

  • Start with restrictive rules and add exceptions
  • Use allow lists for trusted sources
  • Challenge suspicious traffic before blocking
  • Monitor and adjust based on legitimate usage patterns

Continuous Monitoring

  • Regular review of rule analytics and effectiveness
  • Monitor for new attack patterns requiring additional rules
  • Track false positive rates and user impact
  • Update rules based on threat intelligence and attack trends

Your custom firewall rules are now configured to provide comprehensive, flexible security protection that adapts to your specific application requirements and threat landscape.