A short and quick way to kill SQL injection in your project with python and some regex...
#/bin/python3
# by d4rk3r
from re import search, sub
def kill_injected_sql(input_string: str) -> str:
"""
A hard killer for sql injection from an incoming string.
params:
input_string : str [the incoming not sure string]
"""
# keys from an actual sql synthax
k_synthax = [
"CREATE ", "DROP ", "UPDATE ",
"INSERT ", "ALTER ", "DELETE ",
"ATTACH ", "DETACH ", "BEGIN ",
"CALL ", "COMMENT ", "COMMIT ",
"COPY ", "DESCRIBE ", "EXPLAIN ",
"GET ", "GRANT ", "LIST ", "MERGE ",
"PUT ", "REMOVE ", "REVOKE ", "ROLLBACK ",
"SET ", "SHOW ", "TRUNCATE ", "UNDROP ",
"UNSET ", "UPDATE ", "USE ", "WITH ",
"SELECT ", "ORDER BY ", "MERGE ", "EXEC ",
"UNION "
]
# to manage with lowercase string too
k_synthax += list(map(lambda x: x.lower(), k_synthax))
# The regex to detect that
regex = f"^({'|'.join(k_synthax)}|EXEC(UTE){0,1}|INSERT( +INTO){0,1}|{'|'.join(k_synthax)}|UNION( +ALL){0,1})|(?=.*(?:{'|'.join(k_synthax)})).*$"
if search(regex, input_string):
# the patch
return sub("[^0-9a-zA-Z]+", "_", input_string)
return input_string
# Some examples
print(kill_injected_sql("SELECT * FROM TESTS"))
print(kill_injected_sql("create TABLE niangua (test integer);"))
print(kill_injected_sql("DROP DATABASE IMPORTANT;"))
print(kill_injected_sql("normal string"))
# expected outputs
#
# SELECT_FROM_TESTS
# create_TABLE_niangua_test_integer_
# DROP_DATABASE_IMPORTANT_
# normal string
Source Code : https://gist.github.com/Sanix-Darker/19d85eace69e6f312cc2009a6fdd3beb
My Github : github.com/sanix-darker
Have FUN !
Discussion (2)
Using deny-lists instead of allow-lists is not secure at all. This doesn't cover all SQL commands. On top of that, new syntax can easily bypass these checks. It is better to focus on properly handling data input in a secure way instead. Also, using your method would disrupt processing of normal human text. There are other issues here, too, as it looks like you're replacing non-alphanumerics with underscore, which would absolutely break non-english characters.
I assume this is an overkilled function i made and it will not resolve all cases, and that's why am still improving it !