User Tools

Site Tools


wiki:content_security_policy_report_uri_endpoint_python

Content security policy report uri endpoint in python

The content policy can also be enforced in app code. The below is for using the web server to send appropriate headers.

This assumes that the python app will run on the same server where the web server is.

The content policy is set up only to send warnings it will not block anything. Use the directive Content-Security-Policy to actually enforce it. But TEST FIRST!

Setup

apt install python3-venv
pip install Flask
source venv/bin/activate

Add the webserver configuration

apache:

<VirtualHost *:443>
  ...
  ProxyPass /csp http://localhost:5000/
  ...
  Header set Content-Security-Policy-Report-Only "default-src 'self';script-src 'unsafe-inline' 'unsafe-eval';report-uri csp;"
  ...

nginx:

  ...
  location / {
  ...
  add_header Content-Security-Policy-Report-Only "default-src 'self';script-src 'unsafe-inline' 'unsafe-eval';report-uri csp;";
  ...

Create json consumer that the CSP will send to

csp.py
from flask import Flask, request
 
app = Flask(__name__)
 
@app.route("/", methods=['GET', 'POST'])
def hello_world():
    # we need to force the detection of csp payload as json
    content = request.get_json(force=True)
    print(f"Got json {content}")
    if content:
        return content
    else:
        return "Nothing received"

Export name:

export FLASK_APP=csp

and run:

flask run

You should now get the printed json from CSP when you refresh your website page.

Tested on

  • Debian 10.11
  • Ubuntu 20.04.3

See also

References

wiki/content_security_policy_report_uri_endpoint_python.txt · Last modified: 2021/11/12 13:27 by antisa

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki