-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
213 lines (192 loc) · 9.2 KB
/
Copy pathindex.js
File metadata and controls
213 lines (192 loc) · 9.2 KB
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
import {payloads} from "./data/index.js";
import {traverse, traverseForm} from "./utils/bodyUtils.js";
import multer from "multer";
import bodyParser from "body-parser";
class rtguard {
constructor(config) {
this.plevel = config?.plevel || 4 // Paranioa level: threshold number of patterns needed to be detected before classifying the request as malicious
this.allowedBodyTypes = config?.allowedBodyTypes || ['application/json']
this.allowedMethods = config?.allowedMethods || ['GET', 'POST']
this.maxRequestSize = config?.maxRequestSize || 4096
this.verbose = !!config?.verbose
this.multer = config?.multer || multer().any();
this.action = config?.action || 'block' // Action to take when a malicious request is detected
this.useMulterFunction = false
if(this.plevel > 10 || this.plevel < 1) {
throw new Error('Illegal value: plevel must be in between 1-10.')
}
if(config?.multer && typeof this.multer === 'function') {
this.useMulterFunction = true
}
this.rtguard = this.rtguard.bind(this)
}
initialAudit(req) {
if(this.allowedMethods?.length && !this.allowedMethods?.includes('*') && !this.allowedMethods.includes(req.method)) {
return 'Request method not allowed.'
}
if(this.allowedBodyTypes?.length && !this.allowedBodyTypes.includes('*') && req.headers['content-type']) {
let found = false
for(const bt of this.allowedBodyTypes) {
if(req.headers['content-type'].includes(bt)) {
found = true
}
}
if(!found) {
return 'Request content type not allowed.'
}
}
if(this.maxRequestSize && req.headers['content-length'] && parseInt(req.headers['content-length']) > this.maxRequestSize) {
return 'Request exceeds maximum allowed size.'
}
return false
}
getMulterInstance(req) {
if(this.useMulterFunction) {
return this.multer(req)
}
return this.multer
}
checkURL(url, regex) {
return regex.test(url) || regex.test(decodeURIComponent(url))
}
checkHeaders(headers, regex) {
return traverse(headers, regex)
}
checkJsonBody(body, regex) {
return traverse(body, regex);
}
checkMultipartFormBody(body, regex) {
return traverseForm(body, regex)
}
parseBody(req, res) {
const contentType = (req.headers['content-type'] || '').trim();
let parsedBody;
if(!contentType || contentType.length === 0) {
return null
}
return new Promise((resolve, reject) => {
if (contentType.includes('application/json')) {
bodyParser.json()(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'application/json'})
});
} else if (contentType.includes('multipart/form-data')) {
const multerInstance = this.getMulterInstance(req)
multerInstance(req, res, (err) => {
if(err) reject(err)
else {
parsedBody = { files: req.files, fields: req.body };
resolve({body: req.body, type: 'multipart/form-data'})
}
});
} else if (contentType.includes('application/x-www-form-urlencoded')) {
bodyParser.urlencoded({ extended: true })(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'application/x-www-form-urlencoded'})
});
} else if (contentType.includes('text/plain')) {
bodyParser.text()(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'text/plain'})
});
} else if (contentType.includes('text/html')) {
bodyParser.text({ type: 'text/html' })(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'text/html'})
});
} else if (contentType.includes('text/javascript')) {
bodyParser.text({ type: 'text/javascript' })(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'text/javascript'})
});
} else if (contentType.includes('text/css')) {
bodyParser.text({ type: 'text/css' })(req, res, () => {
parsedBody = req.body;
resolve({body: parsedBody, type: 'text/css'})
});
} else {
reject('Unsupported media')
}
})
};
async rtguard(req, res, next) {
const start = process.hrtime();
this.log([`\n[+] Execution trace ${req.method} ${req.url}:`])
const initialAuditResult = this.initialAudit(req)
if(initialAuditResult) {
this.logSummary(null, start, true, req)
return res.status(418).send(`This request was blocked: ${initialAuditResult}`)
}
try {
const parsedBody = await this.parseBody(req)
var audits = []
for(let attacks of payloads) {
let attackName = attacks[0]
let attackPatterns = attacks[1]
for(const pattern of attackPatterns) {
if(this.checkURL(req.url, pattern)) {
audits.push({scope: 'url', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in URL:`, pattern])
}
if(this.checkHeaders(req.headers, pattern)) {
audits.push({scope: 'headers', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in Headers:`, pattern])
}
if(parsedBody && parsedBody.type) {
if(parsedBody.type === 'application/json' && this.checkJsonBody(parsedBody.body, pattern)) {
audits.push({scope: 'json', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in JSON Body:`, pattern])
} else if(parsedBody.type === 'multipart/form-data' && this.checkMultipartFormBody(parsedBody.body, pattern)) {
audits.push({scope: 'multipart form', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in Multipart Form Body:`, pattern])
} else if(parsedBody.type === 'application/x-www-form-urlencoded' && this.checkJsonBody(parsedBody.body, pattern)) {
audits.push({scope: 'url encoded form', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in URL Encoded Form Body:`, pattern])
} else if(parsedBody.type.includes('text') && pattern.test(parsedBody.body)) {
audits.push({scope: 'text', attackName, pattern})
this.log([`\t[***] ${attackName} attack pattern detected in Text Body:`, pattern])
} else {
}
}
if(audits.length >= this.plevel) {
this.logSummary(audits, start, true, req)
return this.verbose ? res.status(418).send(`This request was blocked due to ${attackName} suspicion:\n\n${this.auditSummary(audits)}`) :
res.status(418).send('This request was blocked.')
}
}
}
this.logSummary(audits, start, false, req)
return next()
} catch (e) {
console.log(e)
next()
}
}
logSummary(audits, start, blocked, req) {
const end = process.hrtime(start);
const elapsedTime = (end[0] * 1000) + (end[1] / 1e6);
if(!audits) {
this.log([`\n[+] Audit Summary ${req.method} ${req.url}:\n\tRequest was blocked at initial audit stage.\n\tNumber of detected patterns: N/A\n\tTime taken to audit the request: ${elapsedTime} ms\n`])
return
}
if(blocked) {
this.log([`\n[+] Audit Summary ${req.method} ${req.url}:\n\tRequest was blocked.\n\tNumber of detected patterns: ${audits.length}\n\tTime taken to audit the request: ${elapsedTime} ms\n`])
} else {
this.log([`\n[+] Audit Summary ${req.method} ${req.url}:\n\tRequest was allowed.\n\tNumber of detected patterns: ${audits.length}\n\tTime taken to audit the request: ${elapsedTime} ms`])
}
this.log([this.auditSummary(audits)])
}
auditSummary(audits) {
let res = ''
for(const audit of audits) {
res += `\t${audit.attackName} suspicion in ${audit.scope} with attack pattern ${audit.pattern}.\n`
}
return res
}
log(args) {
if(this.verbose) {
console.log(...args)
}
}
}
export {rtguard}