CVE-2024-3400: PAN-OS Command Injection Vulnerability in GlobalProtect Gateway. Learn More

CVE-2024-3400: PAN-OS Command Injection Vulnerability in GlobalProtect Gateway. Learn More

Services
Capture
Managed Detection & Response

Eliminate active threats with 24/7 threat detection, investigation, and response.

twi-managed-portal-color
Co-Managed SOC (SIEM)

Maximize your SIEM investment, stop alert fatigue, and enhance your team with hybrid security operations support.

twi-briefcase-color-svg
Advisory & Diagnostics

Advance your cybersecurity program and get expert guidance where you need it most.

tw-laptop-data
Penetration Testing

Test your physical locations and IT infrastructure to shore up weaknesses before exploitation.

twi-database-color-svg
Database Security

Prevent unauthorized access and exceed compliance requirements.

twi-email-color-svg
Email Security

Stop email threats others miss and secure your organization against the #1 ransomware attack vector.

tw-officer
Digital Forensics & Incident Response

Prepare for the inevitable with 24/7 global breach response in-region and available on-site.

tw-network
Firewall & Technology Management

Mitigate risk of a cyberattack with 24/7 incident and health monitoring and the latest threat intelligence.

Solutions
BY TOPIC
Offensive Security
Solutions to maximize your security ROI
Microsoft Exchange Server Attacks
Stay protected against emerging threats
Rapidly Secure New Environments
Security for rapid response situations
Securing the Cloud
Safely navigate and stay protected
Securing the IoT Landscape
Test, monitor and secure network objects
Why Trustwave
About Us
Awards and Accolades
Trustwave SpiderLabs Team
Trustwave Fusion Security Operations Platform
Trustwave Security Colony
Partners
Technology Alliance Partners
Key alliances who align and support our ecosystem of security offerings
Trustwave PartnerOne Program
Join forces with Trustwave to protect against the most advance cybersecurity threats
SpiderLabs Blog

ModSecurity Advanced Topic of the Week: Integrating Content Security Policy (CSP)

Mozilla's Content Security Policy (CSP)

Mozilla has developed a fantastic security capability into the FireFox web browser called Content Security Policy (CSP) which they describe as:

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware.

CSP is designed to be fully backward compatible; browsers that don't support it still work with servers that implement it, and vice-versa. Browsers that don't support CSP simply ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. If the site doesn't offer the CSP header, browsers likewise use the standard same-origin policy.

Enabling CSP is as easy as configuring your web server to return the X-Content-Security-Policy HTTP header. See Using Content Security Policy for details on how to configure and enable CSP.

Note: For security reasons, you can't use the <meta> element to configure the X-Content-Security-Policy header.

Mitigating cross site scripting

The primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser's trust of the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from.

CSP makes it possible for server administrators to reduce or eliminate the vectors by which XSS can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those whitelisted domains, ignoring all other script (including inline scripts and event-handling HTML attributes).

As an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution

To summarize - web site owners can include X-Content-Security-Policy response headers sent to FireFox clients which will instruct the browser which html data is is allowed to process and from which sources.

 

CSP Development

Before actually implementing any CSP enforcement, you must first carefully review all CSP directives to develop a policy that is appropriate for your site. Some examples directives include:

  • script-src - which specifies valid Javascript sources
  • img-src - which defines what sources may load images
  • frame-src - which specifies valid sources for framing content

 

Get the Right Team

Developing a proper CSP for your site is actually quite similar to the process that organizations should go through when implementing a Web Application Firewall (WAF) into their environment. It is important to have input from all applicable parties including business owners, developers and operational staff. The OWASP Germany Chapter actually created an outstanding document entitled - Best Practices: Use of Web Application Firewalls. In it, they outlined a number of different people that should be involved with the configuration of a WAF including:

8.3.1 WAF platform manager

Tasks:

  • Planning of the operational architecture of the WAF
  • Responsiblity for operation and support of the WAF, including capacity planning
  • Allocation of URLs to individual applications
  • Patch and version management of the WAF
  • Management and administration of the application manager WAF

Knowledge:

  • Knowledge of the WAF, its operation, administration and the authorisation concept

8.3.2 WAF application manager (per application)

Tasks:

  • Implementation and maintainance of the WAF configuration specific to the application
  • Monitoring and analysis of the log files (at least on the second level)
  • Contact for error messages, in particular false positives analysis in collaboration with the application manager
  • Close cooperation with the WAF application managers and platform managers
  • Test of WAF functionalities for the application, especially when deploying new versions of the application

Knowledge:

  • In-depth knowledge of the WAF configuration in relation to application-specific security mechanism
  • Very good knowledge of the behaviour of the application, in particular input, output, uploads, downloads, character sets, etc.

8.3.3 Application manager

  • Operation or development of the application to be protected
  • Knowledge of the application architecture and the input fields, provides these to the WAF application manager.

This is the exact same personnel that should be involved with developing an appropriate CSP for your site.

 

CSP Implementation using ModSecurity

In the latest SVN trunk version of the OWASP Core Rule Set, we have posted some updates that allow a ModSecurity WAF admin to implement CSP policies and monitor for violation alerts.

 

