Skip to content

Commit eaf927a

Browse files
committed
Inject Content-Security-Policy header into index.html to protect against external scripts
1 parent ccb101c commit eaf927a

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/qwc2_viewer.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fnmatch
33
import os
44
import requests
5+
import secrets
56
import tempfile
67
from urllib.parse import urlparse, urlunparse, urlencode, urljoin, parse_qsl
78
from xml.etree import ElementTree
@@ -204,7 +205,16 @@ def qwc2_index(self, identity, params, request_url):
204205
# Inject CSRF token
205206
token = (get_jwt() or {}).get("csrf")
206207
if token:
207-
viewer_index = viewer_index.replace('</head>', '<meta name="csrf-token" content="%s" />\n</head>' % token)
208+
viewer_index = viewer_index.replace('<head>', '<head>\n<meta name="csrf-token" content="%s" />' % token)
209+
210+
# Inject CSP header and modify script tags
211+
nonce = secrets.token_urlsafe()
212+
csp = "; ".join([
213+
"script-src 'nonce-%s' 'strict-dynamic'" % nonce,
214+
# "style-src 'nonce-%s'" % nonce # TODO
215+
])
216+
viewer_index = viewer_index.replace('<head>', '<head>\n<meta http-equiv="Content-Security-Policy" content="%s">' % csp)
217+
viewer_index = viewer_index.replace('<script ', '<script nonce="%s" ' % nonce)
208218

209219
return viewer_index
210220

0 commit comments

Comments
 (0)