-
Notifications
You must be signed in to change notification settings - Fork 0
/
grindwall.py
224 lines (157 loc) · 8.04 KB
/
grindwall.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from http.server import SimpleHTTPRequestHandler,HTTPServer
from urllib import request,error
import urllib.parse
import http.cookiejar
import sys
import requests
from pycaret.classification import *
import pandas as pd
import logging
import re
from datetime import datetime
nttfy_docker='https://ntfy.sh/th1rt33n'
data = 'Malicious Request Detected'
#Logging
logging.basicConfig(filename='server.log', level=logging.INFO, format='%(asctime)s - %(message)s')
model = load_model('model3_grindwall')
cookies = http.cookiejar.CookieJar()
bad_words = ['sleep', 'drop', 'uid', 'select', 'waitfor', 'delay', 'system', 'union', 'order by', 'delete', 'group by', 'insert', 'or']
xss = ['script','img','a','javascript','svg','onclick']
cmd = ['id','ls','dir','ping','uname','exec','nc','bash']
def cmdi_check(path,body):
cmdi_patterns = [
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)',
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)\s*',
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)\s*[\\"\']?[^\\n\\r]*',
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)\s*[\\"\']?[^\\"\']*[\\"\']?',
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)[\s\w]*',
r'(?:;|&|\||`|\$\(.*\)|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)[^\r\n]*'
]
counter = 0
#cmdi_pattern = r'(?:;|&|\||`|\$\(|\b(?:exec|system|shell_exec|passthru|popen|proc_open|pcntl_exec|eval|etc|bin|ls|id|uname|dir|ping|nc|bash)\b)'
for pattern in cmdi_patterns:
if re.search(pattern,path) or re.search(pattern,body):
counter+=1
return counter
def regex_xss_check(path):
xss_patterns = [
r'<script\s[^>]*>[\s\S]*?<',
r'(on\w+)=["\'](.*?)["\']',
r'<img\s[^>]*\son\w+=["\'](.*?)["\'][^>]*>',
r'href=["\'](javascript:[^"\']+)["\']',
r'\bjavascript:\s*[^;]+;'
]
count = 0
for pattern in xss_patterns:
if re.search(pattern, path):
count=count+1
return count
def extractDF(method,path,body):
path = urllib.parse.unquote(path)
single_quotes = path.count("'") + body.count("'")
double_quotes = path.count('"') + body.count('"')
dashes = path.count('--') + body.count('--')
braces = path.count('{') + path.count('}') + path.count('(') + body.count('{') + body.count('}') + body.count('(')
spaces = path.count(' ') + body.count(" ")
tags = path.count('<') + path.count('>')+ body.count('<')+body.count('>')
colons = path.count(';')+body.count(';')
backtick = path.count('`')+body.count('`')
bad_words_count1 = sum(1 for word in bad_words if re.search(r'\b' + re.escape(word) + r'\b', path, re.IGNORECASE))
bad_words_count2 = sum(1 for word in bad_words if re.search(r'\b' + re.escape(word) + r'\b', body, re.IGNORECASE))
xss_count1 = sum(1 for word in xss if re.search(r'\b' + re.escape(word) + r'\b', path, re.IGNORECASE))
xss_count2 = sum(1 for word in xss if re.search(r'\b' + re.escape(word) + r'\b', body, re.IGNORECASE))
bad_words_count = bad_words_count1+ bad_words_count2
xss_count = xss_count1+xss_count2
xss_check = regex_xss_check(path)
cmdi_c = cmdi_check(path,body)
cmdi_words1 = sum(1 for word in cmd if re.search(r'\b' + re.escape(word) + r'\b', path, re.IGNORECASE))
cmdi_words2 = sum(1 for word in cmd if re.search(r'\b' + re.escape(word) + r'\b', body, re.IGNORECASE))
cmdi_words = cmdi_words1+cmdi_words2
datas = [single_quotes, double_quotes, dashes, braces, spaces,tags,colons,backtick, bad_words_count,xss_check,xss_count,cmdi_words,cmdi_c]
log_data = [method,path,body]
input = pd.DataFrame([datas], columns=['Single Quotes', 'Double Quotes', 'Dashes', 'Braces', 'Spaces','Tags','Colons','Backtick', 'Bad Words','XSS Check','XSS Word','Cmdi Word','Cmdi Check'])
log = pd.DataFrame([log_data],columns=['Method','Path','Body'])
return input,log
def prediction(input):
prediction = predict_model(model,data=input)
return prediction
class SimpleHttpProxy(SimpleHTTPRequestHandler):
@classmethod
def set_routes(cls,proxy_routes):
cls.proxy_routes = proxy_routes
def do_GET(self) -> None:
try:
body=''
path = self.path
method = self.command
full_url = f'{path}'
print(full_url)
response = request.urlopen(full_url)
content = response.read()
inp,log = extractDF(method,path,body)
pred = prediction(inp)
result = pd.concat([log,pred],axis=1)
result.to_csv('log_dataset.csv',mode='a',header=False,index=False)
print(pred)
pp = pred['prediction_label'].to_string()
log_message = f"{datetime.now().strftime('%d-%m-%Y %H:%M:%S')} - GET Prediction: {pred.to_string()}"
logging.info(log_message)
if 'good' in pp:
self.send_response(200)
self.end_headers()
self.wfile.write(content)
else:
self.send_response(403)
self.end_headers()
self.wfile.write(b"Blocked by THE GRINDWALL")
try:
resp = requests.post(nttfy_docker,data=data)
resp.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f"HTTP Error {resp.status_code}: {err}")
except requests.exceptions.RequestException as err:
print(f"Request Error: {err}")
except Exception as e:
logging.error(f"Error in the GET request: str{e}")
def do_POST(self)-> None:
try:
content_length = int(self.headers['Content-Length'])
post_body = self.rfile.read(content_length).decode('utf-8')
path = self.path
method = self.command
full_url = f'{path}'
body = post_body
response = request.urlopen(full_url)
content = response.read()
inp,log = extractDF(method,path,body)
pred = prediction(inp)
result = pd.concat([log,pred],axis=1)
result.to_csv('log_dataset.csv',mode='a',header=False,index=False)
print(pred)
log_message = f"{datetime.now().strftime('%d-%m-%Y %H:%M:%S')} - POST Prediction: {pred.to_string()}"
logging.info(log_message)
pp = pred['prediction_label'].to_string()
# print(pp)
# pred = 'bad'
if 'good' in pp:
self.send_response(200)
self.end_headers()
self.wfile.write(content)
else:
self.send_response(403)
self.end_headers()
self.wfile.write(b"Blocked by THE GRINDWALL")
try:
resp = requests.post(nttfy_docker,data=data)
resp.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f"HTTP Error {resp.status_code}: {err}")
except requests.exceptions.RequestException as err:
print(f"Request Error: {err}")
except Exception as e:
logging.error(f"Error in POST requests: {str(e)}")
if __name__ == '__main__':
server_address = ('', 1234)
httpd = HTTPServer(server_address, SimpleHttpProxy)
httpd.serve_forever()
print("Server Started on port: 1234")