Defining the CSP settings

In the latest SVN trunk modsecurity_crs_10_config.conf.example file, there are new CSP configuration settings that can be activated and adjusted to suit your CSP requirements.

 

#
# -=[ Content Security Policy (CSP) Settings ]=-
#
# The purpose of these settings is to send CSP response headers to
# Mozilla FireFox users so that you can enforce how dynamic content
# is used. CSP usage helps to prevent XSS attacks against your users.
#  
# Reference Link:
#
#	https://developer.mozilla.org/en/Security/CSP
#
# Define the following CSP settings for your site:
#
# - Report-Only mode
#	https://wiki.mozilla.org/Security/CSP/Specification#Report-Only_mode	
#
# - Allow
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#allow
#
# - img-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#img-src
#
# - media-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#media-src
#
# - script-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#script-src
#
# - object-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#object-src
#
# - frame-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#frame-src
#
# - xhr-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#xhr-src
#
# - frame-ancestors
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#frame-ancestors
#
# - style-src
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#style-src
#
# - report-uri
#	https://developer.mozilla.org/en/Security/CSP/CSP_policy_directives#report-uri		  
#
# Uncomment this SecAction line if you want use CSP enforcement.
# You need to set the appropriate directives and settings for your site/domain and
# and activate the CSP file in the experimental_rules directory.
# 
SecAction "phase:1,t:none,nolog,pass, \
setvar:tx.csp_report_only=1, \
setvar:tx.csp_report_uri=/csp_violation_report, \
setenv:'csp_policy=allow \'self\'; img-src *.example.com; media-src *.example.com; style-src *.example.com; frame-ancestors *.example.com; script-src *.example.com; report-uri %{tx.csp_report_uri}'"

 

CSP Enforcement Settings

The latest SVN trunk version of CRS has the new modsecurity_crs_42_csp_enforcement.conf file that controls both issuing CSP Response Headers to the appropriate clients and also generates ModSecurity Alerts when FireFox clients issue CSP Violation Report Requests.

 

#
# -=[ Content Security Policy (CSP) Settings ]=-
#
# The purpose of these settings is to send CSP response headers to
# Mozilla FireFox users so that you can enforce how dynamic content
# is used. CSP usage helps to prevent XSS attacks against your users.
#  
# Reference Link:
#
#       https://developer.mozilla.org/en/Security/CSP
#

#
# If this is a CSP Violation Report Request, we need to enable request
# body population of the REQUEST_BODY variable. This is not done by
# default since the request body content-type is JSON.
#
SecRule REQUEST_FILENAME "@streq %{tx.csp_report_uri}" "phase:1,t:none,nolog,pass,ctl:forceRequestBodyVariable=On"

#
# Check the REQUEST_BODY for CSP Violation Report data and generate an Alert
#
SecRule REQUEST_BODY "({\"csp-report\":.*blocked-uri\":\"(.*?)\".*violated-directive\":\"(.*)\")" "phase:2,id:'960001',capture,t:none,log,pass,msg:'Content Security Policy (CSP) Violation',logdata:'blocked-uri:%{tx.2} violated-directive:%{tx.3}',tag:'OWASP_AppSensor/RP3',tag:'https://www.owasp.org/index.php/AppSensor_DetectionPoints#RP3:_Suspicious_Client-Side_Behavior'"

#
# Check the User-Agent string for FireFox users and then set an ENV var
# to tell Apache which CSP header policy to use.
#
SecRule REQUEST_HEADERS:User-Agent "(?i:mozilla.*firefox)" "phase:3,id:'960002',t:none,nolog,pass,chain"
	SecRule TX:CSP_REPORT_ONLY "@eq 1" "setenv:firefox_client-csp_report_only=1"

SecRule REQUEST_HEADERS:User-Agent "(?i:mozilla.*firefox)" "phase:3,id:'960003',t:none,nolog,pass,chain"
        SecRule TX:CSP_REPORT_ONLY "@eq 0" "setenv:firefox_client-csp_enforce=1"

#
# Set the appropriate CSP Policy Header for FireFox clients
#
Header set X-Content-Security-Policy-Report-Only "%{csp_policy}e" env=firefox_client-csp_report_only
Header set X-Content-Security-Policy "%{csp_policy}e" env=firefox_client-csp_enforce

 

Field Testing CSP Enforcement

It is important that any new web security capabilities are carefully tested and phased in as to not cause undue interrupts to non-malicious users or otherwise interfere with the browsing experience. We recommend two steps.

 

Use Report-Only Mode

Make sure to initially use the X-Content-Security-Policy-Report-Only response header. This ensures that the new settings will not initiate any blocking but allows FireFox to report back any violations to your site.

 

Choose Selective Targets

With ModSecurity, it is possible to only send the CSP response headers to select clients. For instance, you could adjust the CSP rules to only issue the CSP response headers for certain IP addresses:

 

SecRule REQUEST_HEADERS:User-Agent "(?i:mozilla.*firefox)" "phase:3,id:'960002',t:none,nolog,pass,chain"
	SecRule TX:CSP_REPORT_ONLY "@eq 1" "chain"
             SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" "setenv:firefox_client-csp_report_only=1"

 

