|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2020 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing checks for insecure except blocks. |
|
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 from Security.SecurityDefaults import SecurityDefaults |
|
21 |
|
22 |
|
23 def getChecks(): |
|
24 """ |
|
25 Public method to get a dictionary with checks handled by this module. |
|
26 |
|
27 @return dictionary containing checker lists containing checker function and |
|
28 list of codes |
|
29 @rtype dict |
|
30 """ |
|
31 return { |
|
32 "ExceptHandler": [ |
|
33 (checkTryExceptPass, ("S110",)), |
|
34 (checkTryExceptContinue, ("S112",)), |
|
35 ], |
|
36 } |
|
37 |
|
38 |
|
39 def checkTryExceptPass(reportError, context, config): |
|
40 """ |
|
41 Function to check for a pass in the except block. |
|
42 |
|
43 @param reportError function to be used to report errors |
|
44 @type func |
|
45 @param context security context object |
|
46 @type SecurityContext |
|
47 @param config dictionary with configuration data |
|
48 @type dict |
|
49 """ |
|
50 if config and "check_typed_exception" in config: |
|
51 checkTypedException = config["check_typed_exception"] |
|
52 else: |
|
53 checkTypedException = SecurityDefaults["check_typed_exception"] |
|
54 |
|
55 node = context.node |
|
56 if len(node.body) == 1: |
|
57 if ( |
|
58 not checkTypedException and |
|
59 node.type is not None and |
|
60 getattr(node.type, 'id', None) != 'Exception' |
|
61 ): |
|
62 return |
|
63 |
|
64 if isinstance(node.body[0], ast.Pass): |
|
65 reportError( |
|
66 context.node.lineno - 1, |
|
67 context.node.col_offset, |
|
68 "S110", |
|
69 "L", |
|
70 "H", |
|
71 ) |
|
72 |
|
73 |
|
74 def checkTryExceptContinue(reportError, context, config): |
|
75 """ |
|
76 Function to check for a continue in the except block. |
|
77 |
|
78 @param reportError function to be used to report errors |
|
79 @type func |
|
80 @param context security context object |
|
81 @type SecurityContext |
|
82 @param config dictionary with configuration data |
|
83 @type dict |
|
84 """ |
|
85 if config and "check_typed_exception" in config: |
|
86 checkTypedException = config["check_typed_exception"] |
|
87 else: |
|
88 checkTypedException = SecurityDefaults["check_typed_exception"] |
|
89 |
|
90 node = context.node |
|
91 if len(node.body) == 1: |
|
92 if ( |
|
93 not checkTypedException and |
|
94 node.type is not None and |
|
95 getattr(node.type, 'id', None) != 'Exception' |
|
96 ): |
|
97 return |
|
98 |
|
99 if isinstance(node.body[0], ast.Continue): |
|
100 reportError( |
|
101 context.node.lineno - 1, |
|
102 context.node.col_offset, |
|
103 "S112", |
|
104 "L", |
|
105 "H", |
|
106 ) |