Skip to content

Commit

Permalink
Add simple clickjacking prevention
Browse files Browse the repository at this point in the history
Support X-Frame-Options with a default of SAMEORIGIN.
  • Loading branch information
hmpf committed Feb 29, 2024
1 parent 6db0a3f commit 6e2d46d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
5 changes: 4 additions & 1 deletion python/nav/django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@

# Middleware
MIDDLEWARE = (
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'nav.web.auth.middleware.AuthenticationMiddleware',
Expand Down Expand Up @@ -261,12 +262,14 @@
# Configured in etc/webfront/webfront.conf:
# [security]
# needs_tls = yes
# frames_allow = self

SECURE_BROWSER_XSS_FILTER = True # Does no harm

_websecurity_config = WebSecurityConfigParser()
_needs_tls = bool(_websecurity_config.getboolean('security', 'needs_tls'))
_needs_tls = bool(_websecurity_config.getboolean('needs_tls'))
SESSION_COOKIE_SECURE = _needs_tls
X_FRAME_OPTIONS = _websecurity_config.get_x_frame_options()

# Hack for hackers to use features like debug_toolbar etc.
# https://code.djangoproject.com/wiki/SplitSettings (Rob Golding's method)
Expand Down
20 changes: 18 additions & 2 deletions python/nav/web/security.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
from pathlib import Path

from nav.config import NAVConfigParser
from nav.config import NavConfigParserDefaultSection


class WebSecurityConfigParser(NAVConfigParser):
class WebSecurityConfigParser(NavConfigParserDefaultSection):
SECTION = "security"
DEFAULT_CONFIG_FILES = [str(Path('webfront') / 'webfront.conf')]
DEFAULT_CONFIG = u"""
[security]
needs_tls=no
allow_frames=self
"""
FRAMES_OPTION = 'allow_frames'
FRAMES_DEFAULT = 'self'

def __init__(self):
super().__init__(self.SECTION)

# clickjacking-settings

def get_x_frame_options(self):
"Translate CSP frame ancestors to the old X-Frame-Options header"
frames_flag = self.get(self.FRAMES_OPTION) or self.FRAMES_DEFAULT
if frames_flag == 'none':
return 'DENY'

Check warning on line 26 in python/nav/web/security.py

View check run for this annotation

Codecov / codecov/patch

python/nav/web/security.py#L26

Added line #L26 was not covered by tests
return 'SAMEORIGIN'

0 comments on commit 6e2d46d

Please sign in to comment.