[debug-toolbar/display_source_code/security] add security mechanism to only read whitelisted files

Closes #17256791

authorLaurent Peuch <cortex@worlddomination.be>
changeset3a38f779bed5
branchdefault
phasepublic
hiddenno
parent revision#a2b8c201727f [debug-toolbar/display_source_code] add helper to render link to source file
child revision#e6bf15a69ea0 [debug-toolbar/display_source_code] add function to generate html link to source code
files modified by this revision
cubicweb/pyramid/debug_source_code.py
# HG changeset patch
# User Laurent Peuch <cortex@worlddomination.be>
# Date 1569472073 -7200
# Thu Sep 26 06:27:53 2019 +0200
# Node ID 3a38f779bed5fa88eb8ae65dea07ca194783f572
# Parent a2b8c201727f27c33ba2804617ac4c0193f9080b
[debug-toolbar/display_source_code/security] add security mechanism to only read whitelisted files

Closes #17256791

diff --git a/cubicweb/pyramid/debug_source_code.py b/cubicweb/pyramid/debug_source_code.py
@@ -31,10 +31,12 @@
1  from cubicweb.misc.source_highlight import highlight_html, generate_css, has_pygments
2 
3 
4  DEBUG_DISPLAY_SOURCE_CODE_PATH = '_debug_display_source_code'
5 
6 +FILES_WHITE_LIST = set()
7 +
8 
9  def source_code_url(object_or_class):
10      if object_or_class is None:
11          return ""
12 
@@ -45,10 +47,12 @@
13          file_path = inspect.getsourcefile(object_or_class)
14      except TypeError:
15          logging.debug("Error while trying to source code of '%s'" % object_or_class)
16          return ""
17 
18 +    FILES_WHITE_LIST.add(file_path)
19 +
20      try:
21          source_code, line = inspect.getsourcelines(object_or_class)
22      except OSError:  # when we couldn't read the source code/line
23          return '<a href="../%s?file=%s" target="_blank">&lt;&gt;</a>' % (
24              DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path
@@ -79,10 +83,14 @@
25      source_code_file = request.params["file"]
26 
27      if not os.path.exists(source_code_file):
28          return Response("Error: file '%s' doesn't exist on the filesystem." % source_code_file)
29 
30 +    # security
31 +    if source_code_file not in FILES_WHITE_LIST:
32 +        return Response("Error: access to file is not authorized")
33 +
34      try:
35          content = open(source_code_file, "r").read()
36      except Exception as e:
37          return Response("Error: while opening file '%s' got the error: %s" % (source_code_file, e))
38