Skip to content

Commit afd5db2

Browse files
authored
Merge pull request #156 from PerformanC/149-bug-denial-of-service-dos-via-memory-exhaustion
update: limit content-length to 10mb on api
2 parents d630c79 + ac33259 commit afd5db2

1 file changed

Lines changed: 53 additions & 4 deletions

File tree

src/api/index.js

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -251,13 +251,59 @@ async function requestHandler(nodelink, req, res) {
251251
}
252252
}
253253

254+
const MAX_BODY_SIZE = nodelink.options.server?.maxBodySize || 10 * 1024 * 1024
255+
254256
let body = ''
255257
if (req.method !== 'GET') {
258+
const contentLength = parseInt(req.headers['content-length'])
259+
if (!isNaN(contentLength) && contentLength > MAX_BODY_SIZE) {
260+
logger(
261+
'warn',
262+
'Server',
263+
`Request rejected: Content-Length ${contentLength} exceeds limit of ${MAX_BODY_SIZE}`
264+
)
265+
sendErrorResponse(
266+
req,
267+
res,
268+
413,
269+
'Payload Too Large',
270+
'Request body is too large.',
271+
parsedUrl.pathname,
272+
trace
273+
)
274+
req.destroy()
275+
return
276+
}
277+
256278
await new Promise((resolve) => {
257-
req.on('data', (chunk) => {
279+
let receivedSize = 0
280+
281+
const onData = (chunk) => {
282+
receivedSize += chunk.length
283+
if (receivedSize > MAX_BODY_SIZE) {
284+
logger(
285+
'warn',
286+
'Server',
287+
`Request rejected: Body size exceeded limit of ${MAX_BODY_SIZE}`
288+
)
289+
req.removeListener('data', onData)
290+
req.removeListener('end', onEnd)
291+
sendErrorResponse(
292+
req,
293+
res,
294+
413,
295+
'Payload Too Large',
296+
'Request body is too large.',
297+
parsedUrl.pathname,
298+
trace
299+
)
300+
req.destroy()
301+
resolve()
302+
}
258303
body += chunk.toString()
259-
})
260-
req.on('end', () => {
304+
}
305+
306+
const onEnd = () => {
261307
try {
262308
if (
263309
req.headers['content-type']?.includes('application/json') &&
@@ -283,7 +329,10 @@ async function requestHandler(nodelink, req, res) {
283329
return
284330
}
285331
resolve()
286-
})
332+
}
333+
334+
req.on('data', onData)
335+
req.on('end', onEnd)
287336
})
288337
}
289338
req.body = body

0 commit comments

Comments
 (0)