Skip to content

Commit 9fdb190

Browse files
committed
Improve parsing of multipart files and add a protection for bad multipart data.
1 parent 4d272c2 commit 9fdb190

1 file changed

Lines changed: 19 additions & 6 deletions

File tree

internal.js

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
107107
var tmp;
108108
var close = 0;
109109
var rm;
110+
var fn_close = function() {
111+
close--;
112+
};
110113

111114
// Replaces the EMPTYARRAY and EMPTYOBJECT in index.js
112115
req.files = [];
@@ -124,6 +127,10 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
124127
parser.initWithBoundary(boundary);
125128

126129
parser.onPartBegin = function() {
130+
131+
if (req.buffer_exceeded)
132+
return;
133+
127134
// Temporary data
128135
tmp = new HttpFile();
129136
tmp.$data = framework_utils.createBufferSize();
@@ -153,6 +160,13 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
153160
if (tmp.$step !== 0)
154161
return;
155162

163+
// UNKNOWN ERROR, maybe attack
164+
if (header.indexOf('form-data; ') === -1) {
165+
req.buffer_exceeded = true;
166+
!tmp.$is && destroyStream(stream);
167+
return;
168+
}
169+
156170
header = parse_multipart_header(header);
157171

158172
tmp.$step = 1;
@@ -166,11 +180,6 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
166180

167181
tmp.filename = header[1];
168182
tmp.path = path + (INDEXFILE++) + '.bin';
169-
170-
stream = Fs.createWriteStream(tmp.path, WRITESTREAM);
171-
stream.once('close', () => close--);
172-
stream.once('error', () => close--);
173-
close++;
174183
};
175184

176185
parser.onPartData = function(buffer, start, end) {
@@ -185,7 +194,6 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
185194

186195
if (size >= maximumSize) {
187196
req.buffer_exceeded = true;
188-
189197
if (rm)
190198
rm.push(tmp.path);
191199
else
@@ -233,6 +241,10 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
233241

234242
req.files.push(tmp);
235243
F.$events['upload-begin'] && F.emit('upload-begin', req, tmp);
244+
close++;
245+
stream = Fs.createWriteStream(tmp.path, WRITESTREAM);
246+
stream.once('close', fn_close);
247+
stream.once('error', fn_close);
236248
stream.write(data);
237249
tmp.length += length;
238250
};
@@ -270,6 +282,7 @@ exports.parseMULTIPART = function(req, contentType, route, tmpDirectory) {
270282
};
271283

272284
parser.onEnd = function() {
285+
273286
if (close) {
274287
setImmediate(parser.onEnd);
275288
} else {

0 commit comments

Comments
 (0)