The response headers being sent to a test client would look something like this:

 

HTTP/1.1 200 OK
Date: Tue, 12 Apr 2011 22:12:14 GMT
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.12 OpenSSL/0.9.8l DAV/2
Last-Modified: Sat, 20 Nov 2004 20:16:24 GMT
ETag: "df86f-2c-3e9564c23b600"
Accept-Ranges: bytes
Content-Length: 44
X-Content-Security-Policy-Report-Only: allow 'self'; img-src *.example.com; media-src *.example.com; style-src *.example.com; frame-ancestors *.example.com; script-src *.example.com; report-uri /csp_violation_report
Content-Type: text/html

 

Example Alerts

Here is an example alert generated when a rogue iframe was injected in my site that was running these CSP settings:

 

[Tue Apr 12 17:51:26 2011] [error] [client 194.030.232.180] ModSecurity: Warning. Pattern match "({\\"csp-report\\":.*blocked-uri\\":\\"(.*?)\\".*violated-directive\\":\\"(.*)\\")" at REQUEST_BODY. 
[file "/usr/local/apache/conf/crs/base_rules/modsecurity_crs_56_csp_policy.conf"] [line "25"] [id "960001"] 
[msg "Content Security Policy (CSP) Violation"] 
[data "blocked-uri:http://videoonlinefree.co.cc/hck violated-directive:allow http://www.example.com"] [tag "OWASP_AppSensor/RP3"] 
[tag "https://www.owasp.org/index.php/AppSensor_DetectionPoints#RP3:_Suspicious_Client-Side_Behavior"] [hostname "www.example.com"] [uri "/csp_violation_report"] [unique_id "TaTJXsCoqAEAAXE6IOAAAAAA"]

 

Notice that this ModSecurity CSP rule was able to parse the JSON violation report request payload and display reason the violation.

 

OWASP AppSensor Mapping

 

Notice that the ModSecurity alert has also been cross-referenced with the OWASP AppSensor Project and points to the RP3: Suspicious Client Behavior Detection Point.

 

id

RP3

title

RP3 Suspicious Client-Side Behavior

category

Reputation

description

The application receives a report of client-side security policy exceptions

consideration

Take care this information does not contribute to greater false positives.

examples

Example 1: An internal corporate intranet application detects use of a non-standard workstation configuration (e.g. using JavaScript font or plugin detection see SE6). An alert is raised for further investigation.

Example 2: An online banking application receives details of suspicious client-side behaviour that would not be expected in normal application use, via a Firefox Content Security Policyviolation report. The application increases logging for the user, and decreases the monetary limit at which the user's payments require manual authorisation by bank staff.

Example 3: The HTTP user agent header value does not agree with other indicators (e.g. using JavaScript detection as in example 1 above). Reference.

 

Audit Log Example

Here is section of the ModSecurity Audit log file showing the actual CSP Violation Report request:

 

--6292d925-B--
POST /csp_violation_report HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0) Gecko/20100101 Firefox/4.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/json; charset=UTF-8
Content-Length: 603
Pragma: no-cache
Cache-Control: no-cache

--6292d925-C--
{"csp-report":{"request":"POST http://www.example.com/cgi-bin/foo.php
 HTTP/1.1","request-headers":"Host: www.example.com\u000aUser-Agent: Mozilla/5.0 
(Macintosh; Intel Mac OS X 10.6; rv:2.0) Gecko/20100101 Firefox/4.0\u000aAccept: 
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\u000aAccept-Language: 
en-us,en;q=0.5\u000aAccept-Encoding: gzip, deflate\u000aAccept-Charset: ISO-8859-1,utf-
8;q=0.7,*;q=0.7\u000aKeep-Alive: 115\u000aConnection: keep-alive\u000aReferer: 
http://www.example.com/upload.php\u000a","blocked-
uri":"http://videoonlinefree.co.cc/hck","violated-directive":"allow 
http://www.example.com"}}

 

Reviewing CSP Alerts

While the CSP settings are in a reporting only mode, ModSecurity Admins should review all CSP alerts and verify if the CSP enforcement settings need to be adjusted. For example, there may be image files legitimately being served from a sub-domain or 3rd party site that will need to be added. With these settings in place, it will provide an extra layer of security for FireFox 4 users who are using your application.

Latest SpiderLabs Blogs

Fake Dialog Boxes to Make Malware More Convincing

Let’s explore how SpiderLabs created and incorporated user prompts, specifically Windows dialog boxes into its malware loader to make it more convincing to phishing targets during a Red Team...

Read More

The Secret Cipher: Modern Data Loss Prevention Solutions

This is Part 7 in my ongoing project to cover 30 cybersecurity topics in 30 weekly blog posts. The full series can be found here. Far too many organizations place Data Loss Prevention (DLP) and Data...

Read More

CVE-2024-3400: PAN-OS Command Injection Vulnerability in GlobalProtect Gateway

Overview A command injection vulnerability has been discovered in the GlobalProtect feature within Palo Alto Networks PAN-OS software for specific versions that have distinct feature configurations...

Read More