Terarea  2
The automation project
Loading...
Searching...
No Matches
sql_injection.py
Go to the documentation of this file.
1"""
2 EPITECH PROJECT, 2022
3 Desktop_pet (Workspace)
4 File description:
5 injection.py
6
7 The file un charge of checking if an injection is attempted with the open database
8"""
9
10import base64
11from typing import Union, List
12
13from display_tty import Disp, TOML_CONF, SAVE_TO_FILE, FILE_NAME
14
15
17 """ Check if an sql injection is present """
18
19 def __init__(self, error: int = 84, success: int = 0, debug: bool = False) -> None:
20 # ---------------------------- Status codes ----------------------------
21 self.debug: bool = debug
22 self.error: int = error
23 self.success: int = success
24 # ---------------------------- Logging data ----------------------------
25 self.disp: Disp = Disp(
26 TOML_CONF,
27 SAVE_TO_FILE,
28 FILE_NAME,
29 self.debug,
30 logger=self.__class__.__name__
31 )
32 # ------------------ Injection checking related data ------------------
33 self.injection_err: int = (-1)
34 self.injection_message: str = "Injection attempt detected"
35 self.symbolssymbols: List[str] = [';', '--', '/*', '*/']
36 self.keywordskeywords: List[str] = [
37 'SELECT', 'INSERT', 'UPDATE', 'DELETE',
38 'DROP', 'CREATE', 'ALTER', 'TABLE', 'UNION', 'JOIN', 'WHERE'
39 ]
40 self.command: List[str] = self.keywordskeywords
41 self.logic_gateslogic_gates: List[str] = ['OR', 'AND', 'NOT']
42 self.allall: List[str] = []
43 self.allall.extend(self.keywordskeywords)
44 self.allall.extend(self.symbolssymbols)
45 self.allall.extend(self.keywordskeywords)
46
47 def _perror(self, string: str = "") -> None:
48 """ Print an error message """
49 self.disp.disp_print_error(f"(Injection) {string}")
50
51 def _is_base64(self, string: str) -> bool:
52 """ Check if a string is base64 encoded """
53 try:
54 base64.b64decode(string, validate=True)
55 return True
56 except Exception:
57 return False
58
59 def check_if_symbol_sql_injection(self, string: Union[str, List[str]]) -> bool:
60 """ Check if symbols are the source of the injection """
61 if isinstance(string, List) is True:
62 for i in string:
63 if self.check_if_symbol_sql_injection(i) is True:
64 return True
65 return False
66 if isinstance(string, str) is True:
67 if ";base64" in string:
68 return self._is_base64(string)
69 for i in self.symbolssymbols:
70 if i in string:
71 self.disp.log_debug(
72 f"Failed for {string}, node {i} was found.",
73 "check_if_symbol_sql_injection"
74 )
75 return True
76 else:
77 msg = "(check_if_symbol_sql_injection) string must be a string or a List of strings"
78 self._perror(msg)
79 return True
80 return False
81
82 def check_if_command_sql_injection(self, string: Union[str, List[str]]) -> bool:
83 """ Check if sql keywords are present """
84 if self.debug is True:
85 msg = "(check_if_command_sql_injection) string = "
86 msg += f"'{string}', type(string) = '{type(string)}'"
87 self.disp.disp_print_debug(msg)
88 if isinstance(string, List) is True:
89 for i in string:
90 if self.check_if_command_sql_injection(i) is True:
91 return True
92 return False
93 if isinstance(string, str) is True:
94 for i in self.keywordskeywords:
95 if i in string:
96 self.disp.log_debug(
97 f"Failed for {string}, node {i} was found.",
98 "check_if_command_sql_injection"
99 )
100 return True
101 else:
102 msg = "(check_if_command_sql_injection) string must be a string or a List of strings"
103 self._perror(msg)
104 return True
105 return False
106
107 def check_if_logic_gate_sql_injection(self, string: Union[str, List[str]]) -> bool:
108 """ Check if a logic gate is present """
109 if isinstance(string, List) is True:
110 for i in string:
111 if self.check_if_logic_gate_sql_injection(i) is True:
112 return True
113 return False
114 if isinstance(string, str) is True:
116 if i in string:
117 self.disp.log_debug(
118 f"Failed for {string}, node {i} was found.",
119 "check_if_logic_gate_sql_injection"
120 )
121 return True
122 else:
123 msg = "(check_if_logic_gate_sql_injection) string must be a string or a List of strings"
124 self._perror(msg)
125 return True
126 return False
127
128 def check_if_symbol_and_command_injection(self, string: Union[str, List[str]]) -> bool:
129 """ Check if symbols and commands are the source of the injection """
130 is_symbol = self.check_if_symbol_sql_injection(string)
131 is_command = self.check_if_command_sql_injection(string)
132 if is_symbol is True or is_command is True:
133 return True
134 return False
135
136 def check_if_symbol_and_logic_gate_injection(self, string: Union[str, List[str]]) -> bool:
137 """ Check if symbols and logic gates are the source of the injection """
138 is_symbol = self.check_if_symbol_sql_injection(string)
139 is_logic_gate = self.check_if_logic_gate_sql_injection(string)
140 if is_symbol is True or is_logic_gate is True:
141 return True
142 return False
143
144 def check_if_command_and_logic_gate_injection(self, string: Union[str, List[str]]) -> bool:
145 """ Check if command and logic gates are the source of the injection """
146 is_command = self.check_if_command_sql_injection(string)
147 is_logic_gate = self.check_if_logic_gate_sql_injection(string)
148 if is_command is True or is_logic_gate is True:
149 return True
150 return False
151
152 def check_if_sql_injection(self, string: Union[str, List[str]]) -> bool:
153 """ Check if there is an sql injection, uses all the parameters """
154 if isinstance(string, List) is True:
155 for i in string:
156 if self.check_if_sql_injection(i) is True:
157 return True
158 return False
159 if isinstance(string, str) is True:
160 if ";base64" in string:
161 return self._is_base64(string)
162 for i in self.allall:
163 if i in string:
164 return True
165 else:
166 msg = "(check_if_sql_injection) string must be a string or a List of strings"
167 self._perror(msg)
168 return True
169 return False
170
171 def check_if_injections_in_strings(self, array_of_strings: Union[str, List[str], List[List[str]]]) -> bool:
172 """ Check if there is an injection in the provided array of strings """
173 if isinstance(array_of_strings, List) is True:
174 for i in array_of_strings:
175 if isinstance(i, List) is True:
176 if self.check_if_injections_in_strings(i) is True:
177 return True
178 continue
179 if isinstance(i, str) is False:
180 err_message = "(check_if_injections_in_strings) Expected a string but "
181 err_message += f"got an {type(i)}"
182 self._perror(err_message)
183 return True
184 if self.check_if_sql_injection(i) is True:
185 return True
186 return False
187 if isinstance(array_of_strings, str) is True:
188 if self.check_if_sql_injection(array_of_strings) is True:
189 return True
190 return False
191 err_message = "(check_if_injections_in_strings) The provided item is neither a List a table or a string"
192 self._perror(err_message)
193 return False
194
195 def run_test(self, title: str, array: List[str], function: object, expected_response: bool = False, global_status: int = 0) -> int:
196 """ Run a test and return it's status"""
197 err = 84
198 global_response = global_status
199 print(f"{title}", end="")
200 for i in array:
201 print(".", end="")
202 response = function(i)
203 if response != expected_response:
204 print("[error]")
205 global_response = err
206 print("[success]")
207 return global_response
208
209 def test_injection_class(self) -> int:
210 """ Test the injection class """
211 success = 0
212 global_status = success
213 test_sentences = [
214 "SHOW TABLES;",
215 "SHOW Databases;",
216 "DROP TABLES;",
217 "SHOW DATABASE;",
218 "SELECT * FROM table;",
219 ]
220 global_status = self.run_test(
221 title="Logic gate test:",
222 array=self.logic_gateslogic_gates,
224 expected_response=True,
225 global_status=global_status
226 )
227 global_status = self.run_test(
228 title="Keyword check:",
229 array=self.keywordskeywords,
230 function=self.check_if_command_sql_injection,
231 expected_response=True,
232 global_status=global_status
233 )
234 global_status = self.run_test(
235 title="Symbol check:",
236 array=self.symbolssymbols,
237 function=self.check_if_symbol_sql_injection,
238 expected_response=True,
239 global_status=global_status
240 )
241 global_status = self.run_test(
242 title="All injections:",
243 array=self.allall,
244 function=self.check_if_sql_injection,
245 expected_response=True,
246 global_status=global_status
247 )
248 global_status = self.run_test(
249 title="Array check:",
250 array=[self.allall],
251 function=self.check_if_injections_in_strings,
252 expected_response=True,
253 global_status=global_status
254 )
255 global_status = self.run_test(
256 title="Double array check:",
257 array=[self.allall, self.allall],
258 function=self.check_if_injections_in_strings,
259 expected_response=True,
260 global_status=global_status
261 )
262 global_status = self.run_test(
263 title="SQL sentences:",
264 array=test_sentences,
265 function=self.check_if_sql_injection,
266 expected_response=True,
267 global_status=global_status
268 )
269 return global_status
270
271
272if __name__ == "__main__":
274 res = II.test_injection_class()
275 print(f"test status = {res}")
int run_test(self, str title, List[str] array, object function, bool expected_response=False, int global_status=0)
bool check_if_command_sql_injection(self, Union[str, List[str]] string)
bool check_if_symbol_and_logic_gate_injection(self, Union[str, List[str]] string)
bool check_if_symbol_sql_injection(self, Union[str, List[str]] string)
None __init__(self, int error=84, int success=0, bool debug=False)
bool check_if_injections_in_strings(self, Union[str, List[str], List[List[str]]] array_of_strings)
bool check_if_logic_gate_sql_injection(self, Union[str, List[str]] string)
bool check_if_command_and_logic_gate_injection(self, Union[str, List[str]] string)
None _perror(self, str string="")
bool check_if_symbol_and_command_injection(self, Union[str, List[str]] string)
bool check_if_sql_injection(self, Union[str, List[str]] string)