Virtual Patching Best Practices
Table of contents
- Injection
- 1. FortiWeb: Virtual Patching for SQL Injection
- 2. F5 BIG-IP ASM: Virtual Patching for Command Injection
- 3. AWS WAF: Virtual Patching for SQL Injection
- 4. Azure WAF: Virtual Patching for SQL and Command Injection
- 5. Cloudflare: Virtual Patching for SQL Injection and Command Injection
- 6. OpenRASP: Runtime Application Self-Protection (RASP) for SQL Injection
- Request Forgery
- Security Misconfigurations
- 1. FortiWeb: Virtual Patching for XXE and Insecure File Uploads
- 2. F5 Big-IP ASM: Protecting Against XXE and Insecure File Uploads
- 3. AWS WAF: Protecting Against XXE and Insecure File Uploads
- 4. Azure WAF: Defending Against XXE and File Upload Vulnerabilities
- 5. Cloudflare WAF: Virtual Patching for XXE and File Upload Defense
- 6. OpenRASP: Runtime Application Self-Protection for XXE and Insecure File Uploads
- Broken Access Control
- Identification and Authentication Failures
- Cross Site Scripting
Virtual patching is a crucial security strategy within the DevSecOps framework, offering a quick and effective way to mitigate vulnerabilities in web applications without modifying the underlying code. In dynamic development environments, vulnerabilities may be discovered in production or legacy systems where immediate code fixes aren't feasible. Virtual patching addresses this by leveraging a Web Application Firewall (WAF) or Intrusion Prevention System (IPS) to detect and block attacks targeting specific vulnerabilities. This method helps ensure continuous security, giving development teams the time needed to implement permanent patches, without disrupting deployment cycles or slowing down operations.
In the context of DevSecOps, virtual patching aligns with the practice of continuous security by automating threat mitigation during the development lifecycle. By integrating WAFs into CI/CD pipelines, organizations can secure applications in real-time as new code is pushed, reducing the attack surface while adhering to DevOps' rapid deployment demands. This approach supports the collaboration between development, operations, and security teams, ensuring that applications remain protected even as they evolve, thus reinforcing security at every stage of development.
Injection
Virtual patching is a method that helps protect applications from common vulnerabilities like SQL injections and command injections without modifying the application's source code. In web application firewalls (WAFs), virtual patches are used to prevent attacks by analyzing incoming traffic and blocking malicious requests. Here's a breakdown of how virtual patching works across different WAF solutions with examples and commands.
1. FortiWeb: Virtual Patching for SQL Injection
FortiWeb provides a robust WAF that helps defend against injection attacks. You can create custom security rules to virtually patch SQL injection vulnerabilities by filtering suspicious request patterns.
Steps to create a custom policy:
Log in to FortiWeb and go to Web Protection > Signature Rules.
Select Create New to define a custom signature to detect SQL injection patterns.
Example of a custom SQL injection rule:
SELECT.*FROM|INSERT.*INTO|DELETE.*FROM|DROP.*TABLE|UNION.*SELECT|--|/*
This rule captures common SQL injection attempts by searching for dangerous SQL keywords like SELECT
, INSERT
, DELETE
, DROP
, and UNION
.
Enforcing virtual patching:
- After creating the signature, apply the custom rule to the HTTP traffic by navigating to Web Protection Profiles and associating the rule with the necessary web applications.
2. F5 BIG-IP ASM: Virtual Patching for Command Injection
F5's BIG-IP ASM (Application Security Manager) is highly customizable and allows for virtual patching via manual attack signatures or policies. You can configure a security policy to block command injection attacks.
Command injection blocking:
Go to Security > Application Security > Attack Signatures.
Create a new attack signature targeting command injection patterns.
Example command injection pattern:
(;|\||&|\$|\`|<|>|"|'|\(|\)|\{|\})
This pattern targets characters often used in command injection payloads, such as ;
, |
, and &
.
Applying the policy:
- After defining the signature, enable it in the security policy applied to the web application. This ensures all traffic passes through the virtual patch.
3. AWS WAF: Virtual Patching for SQL Injection
AWS WAF allows you to create rules using conditions based on SQL injection patterns. With AWS WAF, you can automatically block SQL injection attempts using managed rules, or you can create custom SQL injection detection.
Steps for creating a SQL injection rule:
Navigate to AWS WAF & Shield > Web ACLs > Create Rule.
Select Add rule and choose SQL injection match condition.
Example AWS WAF SQL injection rule:
statement:
"queryArguments":
[
{"union select", "insert into", "drop table", "--"}
]
This custom match rule identifies common SQL injection payloads such as UNION SELECT
and DROP TABLE
.
Apply the rule:
- Attach the rule to your Web ACL, and it will monitor incoming traffic to block requests containing SQL injection attempts.
4. Azure WAF: Virtual Patching for SQL and Command Injection
Azure WAF on Application Gateway offers out-of-the-box virtual patches through managed rules to defend against SQL and command injections. You can also define custom rules for more granular control.
Custom rule for SQL injection:
Navigate to WAF Policies > Custom rules in Azure Portal.
Add a new custom rule for SQL injection patterns.
Example of a custom rule expression:
SELECT|INSERT|DELETE|DROP|UNION|%27|%22
This custom regex rule filters out SQL keywords and encodings like %27
(single quote) and %22
(double quote) used in injection attacks.
Applying virtual patching:
- Once the rule is created, apply it to the WAF policy associated with your Azure Application Gateway.
5. Cloudflare: Virtual Patching for SQL Injection and Command Injection
Cloudflare WAF provides managed rulesets as well as the ability to create custom firewall rules using expressions to defend against injection attacks.
Steps for custom virtual patch:
Go to Firewall > Firewall Rules in the Cloudflare dashboard.
Create a new firewall rule with a custom expression for SQL injection.
Example Cloudflare WAF rule (for SQL injection):
(http.request.uri.query contains "SELECT" or
http.request.uri.query contains "DROP" or
http.request.uri.query contains "'--")
This rule checks if the request URI contains typical SQL injection patterns.
Enforcement:
- Enable the rule to protect your site from SQL injection attacks in real-time.
6. OpenRASP: Runtime Application Self-Protection (RASP) for SQL Injection
OpenRASP provides runtime application self-protection, which defends against injection attacks by monitoring code execution in real-time. Unlike WAFs, it directly integrates with the application runtime, offering deep visibility into application behavior.
Example of defending against SQL injection in OpenRASP:
Install OpenRASP for your application. For example, in a Java environment, add OpenRASP as a JVM agent.
Configure the
sql
module inopenrasp.yml
to monitor for SQL injection patterns.
Example OpenRASP SQL Injection detection config:
plugin.filter.sql_policy:
action: "block"
rules:
- "SELECT.*FROM.*"
- "INSERT.*INTO.*"
- "UNION.*SELECT.*"
This configuration blocks SQL injection attempts that contain patterns like SELECT FROM
and UNION SELECT
.
Applying virtual patches:
- OpenRASP will automatically block requests with malicious SQL statements at runtime.
Request Forgery
Virtual patching provides a robust layer of defense against common web vulnerabilities like Server-Side Request Forgery (SSRF) and Cross-Site Request Forgery (CSRF) by blocking malicious requests before they reach the application layer. Below is a detailed guide on how to configure virtual patching in various platforms—FortiWeb, F5, AWS, Azure, Cloudflare, and OpenRASP—to mitigate SSRF and CSRF attacks.
1. FortiWeb:
FortiWeb is a Web Application Firewall (WAF) solution that provides robust virtual patching features to protect against SSRF and CSRF. It can inspect and block HTTP requests that match malicious patterns, such as forged requests.
CSRF Defense in FortiWeb:
FortiWeb provides an anti-CSRF module that tracks user sessions and validates request tokens.
Step 1: Enable CSRF protection:
Navigate to Web Protection → CSRF Protection.
Enable Insert CSRF Token for forms and AJAX requests.
Set Token Expiry (in minutes) to limit token reuse
config waf csrf-protection
set status enable
set csrf-token-timeout 300
end
SSRF Defense in FortiWeb:
- Step 1: Configure URL restriction policies to block requests targeting internal servers (used in SSRF).
config waf url-rewrite-policy
edit "block_ssrf"
set url /api/*
set action block
set server-internal-network 192.168.1.0/24
next
end
2. F5 BIG-IP:
F5's BIG-IP ASM (Application Security Manager) allows you to create custom signatures and URL filters that can block forged requests, particularly SSRF and CSRF attacks.
CSRF Defense in F5 ASM:
BIG-IP includes CSRF protection mechanisms that enforce token validation across all sensitive requests.
Step 1: Enable CSRF protection in ASM policy:
Navigate to Security → Application Security → Policy Building → CSRF Protection.
Add token-based validation for forms.
tmsh modify asm policy my_asm_policy csrf-protection enable
SSRF Defense in F5 ASM:
- Step 1: Create an ASM signature to block SSRF requests by filtering suspicious payloads such as internal IP addresses or unusual DNS lookups.
tmsh modify asm signature-sets SSRF-signature-set enable
3. AWS WAF:
AWS WAF can block SSRF and CSRF by using custom rules to filter requests based on header inspection, payload patterns, and IP filtering.
CSRF Defense in AWS WAF:
AWS WAF doesn’t natively support CSRF token management, but you can use custom rules to detect missing or mismatched tokens.
- Step 1: Create a rule that checks for the presence of a CSRF token in headers.
{
"Name": "csrf-token-check",
"Priority": 1,
"Action": {
"Block": {}
},
"Statement": {
"ByteMatchStatement": {
"SearchString": "csrf-token",
"FieldToMatch": {
"Headers": {
"Name": "X-Csrf-Token"
}
},
"TextTransformations": [
{
"Type": "LOWERCASE"
}
]
}
}
}
SSRF Defense in AWS WAF:
- Step 1: Create a rule to block SSRF attempts by filtering IP ranges and restricting URL patterns that target internal IPs or local network requests.
{
"Name": "ssrf-detect",
"Priority": 2,
"Action": {
"Block": {}
},
"Statement": {
"IPSetReferenceStatement": {
"ARN": "arn:aws:wafv2:region:account-id:ipset/internal-ips"
}
}
}
4. Azure WAF:
Azure WAF provides virtual patching through custom rule sets in Azure Front Door or Application Gateway.
CSRF Defense in Azure WAF:
- Step 1: Enable custom rule to validate CSRF tokens in headers
az network application-gateway waf-policy custom-rule create \
--name block-missing-csrf \
--action block \
--priority 1 \
--match-variable RequestHeaders.csrf-token \
--operator Equal \
--value 0
SSRF Defense in Azure WAF:
- Step 1: Block SSRF by defining rules that filter requests based on IP ranges, URL patterns, or specific headers.
az network application-gateway waf-policy custom-rule create \
--name block-ssrf \
--action block \
--priority 2 \
--match-variable RequestUri \
--operator Contains \
--value "169.254.169.254" # block AWS/Azure metadata IP
5. Cloudflare WAF:
Cloudflare provides virtual patching through custom firewall rules that can block SSRF and CSRF attempts.
CSRF Defense in Cloudflare:
- Step 1: Add a custom rule to validate CSRF tokens in headers.
http.request.headers["X-Csrf-Token"] eq "" or http.request.body.empty
SSRF Defense in Cloudflare:
- Step 1: Use Cloudflare’s firewall rules to block SSRF by detecting private IP addresses and abnormal request patterns.
ip.src in {192.168.0.0/16 10.0.0.0/8} and http.request.uri contains "internal"
6. OpenRASP:
OpenRASP is a runtime application security protection tool that can detect SSRF and CSRF attacks at runtime by analyzing application behavior.
CSRF Defense in OpenRASP:
- Step 1: Configure CSRF detection in OpenRASP's policy file.
{
"csrf_protection": {
"enable": true,
"csrf_token": "X-Csrf-Token",
"check_ajax": true
}
}
SSRF Defense in OpenRASP:
- Step 1: Enable SSRF detection in OpenRASP configuration.
{
"ssrf_protection": {
"enable": true,
"block_internal": true,
"whitelist": ["127.0.0.1", "localhost"]
}
}
Security Misconfigurations
Virtual patching plays an essential role in defending against various security misconfigurations, such as XML External Entity (XXE) injection or insecure file uploads. These vulnerabilities can expose sensitive information or allow attackers to upload malicious files. By leveraging Web Application Firewalls (WAFs) and Runtime Application Self-Protection (RASP) solutions, we can deploy immediate virtual patches that mitigate these threats without requiring changes to the application code. Below is a detailed description of how to implement virtual patching for security misconfigurations in popular platforms like FortiWeb, F5, AWS, Azure, Cloudflare, and OpenRASP.
1. FortiWeb: Virtual Patching for XXE and Insecure File Uploads
FortiWeb provides a robust WAF that helps create virtual patches against common vulnerabilities such as XXE or insecure file uploads.
Step 1: Create a Custom Signature for XXE Mitigation
Log in to FortiWeb.
Navigate to Web Protection > Custom Signature.
Create a new signature rule for detecting malicious XML content:
Signature ID: xxe-detect-01
Attack Type: XXE Injection
Signature Pattern: `<!ENTITY\s+%|\]\]>|SYSTEM\s+".+"|SYSTEM\s+'\w+:'`
Action: Block
- Apply the signature to the protection profile: Web Protection > Signature Rules > Apply to Policy.
Step 2: Protect Against Insecure File Uploads
- Enable File Upload Restrictions under File Upload Security:
Max File Size: 5MB
Allowed Extensions: .jpg, .png, .pdf
Action: Block and Log
- Add these settings to the relevant policy.
curl -X POST -d "<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM \"file:///etc/passwd\">]><foo>&xxe;</foo>" https://yourdomain.com/endpoint
If properly configured, FortiWeb will block the malicious XXE payload.
2. F5 Big-IP ASM: Protecting Against XXE and Insecure File Uploads
F5’s Advanced WAF can be configured to block security misconfigurations such as XXE and insecure file uploads.
Step 1: Create XXE Detection iRule
- Create a custom iRule to detect XXE patterns:
when HTTP_REQUEST {
if {[HTTP::payload] contains "ENTITY"} {
log local0. "XXE Attack Detected"
drop
}
}
- Attach the iRule to the relevant virtual server.
Step 2: Enable File Type Enforcement
Navigate to Security > Application Security > Policy > File Types.
Enable Strict File Upload Validation:
Allowed File Types: .jpg, .png, .txt
Maximum File Size: 10MB
Action: Block
curl -X POST --data-binary @malicious_file.xml https://yourdomain.com/upload
The iRule will block malicious uploads containing XXE attacks.
3. AWS WAF: Protecting Against XXE and Insecure File Uploads
AWS WAF can be configured using custom rules to detect and block XXE and insecure file uploads.
Step 1: Configure a Web ACL for XXE
In the AWS Console, navigate to AWS WAF > Web ACL.
Create a rule to block XXE payloads using regex patterns:
<!DOCTYPE\s+|\]\]>\s+|\&xxe;
- Set the action to Block.
Step 2: Secure File Uploads
- Use AWS Lambda@Edge with AWS WAF to filter file uploads based on type:
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
if not request['headers']['content-type'][0]['value'].startswith('image/'):
return {
'status': '403',
'body': 'File type not allowed.'
}
return request
- Deploy this Lambda function with AWS WAF.
aws wafv2 get-web-acl --name your-acl-name --scope REGIONAL --id your-acl-id
AWS WAF will now block the XXE and insecure file upload attempts.
4. Azure WAF: Defending Against XXE and File Upload Vulnerabilities
Azure WAF can block XXE and insecure file uploads through custom rules in the Azure Firewall Manager.
Step 1: Add a Custom WAF Rule for XXE
Navigate to Azure Front Door > WAF Policy > Custom Rules.
Add a rule to block XXE attempts:
Rule Name: Block-XXE
Match Condition: Request Body
Pattern: <!DOCTYPE|SYSTEM|ENTITY
Action: Block
Step 2: Protect File Uploads
In Azure Application Gateway WAF, add validation for file uploads.
Block specific content types and enforce size limits using custom rules.
az network waf-policy rule add --policy-name my-waf-policy --custom-rule block-xxe --priority 1 --rule-type Match
Azure WAF will enforce the virtual patch and block malicious payloads.
5. Cloudflare WAF: Virtual Patching for XXE and File Upload Defense
Cloudflare WAF allows for customizable firewall rules to block XXE and control file uploads.
Step 1: Create a Firewall Rule for XXE
In Cloudflare Dashboard, navigate to WAF > Firewall Rules > Create Rule.
Add a new rule to block XXE
Field: Body
Operator: contains
Value: <!DOCTYPE
Action: Block
Step 2: Secure File Uploads
- Enforce file upload restrictions by creating another rule:
Field: Content-Type
Operator: does not contain
Value: image/
Action: Block
curl -X POST -d "<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM \"file:///etc/passwd\">]><foo>&xxe;</foo>" https://yourdomain.com
Cloudflare WAF will detect and block XXE attempts.
6. OpenRASP: Runtime Application Self-Protection for XXE and Insecure File Uploads
OpenRASP works inside the application to detect and block malicious activity such as XXE or insecure file uploads in real time.
Step 1: Enable XXE Protection
- Modify the
rasp-conf.json
file to enable XXE detection:
"xxe": {
"enabled": true,
"action": "block"
}
Step 2: Enable File Upload Security
- In the same
rasp-conf.json
file, configure file upload protection:
"fileUpload": {
"enabled": true,
"maxFileSize": 5242880, # 5MB
"allowedExtensions": [".jpg", ".png", ".pdf"]
}
curl -X POST -F 'file=@malicious.xml' https://yourdomain.com/upload
OpenRASP will block the malicious file upload or XXE attack in real time.
Broken Access Control
Broken access control vulnerabilities, such as Insecure Direct Object Reference (IDOR) and function-level access control issues, pose a critical threat to web applications. Attackers can exploit these flaws to gain unauthorized access to resources or perform restricted actions. Virtual patching, implemented using Web Application Firewalls (WAFs) and Runtime Application Self-Protection (RASP) solutions, is an effective defense strategy when immediate source code fixes are not possible.
Below is a detailed approach to virtually patch broken access control vulnerabilities across multiple platforms like FortiWeb, F5, AWS WAF, Azure WAF, Cloudflare, and OpenRASP.
1. FortiWeb (Fortinet WAF)
FortiWeb offers advanced protection mechanisms, including custom signature-based virtual patches, to prevent access control vulnerabilities.
Example: Blocking IDOR with FortiWeb
Step 1: Create a Custom Signature
# Define a custom signature that matches unauthorized URL access or parameter tampering
config waf custom-signature
edit "idor_prevention"
set signature "GET /api/user/{ID} where {ID} should match the logged-in user"
set action block
end
Step 2: Apply the Signature to a Protected Policy
# Apply the custom signature to your WAF protection policy
config waf policy
edit "app_policy"
set custom-signature "idor_prevention"
end
This signature monitors requests to sensitive API endpoints and checks for improper access attempts, blocking any unauthorized actions.
2. F5 (BIG-IP ASM)
F5's BIG-IP ASM module provides detailed policies and customizable rules to prevent unauthorized access through URL parameter manipulation or direct object references.
Example: Implementing Virtual Patching for Function-Level Access Control
Step 1: Create a Parameter Protection Rule
Go to Security ›› Application Security ›› Parameters ›› Add New Parameter.
Create a rule to monitor a specific parameter that could be tampered with (e.g.,
user_id
).
Step 2: Enforce URL Access Rules
- Use Request Blocking ›› URL Access to configure role-based access control. For example, block users from accessing certain functions unless they have the appropriate privileges.
# Example blocking based on request violations
set asm policy parameter-value-enforcement "user_id"
add user_id_validation_rule "Only accessible by authorized users"
apply user_id_validation_rule "user_id" action deny
F5 allows integrating custom expressions or leveraging session data to enforce proper access control, ensuring IDOR exploits are mitigated.
3. AWS WAF
AWS WAF provides the flexibility to write custom rules to prevent unauthorized access to API endpoints or tampered requests.
Example: Block IDOR Exploit Using AWS WAF
Step 1: Create a Custom WAF Rule
Go to the AWS WAF Console, select Web ACLs, and choose your Web ACL.
Add a rule to block requests to sensitive endpoints unless the request matches a logged-in user's ID.
{
"Statement": {
"Effect": "Deny",
"Condition": {
"IpAddress": {
"aws:SourceIp": "BLOCKED_IP"
},
"StringEquals": {
"Request.User_Id": "Authenticated_User"
}
}
}
}
Step 2: Apply the Rule
- Attach the rule to your Web ACL to block any unauthorized requests to the specified resources.
4. Azure WAF (Application Gateway)
Azure WAF on Application Gateway enables virtual patching by creating custom rules that inspect HTTP headers, methods, and parameters.
Example: Virtual Patching for Function-Level Access
Step 1: Define a Custom Rule in Azure WAF
Go to the Azure portal, select Application Gateway ›› WAF Policies ›› Custom Rules.
Add a custom rule to block unauthorized actions based on user roles.
{
"RuleType": "Match",
"MatchConditions": [
{
"MatchVariables": [
{
"VariableName": "RequestHeader",
"Selector": "Authorization"
}
],
"Operator": "Equal",
"MatchValues": ["ROLE_ADMIN"]
}
],
"Action": "Block"
}
Step 2: Apply the WAF Policy
- Apply the custom rule to your application, enforcing access control for sensitive actions like
DELETE
,POST
, orPUT
.
5. Cloudflare WAF
Cloudflare’s WAF allows you to create custom firewall rules that block unauthorized access to certain parts of your application.
Example: Block Unauthorized Access to User Resources
Step 1: Create a WAF Rule in Cloudflare
Navigate to Firewall Rules in the Cloudflare dashboard.
Add a rule to block unauthorized access to sensitive endpoints.
# Block access to user profiles unless authenticated
if (http.request.uri.path contains "/user" and not http.request.headers["Authorization"] contains "Bearer") {
action = "block"
}
This rule blocks requests attempting to access user data unless the proper authorization token is present.
6. OpenRASP (Runtime Application Self-Protection)
OpenRASP directly monitors and intercepts runtime actions, providing virtual patching for access control vulnerabilities by analyzing in-app behavior.
Example: Preventing IDOR Using OpenRASP
Step 1: Define a Custom RASP Hook
- Create a custom rule to check the validity of object references before processing them.
{
"rules": [
{
"type": "request_parameter",
"name": "Validate ID in Request",
"desc": "Prevent unauthorized ID access",
"action": "block",
"condition": {
"parameter": "user_id",
"operator": "not_equals",
"value": "session.user_id"
}
}
]
}
Step 2: Enforce the Rule
- The RASP engine enforces this rule at runtime, ensuring that object references match the session user and preventing IDOR attacks.
Identification and Authentication Failures
Virtual patching for Identification and Authentication Failures is an essential defense strategy to protect against common vulnerabilities like credential stuffing or brute force attacks. Virtual patches use Web Application Firewalls (WAFs) to block malicious requests before they reach the application. Below, we’ll walk through defending against two attacks—credential stuffing and brute force—by setting up virtual patches on FortiWeb and Cloudflare.
1. Defending Against Credential Stuffing on FortiWeb
Credential stuffing occurs when attackers use a list of stolen credentials to log in. Virtual patching in FortiWeb can help by detecting and blocking excessive login attempts with invalid credentials.
Configuration:
To protect against credential stuffing:
- Enable brute-force detection: This feature tracks failed login attempts over a period of time and blocks access once a threshold is reached.
FortiWeb commands:
config server-policy
edit "web-login-policy"
config waf
set brute-force-prevention enable
set max-login-attempts 5
set block-period 600
end
next
end
This configuration:
Tracks login attempts and blocks the user after 5 invalid attempts.
Blocks the IP for 600 seconds (10 minutes).
This blocks credential stuffing attempts by preventing automated bots from trying multiple usernames and passwords in quick succession.
2. Defending Against Brute Force on Cloudflare
Brute force attacks involve trying many password combinations to break into an account. Using Cloudflare WAF, we can implement a virtual patch by creating rate-limiting rules to block repeated login attempts from a single IP.
Configuration:
To protect against brute force:
Set rate limits on login endpoints.
Challenge requests after a certain threshold is met.
Cloudflare dashboard steps:
Go to Security > WAF > Rate Limiting.
Create a new rate limit rule for the login URL (e.g.,
/login
).Set the rate limit to 10 requests per minute from a single IP.
Example rule:
Login Rate Limit Rule:
- URL: "/login"
- Methods: POST
- Requests per minute: 10
- Action: Block or Challenge
If the same IP sends more than 10 login attempts in a minute, Cloudflare will block or challenge them, effectively mitigating brute force attacks.
Explanation of Attack Coverage:
Credential Stuffing: FortiWeb’s virtual patch blocks credential stuffing by limiting login attempts from a single user. It prevents automated tools from testing large credential lists.
Brute Force: Cloudflare’s rate-limiting blocks brute force attacks by preventing too many login attempts from a single IP address within a short timeframe.
SSO
1. FortiWeb
FortiWeb provides capabilities to define custom rules that can prevent open redirect vulnerabilities by allowing only specified URLs.
- Creating a Custom Rule: To create a custom signature that detects open redirects and enforces a whitelist of allowed URLs:
config waf custom-signature
edit "OpenRedirectProtection"
set action block
set signature "http.request.uri.path contains \"/redirect\" and not http.request.uri.query contains \"allowed-url.com\""
set severity high
next
end
- Whitelist Configuration: Ensure the application allows redirection only to specified URLs:
config webapp firewall
edit "WebAppProtection"
set allow-http-redirect yes
set whitelist-url "https://allowed-url.com"
end
This configuration will block any redirect attempts to URLs not on the whitelist while logging these events.
2. F5 (BIG-IP)
F5’s ASM (Application Security Manager) allows for the creation of security policies that can effectively manage open redirect and postMessage attacks.
- Creating an ASM Policy: Set up a policy that checks for valid redirect URLs and blocks malicious attempts:
tmsh create security policy <policy-name> rules <rule-name> {
match "http.request.uri.path" {
string "redirect"
operator "contains"
}
action block
}
PostMessage Validation: To prevent postMessage misconfiguration, you can create an iRule to restrict messages to whitelisted domains:
when HTTP_REQUEST {
if { [HTTP::header "Origin"] ne "https://allowed-url.com" } {
log local0. "Blocked postMessage from unauthorized origin"
HTTP::respond 403
}
}
These configurations enforce strict rules around URL redirection and postMessage usage, ensuring only safe interactions occur.
3. AWS WAF
AWS WAF allows for creating Web ACLs to manage traffic effectively, helping to prevent open redirect and postMessage attacks.
- Web ACL Configuration: Create a Web ACL that includes a rule for open redirect attacks, allowing only whitelisted URLs:
aws wafv2 create-web-acl --name "OpenRedirectProtection" \
--scope "REGIONAL" --default-action Allow \
--rules file://open-redirect-rules.json --visibility-config SampleVisibilityConfig
Example JSON Rule (open-redirect-rules.json
):
{
"Name": "RedirectRule",
"Priority": 1,
"Statement": {
"ByteMatchStatement": {
"SearchString": "/redirect",
"FieldToMatch": { "UriPath": {} },
"TextTransformations": [{ "Priority": 0, "Type": "NONE" }],
"PositionalConstraint": "CONTAINS"
}
},
"Action": { "Block": {} },
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "RedirectRule"
}
}
This rule blocks any redirects to unauthorized URLs while logging attempts for monitoring.
4. Azure WAF
Azure WAF also supports custom rules to protect against open redirects and postMessage misconfigurations.
- Creating a Custom Rule: Define a rule that checks for a specific path to block any unauthorized redirects:
az network application-gateway waf-policy rule create \
--policy-name "WAFPolicy" --name "BlockOpenRedirect" \
--rule-type "MatchRule" --match-variables "RequestUri" \
--operator "Contains" --values "/redirect" --action Block --priority 1
- Whitelisting URLs: Ensure that only specific URLs can be accessed via redirects: \
az network application-gateway waf-policy set --policy-name "WAFPolicy" --whitelist-url "https://allowed-url.com"
This configuration ensures that Azure WAF blocks unauthorized redirects and monitors any blocked attempts.
5. Cloudflare
Cloudflare allows for granular control over traffic with its firewall rules, which can be configured to block open redirects and misconfigured postMessage interactions.
- Creating a Firewall Rule:
curl -X POST "https://api.cloudflare.com/client/v4/zones/<zone_id>/firewall/rules" \
-H "X-Auth-Email: <email>" \
-H "X-Auth-Key: <api_key>" \
-H "Content-Type: application/json" \
--data '{
"action": "block",
"filter": {
"expression": "(http.request.uri.path contains \"/redirect\") and (not http.request.uri.path matches \"^https://allowed-url.com\")"
},
"description": "Block open redirect attacks"
}'
This rule blocks redirects to any URLs not on the whitelist, ensuring only safe URLs are processed.
6. OpenRASP
OpenRASP integrates directly with applications, allowing it to monitor and protect against open redirects and postMessage misconfigurations at runtime.
- RASP Rule for Open Redirect Protection:
{
"name": "OpenRedirectProtection",
"description": "Block open redirect attempts",
"action": "block",
"condition": {
"type": "OPEN_REDIRECT",
"pattern": ["/redirect"],
"whitelist": ["https://allowed-url.com"]
}
}
- Configuration: Add this rule to the OpenRASP configuration to ensure that redirects only occur to the specified URL:
openrasp build --rules ./open-redirect-rules.json --output ./output.json
This rule blocks attempts to redirect to unauthorized URLs, actively preventing potential attacks.
Cross Site Scripting
Virtual patching is a critical strategy in defending against Cross-Site Scripting (XSS) and DOM Clobbering attacks. By implementing virtual patches through various Web Application Firewalls (WAF) and security solutions, organizations can effectively mitigate vulnerabilities without altering the application code. Below are examples of how to deploy virtual patching against XSS and DOM Clobbering patterns in FortiWeb, F5, AWS, Azure, Cloudflare, and OpenRASP.
1. FortiWeb
FortiWeb provides a powerful platform for protecting against XSS attacks through custom signatures and security policies. Here’s how to implement virtual patching for XSS and DOM Clobbering.
- Creating a Custom Signature for XSS Protection:
config waf custom-signature
edit "Custom_XSS_Protection"
set action block
set signature "pattern-to-detect-xss"
set severity high
next
end
Enabling XSS Protection in the Security Policy:
config web-app
edit "my_web_app"
set xss-protection enable
set action block
set log enable
end
With this configuration, FortiWeb will block requests containing potential XSS vectors and log any attempts for further analysis.
2. F5 (BIG-IP)
F5’s Advanced WAF allows for the implementation of virtual patches using iRules and ASM (Application Security Manager) policies to protect against XSS attacks.
- iRule for Blocking XSS Attempts:
when HTTP_REQUEST {
set suspicious_user_agent [HTTP::header "User-Agent"]
if { $suspicious_user_agent contains "XSS" } {
log local0. "XSS attempt detected from [IP::client_addr]"
HTTP::respond 403
}
}
Creating an ASM Policy to Block XSS:
tmsh modify security policy <policy-name> waf-violations add { xss { action block } }
This setup will effectively monitor for XSS attempts and block them, while also logging suspicious activities.
3. AWS WAF
AWS WAF allows you to create Web ACLs with rules specifically designed to detect and block XSS patterns.
- Creating a Web ACL with XSS Protection:
aws wafv2 create-web-acl --name "XSSProtectionACL" \
--scope "REGIONAL" --default-action Allow \
--rules file://xss-rules.json --visibility-config SampleVisibilityConfig
Sample Rule for Blocking XSS (xss-rules.json
):
{
"Name": "XSSDefenseRule",
"Priority": 1,
"Statement": {
"ByteMatchStatement": {
"SearchString": "<script>",
"FieldToMatch": { "Body": {} },
"TextTransformations": [
{ "Priority": 0, "Type": "NONE" }
]
}
},
"Action": { "Block": {} },
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "XSSDefenseRule"
}
}
This rule will block any request containing the <script>
tag, thereby mitigating XSS vulnerabilities.
4. Azure WAF
Azure WAF enables the implementation of custom rules to detect and mitigate XSS attacks effectively.
- Creating a Custom Rule for XSS:
az network application-gateway waf-policy rule create \
--policy-name "XSSWAFPolicy" --name "BlockXSS" --rule-type "MatchRule" \
--match-variables "RequestBody" --operator "Contains" --values "<script>" \
--action Block --priority 1
Enable Logging for XSS Attempts:
az network application-gateway waf-policy set --enabled true --log-config {cloudwatch=true}
This approach ensures that XSS attempts are blocked at the WAF level and logged for further investigation.
5. Cloudflare
Cloudflare allows you to create firewall rules to prevent XSS and DOM Clobbering attacks by filtering out malicious input.
- Cloudflare Firewall Rule for XSS:
curl -X POST "https://api.cloudflare.com/client/v4/zones/<zone_id>/firewall/rules" \
-H "X-Auth-Email: <email>" \
-H "X-Auth-Key: <api_key>" \
-H "Content-Type: application/json" \
--data '{
"action": "block",
"filter": {
"expression": "(http.request.body contains \"<script>\")"
},
"description": "Block XSS attacks"
}'
This rule ensures that any requests containing <script>
tags are blocked, thereby preventing XSS exploits.
6. OpenRASP
OpenRASP offers runtime protection by embedding itself into applications to detect and prevent XSS and DOM Clobbering attacks.
- RASP Rule for XSS Protection:
{
"name": "XSS Protection",
"description": "Block XSS attempts",
"action": "block",
"condition": {
"type": "XSS",
"pattern": ["<script>", "javascript:"]
}
}
Configuration Command:
openrasp build --rules ./xss-rules.json --output ./output.json
This configuration will enable OpenRASP to actively monitor and block malicious XSS attempts in real-time.
Subscribe to my newsletter
Read articles from Reza Rashidi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by