Text Classification
Keras
English
sql-injection
malicious-sql
sql-injection-detection
malicious-sql-detection
deathsaber93 commited on
Commit
df01262
β€’
1 Parent(s): b5de555

Update README.md

Browse files

Added details and how to use in readme.

Files changed (1) hide show
  1. README.md +265 -3
README.md CHANGED
@@ -1,3 +1,265 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - b-mc2/sql-create-context
5
+ - philikai/Spider-SQL-LLAMA2_train
6
+ - ChrisHayduk/Llama-2-SQL-Dataset
7
+ language:
8
+ - en
9
+ metrics:
10
+ - accuracy
11
+ - f1
12
+ - recall
13
+ - precision
14
+ library_name: keras
15
+ pipeline_tag: text-classification
16
+ tags:
17
+ - sql-injection
18
+ - malicious-sql
19
+ - sql-injection-detection
20
+ - malicious-sql-detection
21
+ ---
22
+
23
+ # SafeSQL-v1
24
+
25
+ ### Model Description
26
+ - **Feedback:** aakash.howlader@gmail.com
27
+ - **Model type:** Language model
28
+ - **Language(s) (NLP):** English
29
+ - **License:** Apache 2.0
30
+
31
+
32
+ ## Overview
33
+
34
+ This is a Keras 3.x model trained specifically to detect malicious SQLs. It is able to detect various SQL injection vectors such as Error-based, Union-based, Blind, Boolean-based
35
+ ,Time-based, Out-of-band, Stacked queries. This was trained on ~167K SQLs containing an almost even distribution of malicious and benign SQLs. SQiD's training involved preprocessing specifically for
36
+ SQL with special masking tokens. The training consisted of a warm-up period with a smaller, sinusoidally decaying learning rate
37
+ followed by a higher learning rate with cosine decay. A special callback was used to monitor for and protect against gradient
38
+ explosions. Weight and kernel constraints are applied to help prevent overfitting and achieve better generalization.
39
+ For faster model loading and inference, [mixed precision](https://www.tensorflow.org/guide/mixed_precision) has been used.
40
+
41
+ The best checkpoint is saved and made available for use.
42
+
43
+ **CONTEXT WINDOW:** 1200 tokens
44
+ **PARAMETERS:** 30.7M *(**Trainable:** 7.7M, **Frozen:** 2K, **Optimizer:** 23M)*
45
+ **NUMBER OF INPUTS:** 2 - The SQL queries as string and extra numeric features.
46
+ **NUMBER OF OUTPUTS:** 1 - Probability that the given SQL is malicious (the output layer uses a sigmoid activation).
47
+
48
+ The training data is made available [here](dataset/train.csv) and the benchmark data is made
49
+ available [here](dataset/benchmark.csv). The data was curated from the following sources -
50
+
51
+ #### Checkpointed Epoch
52
+
53
+ ```
54
+ 823/823 ━━━━━━━━━━━━━━━━━━━━ 99s 120ms/step - AUPR: 0.9979 - f1_score: 0.5782 - fn: 64.0947 - fp: 8.2500 - loss: 0.0236 - precision: 0.9987 - recall: 0.9889 - val_AUPR: 0.9970 - val_f1_score: 0.5775 - val_fn: 34.0000 - val_fp: 4.0000 - val_loss: 0.0298 - val_precision: 0.9985 - val_recall: 0.9873 - learning_rate: 7.0911e-04
55
+ ```
56
+
57
+ #### Training Data
58
+
59
+ 1. https://www.kaggle.com/datasets/gambleryu/biggest-sql-injection-dataset/data
60
+ 2. https://huggingface.co/datasets/b-mc2/sql-create-context
61
+ 3. https://github.com/payloadbox/sql-injection-payload-list/tree/master/Intruder
62
+ 4. https://huggingface.co/datasets/ChrisHayduk/Llama-2-SQL-Dataset/viewer/default/eval
63
+ 5. https://huggingface.co/datasets/philikai/Spider-SQL-LLAMA2_train/viewer/default/train
64
+
65
+ #### Benchmark Data
66
+
67
+ 1. https://www.kaggle.com/datasets/sajid576/sql-injection-dataset?select=Modified_SQL_Dataset.csv
68
+
69
+
70
+ ## How to Use
71
+
72
+ 1. Based on your hardware (whether using GPU or not), please download the corresponding `requiremnts-[cpu/gpu].txt` file and install it (`pip install -r requirements.txt`)
73
+ 2. Download the model file `sqid.keras`.
74
+ 3. The model expects certain numerical features along with the SQL query. As of v1, some boiler-plate code needs to be written in order to add the numeric features. Please use the below code snippet to load the model, add the expected numeric features and run an inference.
75
+ Future iterations of the model will have the feature addition baked into the model itself.
76
+
77
+
78
+ ```Python
79
+ import re
80
+ from multiprocessing import cpu_count
81
+
82
+ from keras.src.saving import load_model
83
+ import pandas as pd
84
+ from numpy import int64
85
+ from pandarallel import pandarallel
86
+ from sklearn.preprocessing import RobustScaler
87
+
88
+ model = load_model('./sqid.keras')
89
+ pandarallel.initialize(use_memory_fs=True, nb_workers=cpu_count())
90
+
91
+
92
+ def sql_tokenize(sql_query):
93
+ sql_query = sql_query.replace('`', ' ').replace('%20', ' ').replace('=', ' = ').replace('((', ' (( ').replace(
94
+ '))', ' )) ').replace('(', ' ( ').replace(')', ' ) ').replace('||', ' || ').replace(',', '').replace(
95
+ '--', ' -- ').replace(':', ' : ').replace('%23', ' # ').replace('+', ' + ').replace('!=',
96
+ ' != ') \
97
+ .replace('"', ' " ').replace('%26', ' and ').replace('$', ' $ ').replace('%28', ' ( ').replace('%2A', ' * ') \
98
+ .replace('%7C', ' | ').replace('&', ' & ').replace(']', ' ] ').replace('[', ' [ ').replace(';',
99
+ ' ; ').replace(
100
+ '/*', ' /* ')
101
+ sql_reserved = {'SELECT', 'FROM', 'WHERE', 'AND', 'OR', 'NOT', 'IN', 'LIKE', 'ORDER', 'BY', 'GROUP', 'HAVING',
102
+ 'LIMIT', 'BETWEEN', 'IS', 'NULL', '%', 'LIKE', 'MIN', 'MAX', 'AS', 'UPPER', 'LOWER', 'TO_DATE',
103
+ '=', '>', '<', '>=', '<=', '!=', '<>', 'BETWEEN', 'LIKE', 'EXISTS', 'JOIN', 'UNION', 'ALL',
104
+ 'ASC', 'DESC', '||', 'AVG', 'LIMIT', 'EXCEPT', 'INTERSECT', 'CASE', 'WHEN', 'THEN', 'IF',
105
+ 'IF', 'ANY', 'CAST', 'CONVERT', 'COALESCE', 'NULLIF', 'INNER', 'OUTER', 'LEFT', 'RIGHT', 'FULL',
106
+ 'CROSS', 'OVER', 'PARTITION', 'SUM', 'COUNT', 'WITH', 'INTERVAL', 'WINDOW', 'OVER',
107
+ 'ROW_NUMBER', 'RANK',
108
+ 'DENSE_RANK', 'NTILE', 'FIRST_VALUE', 'LAST_VALUE', 'LAG', 'LEAD', 'DISTINCT', 'COMMENT',
109
+ 'INSERT',
110
+ 'UPDATE', 'DELETED', 'MERGE', '*', 'generate_series', 'char', 'chr', 'substr', 'lpad',
111
+ 'extract',
112
+ 'year', 'month', 'day', 'timestamp', 'number', 'string', 'concat', 'INFORMATION_SCHEMA',
113
+ "SQLITE_MASTER", 'TABLES', 'COLUMNS', 'CUBE', 'ROLLUP', 'RECURSIVE', 'FILTER', 'EXCLUDE',
114
+ 'AUTOINCREMENT', 'WITHOUT', 'ROWID', 'VIRTUAL', 'INDEXED', 'UNINDEXED', 'SERIAL',
115
+ 'DO', 'RETURNING', 'ILIKE', 'ARRAY', 'ANYARRAY', 'JSONB', 'TSQUERY', 'SEQUENCE',
116
+ 'SYNONYM', 'CONNECT', 'START', 'LEVEL', 'ROWNUM', 'NOCOPY', 'MINUS', 'AUTO_INCREMENT', 'BINARY',
117
+ 'ENUM', 'REPLACE', 'SET', 'SHOW', 'DESCRIBE', 'USE', 'EXPLAIN', 'STORED', 'VIRTUAL', 'RLIKE',
118
+ 'MD5', 'SLEEP', 'BENCHMARK', '@@VERSION', 'VERSION', '@VERSION', 'CONVERT', 'NVARCHAR', '#',
119
+ '##', 'INJECTX',
120
+ 'DELAY', 'WAITFOR', 'RAND',
121
+ }
122
+
123
+ tokens = sql_query.split()
124
+ tokens = [re.sub(r"""[^*\w\s.=\-><_|()!"']""", '', token) for token in tokens]
125
+ for i, token in enumerate(tokens):
126
+ if token.strip().upper() in sql_reserved:
127
+ continue
128
+ if token.strip().isnumeric():
129
+ tokens[i] = '#NUMBER#'
130
+ elif re.match(r'^[a-zA-Z_.|][a-zA-Z0-9_.|]*$', token.strip()):
131
+ tokens[i] = '#IDENTIFIER#'
132
+ elif re.match(r'^[\d:]*$', token.strip()):
133
+ tokens[i] = '#TIMESTAMP#'
134
+ elif '%' in token.strip():
135
+ tokens[i] = ' '.join(
136
+ [j.strip() if j.strip() in ('%', "'", "'") else '#IDENTIFIER#' for j in token.strip().split('%')])
137
+ return ' '.join(tokens)
138
+
139
+
140
+ def add_features(x):
141
+ s = ["num_tables", "num_columns", "num_literals", "num_parentheses", "has_union", "depth_nested_queries", "num_join", "num_sp_chars", "has_mismatched_quotes", "has_tautology"]
142
+ x['Query'] = x['Query'].copy().parallel_apply(lambda a: sql_tokenize(a))
143
+ x['num_tables'] = x['Query'].str.lower().str.count(r'FROM\s+#IDENTIFIER#', flags=re.I)
144
+ x['num_columns'] = x['Query'].str.lower().str.count(r'SELECT\s+#IDENTIFIER#', flags=re.I)
145
+ x['num_literals'] = x['Query'].str.lower().str.count("'[^']*'", flags=re.I) + x['Query'].str.lower().str.count(
146
+ '"[^"]"', flags=re.I)
147
+ x['num_parentheses'] = x['Query'].str.lower().str.count("\\(", flags=re.I) + x['Query'].str.lower().str.count(
148
+ '\\)',
149
+ flags=re.I)
150
+ x['has_union'] = x['Query'].str.lower().str.count(" union |union all", flags=re.I) > 0
151
+ x['has_union'] = x['has_union'].astype(int64)
152
+ x['depth_nested_queries'] = x['Query'].str.lower().str.count("\\(", flags=re.I)
153
+ x['num_join'] = x['Query'].str.lower().str.count(
154
+ " join |inner join|outer join|full outer join|full inner join|cross join|left join|right join",
155
+ flags=re.I)
156
+ x['num_sp_chars'] = x['Query'].parallel_apply(lambda a: len(re.findall(r'[\'";\-*/%=><|#]', a)))
157
+ x['has_mismatched_quotes'] = x['Query'].parallel_apply(
158
+ lambda sql_query: 1 if re.search(r"'.*[^']$|\".*[^\"]$", sql_query) else 0)
159
+ x['has_tautology'] = x['Query'].parallel_apply(lambda sql_query: 1 if re.search(r"'[\s]*=[\s]*'", sql_query) else 0)
160
+ return x
161
+
162
+
163
+ input_sqls = ['SELECT roomName , RoomId FROM Rooms WHERE basePrice > 160 AND maxOccupancy > 2;', # Not malicious
164
+ "ORDER BY 1,SLEEP(5),BENCHMARK(1000000,MD5('A')),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18#", # Malicious
165
+ "; desc users; --", # Malicious
166
+ "ORDER BY 1,SLEEP(5),BENCHMARK(1000000,MD5('A')),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27", # Malicious
167
+ "SELECT DISTINCT t2.datasetid FROM paperdataset AS t3 JOIN dataset AS t2 ON t3.datasetid = t2.datasetid JOIN paperkeyphrase AS t1 ON t1.paperid = t3.paperid JOIN keyphrase AS t4 ON t1.keyphraseid = t4.keyphraseid WHERE t4.keyphrasename = ""semantic parsing"";" # Not malicious
168
+ ]
169
+
170
+ numeric_features = ["num_tables", "num_columns", "num_literals", "num_parentheses", "has_union", "depth_nested_queries", "num_join", "num_sp_chars", "has_mismatched_quotes", "has_tautology"]
171
+
172
+ input_df = pd.DataFrame(input_sqls, columns=['Query'])
173
+ input_df = add_features(input_df)
174
+
175
+ scaler = RobustScaler()
176
+ x_in = scaler.fit_transform(input_df[numeric_features])
177
+
178
+ preds = model.predict([input_df['Query'], x_in]).tolist()
179
+
180
+
181
+ for i, pred in enumerate(preds):
182
+ print()
183
+ print(f'Query: {input_sqls[i]}')
184
+ print(f'Malicious? {pred[0] >= 0.50} ({pred[0]})')
185
+ print()
186
+
187
+ # Run the benchmark
188
+
189
+ input_df = pd.read_csv('./dataset/benchmark.csv')
190
+ hits = 0
191
+ data_size = input_df.shape[0]
192
+ miss_pos, miss_neg = [], []
193
+ total_negs = input_df[input_df['Label'] == 1.0].shape[0]
194
+ total_pos = input_df[input_df['Label'] == 0.0].shape[0]
195
+ pred_trans = ['Benign', 'Malicious']
196
+ false_metrics = {0: 0, 1: 0}
197
+ x_in = scaler.transform(input_df[numeric_features])
198
+ print('Running benchmark')
199
+ preds = model.predict([input_df['Query'], x_in])
200
+ miss_q = []
201
+
202
+ actuals = input_df['Label'].tolist()
203
+ for i, pred in enumerate(preds):
204
+ pred = int(pred[0] > .95)
205
+ if pred == actuals[i]:
206
+ hits += 1
207
+ else:
208
+ false_metrics[int(pred)] += 1
209
+
210
+ print('Finished benchmark.')
211
+ print('printing results.')
212
+ acc = round((hits / data_size) * 100, 2)
213
+ f_neg = round((false_metrics[0] / total_negs) * 100, 2)
214
+ f_pos = round((false_metrics[1] / total_pos) * 100, 2)
215
+ print(f'Total data: {data_size}')
216
+ print(f'Total Negatives: {total_negs} \t Total Positives: {total_pos}')
217
+ print()
218
+ print(f'Total hits: {hits}/{data_size} with accuracy of {acc}%.')
219
+ print(f'False Negatives: {false_metrics[0]}({f_neg}%) \t False Positives: {false_metrics[1]}({f_pos}%)', false_metrics[0], f_neg, false_metrics[1], f_pos)
220
+
221
+ ```
222
+
223
+
224
+ #### Output
225
+
226
+ ```
227
+ 2024-06-16 17:34:54.587073: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
228
+ ...
229
+ 2024-06-16 17:36:11.762174: I external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:465] Loaded cuDNN version 8902
230
+ 1/1 ━━━━━━━━━━━━━━━━━━━━ 14s 14s/step
231
+
232
+ Query: SELECT roomName , RoomId FROM Rooms WHERE basePrice > 160 AND maxOccupancy > 2;
233
+ Malicious? False (7.727547199465334e-05)
234
+
235
+
236
+ Query: ORDER BY 1,SLEEP(5),BENCHMARK(1000000,MD5('A')),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18#
237
+ Malicious? True (1.0)
238
+
239
+
240
+ Query: ; desc users; --
241
+ Malicious? True (0.9999552965164185)
242
+
243
+
244
+ Query: ORDER BY 1,SLEEP(5),BENCHMARK(1000000,MD5('A')),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27
245
+ Malicious? True (1.0)
246
+
247
+
248
+ Query: SELECT DISTINCT t2.datasetid FROM paperdataset AS t3 JOIN dataset AS t2 ON t3.datasetid = t2.datasetid JOIN paperkeyphrase AS t1 ON t1.paperid = t3.paperid JOIN keyphrase AS t4 ON t1.keyphraseid = t4.keyphraseid WHERE t4.keyphrasename = semantic parsing;
249
+ Malicious? False (6.156865989259686e-11)
250
+
251
+ Running benchmark
252
+ 967/967 ━━━━━━━━━━━━━━━━━━━━ 37s 37ms/step
253
+ Finished benchmark.
254
+ printing results.
255
+ Total data: 30919
256
+ Total Negatives: 11382 Total Positives: 19537
257
+
258
+ Total hits: 30844/30919 with accuracy of 99.76%.
259
+ False Negatives: 69(0.61%) False Positives: 6(0.03%) 69 0.61 6 0.03
260
+
261
+ ```
262
+
263
+ ## Architecture
264
+
265
+ ![Overall Architecture](./sqid.keras.png)