|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2020 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing a check for not auto escaping in jinja2. |
|
8 """ |
|
9 |
|
10 # |
|
11 # This is a modified version of the one found in the bandit package. |
|
12 # |
|
13 # Original Copyright 2014 Hewlett-Packard Development Company, L.P. |
|
14 # |
|
15 # SPDX-License-Identifier: Apache-2.0 |
|
16 # |
|
17 |
|
18 import ast |
|
19 |
|
20 |
|
21 def getChecks(): |
|
22 """ |
|
23 Public method to get a dictionary with checks handled by this module. |
|
24 |
|
25 @return dictionary containing checker lists containing checker function and |
|
26 list of codes |
|
27 @rtype dict |
|
28 """ |
|
29 return { |
|
30 "Call": [ |
|
31 (checkJinja2Autoescape, ("S701",)), |
|
32 ], |
|
33 } |
|
34 |
|
35 |
|
36 def checkJinja2Autoescape(reportError, context, config): |
|
37 """ |
|
38 Function to check for not auto escaping in jinja2. |
|
39 |
|
40 @param reportError function to be used to report errors |
|
41 @type func |
|
42 @param context security context object |
|
43 @type SecurityContext |
|
44 @param config dictionary with configuration data |
|
45 @type dict |
|
46 """ |
|
47 if isinstance(context.callFunctionNameQual, str): |
|
48 qualnameList = context.callFunctionNameQual.split('.') |
|
49 func = qualnameList[-1] |
|
50 if 'jinja2' in qualnameList and func == 'Environment': |
|
51 for node in ast.walk(context.node): |
|
52 if isinstance(node, ast.keyword): |
|
53 # definite autoescape = False |
|
54 if ( |
|
55 getattr(node, 'arg', None) == 'autoescape' and |
|
56 ( |
|
57 getattr(node.value, 'id', None) == 'False' or |
|
58 getattr(node.value, 'value', None) is False |
|
59 ) |
|
60 ): |
|
61 reportError( |
|
62 context.node.lineno - 1, |
|
63 context.node.col_offset, |
|
64 "S701.1", |
|
65 "H", |
|
66 "H", |
|
67 ) |
|
68 return |
|
69 |
|
70 # found autoescape |
|
71 if getattr(node, 'arg', None) == 'autoescape': |
|
72 value = getattr(node, 'value', None) |
|
73 if ( |
|
74 getattr(value, 'id', None) == 'True' or |
|
75 getattr(value, 'value', None) is True |
|
76 ): |
|
77 return |
|
78 |
|
79 # Check if select_autoescape function is used. |
|
80 elif ( |
|
81 isinstance(value, ast.Call) and |
|
82 (getattr(value.func, 'id', None) == |
|
83 'select_autoescape') |
|
84 ): |
|
85 return |
|
86 |
|
87 else: |
|
88 reportError( |
|
89 context.node.lineno - 1, |
|
90 context.node.col_offset, |
|
91 "S701.1", |
|
92 "H", |
|
93 "M", |
|
94 ) |
|
95 return |
|
96 |
|
97 # We haven't found a keyword named autoescape, indicating default |
|
98 # behavior |
|
99 reportError( |
|
100 context.node.lineno - 1, |
|
101 context.node.col_offset, |
|
102 "S701.2", |
|
103 "H", |
|
104 "H", |
|
105 ) |