diff --git a/README.md b/README.md index df93069..4233a0d 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,12 @@ fs.stat(filepath, function (err, stat) { ## API Doc +Field names and filenames use percent encoding for carriage returns (`%0D`), +line feeds (`%0A`), and double quotes (`%22`) in multipart headers. +Other characters and field contents remain unchanged. +The `field()`, `buffer()`, and `stream()` methods throw a `TypeError` synchronously +if a supplied MIME type contains a carriage return or line feed. + ### formstream([options]) Create a form instance. @@ -104,7 +110,7 @@ Create a form instance. Form - form instance -### FormStream#field(name, value) +### FormStream#field(name, value[, mimeType]) Add a normal field to the form. @@ -112,6 +118,7 @@ Add a normal field to the form. - **name** String - Name of field - **value** String - Value of field +- ***mimeType*** String - Optional. Content-Type of the field #### Returns diff --git a/lib/formstream.js b/lib/formstream.js index ed2de6e..5d1abe1 100644 --- a/lib/formstream.js +++ b/lib/formstream.js @@ -161,14 +161,14 @@ FormStream.prototype.stream = function (name, stream, filename, mimeType, size) mimeType = mime.getType(filename); } + var leading = this._leading({ name: name, filename: filename }, mimeType); + stream.once('error', this.emit.bind(this, 'error')); // if form stream destroy, also destroy the source stream this.once('destroy', function () { destroy(stream); }); - var leading = this._leading({ name: name, filename: filename }, mimeType); - var ps = parseStream().pause(); stream.pipe(ps); @@ -226,12 +226,18 @@ FormStream.prototype._leading = function (disposition, type) { if (disposition) { for (var k in disposition) { - dispositions.push(k + '="' + disposition[k] + '"'); + // Escape multipart names and filenames as in HTML form submissions. + var value = String(disposition[k]).replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22'); + dispositions.push(k + '="' + value + '"'); } } leading.push('Content-Disposition: form-data; ' + dispositions.join('; ')); if (type) { + type = String(type); + if (/[\r\n]/.test(type)) { + throw new TypeError('MIME type must not contain CR or LF'); + } leading.push('Content-Type: ' + type); } diff --git a/test/formstream.test.js b/test/formstream.test.js index d9b0252..41ca225 100644 --- a/test/formstream.test.js +++ b/test/formstream.test.js @@ -77,6 +77,48 @@ describe('formstream.test.js', function () { }); }); + it('should keep an injected field name in one multipart parameter', function (done) { + var form = formstream(); + form.field('public"; name="is_admin\r\nX-Injected: true', 'true'); + post(port, '/post', form, function (err, data) { + should.not.exist(err); + data.body.should.eql({ + 'public%22; name=%22is_admin%0D%0AX-Injected: true': 'true' + }); + data.files.should.eql({}); + done(); + }); + }); + + it('should preserve the field name with an injected filename', function (done) { + var form = formstream(); + form.buffer('public', Buffer.from('true'), + 'file.txt"; name="is_admin\r\nX-Injected: true', 'text/plain'); + post(port, '/post', form, function (err, data) { + should.not.exist(err); + data.body.should.eql({}); + data.files.should.have.keys('public'); + data.files.public.size.should.equal(4); + data.files.public.mime.should.equal('text/plain'); + done(); + }); + }); + + it('should preserve the field name after rejecting an injected MIME type', function (done) { + var form = formstream(); + (function () { + form.field('public', 'true', + 'text/plain\r\nContent-Disposition: form-data; name="is_admin"\r\nContent-Type:'); + }).should.throw('MIME type must not contain CR or LF'); + form.field('public', 'true'); + post(port, '/post', form, function (err, data) { + should.not.exist(err); + data.body.should.eql({ public: 'true' }); + data.files.should.eql({}); + done(); + }); + }); + it('should post fields only with content-length', function (done) { done = pedding(2, done); var form = formstream(); diff --git a/test/header-injection.test.js b/test/header-injection.test.js new file mode 100644 index 0000000..6da154d --- /dev/null +++ b/test/header-injection.test.js @@ -0,0 +1,123 @@ +'use strict'; + +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var Stream = require('stream'); +var formstream = require('../'); + +var filepath = path.join(__dirname, 'fixtures', 'foo.txt'); +var payload = fs.readFileSync(filepath); + +function collect(form, callback) { + var headers = form.headers(); + var chunks = []; + form.on('error', callback); + form.on('data', function (chunk) { + chunks.push(chunk); + }); + form.on('end', function () { + var body = Buffer.concat(chunks); + assert.strictEqual(headers['Content-Length'], String(body.length)); + callback(null, body.toString()); + }); +} + +function append(form, method, name, filename, mimeType) { + if (method === 'field') { + return form.field(name, payload, mimeType); + } + if (method === 'buffer') { + return form.buffer(name, payload, filename, mimeType); + } + if (method === 'stream') { + return form.stream(name, fs.createReadStream(filepath), filename, mimeType, payload.length); + } + return form.file(name, filepath, filename, payload.length); +} + +describe('multipart header injection', function () { + var unsafe = 'a\rb\nc\r\n"; name="injected"; 中文.txt'; + var escaped = 'a%0Db%0Ac%0D%0A%22; name=%22injected%22; 中文.txt'; + + ['field', 'buffer', 'stream', 'file'].forEach(function (method) { + it('should escape field names in ' + method + ' headers', function (done) { + var form = formstream(); + append(form, method, unsafe, 'normal.txt'); + collect(form, function (err, body) { + assert.ifError(err); + var disposition = 'Content-Disposition: form-data; name="' + escaped + '"'; + if (method !== 'field') { + disposition += '; filename="normal.txt"'; + } + assert.strictEqual(body, '--' + form._boundary + '\r\n' + disposition + '\r\n' + + (method === 'field' ? '' : 'Content-Type: text/plain\r\n') + + '\r\n' + payload + '\r\n--' + form._boundary + '--\r\n'); + done(); + }); + }); + + if (method !== 'field') { + it('should escape filenames in ' + method + ' headers', function (done) { + var form = formstream(); + append(form, method, 'public', unsafe); + collect(form, function (err, body) { + assert.ifError(err); + assert.strictEqual(body, '--' + form._boundary + '\r\n' + + 'Content-Disposition: form-data; name="public"; filename="' + escaped + '"\r\n' + + '\r\n' + payload + + '\r\n--' + form._boundary + '--\r\n'); + done(); + }); + }); + } + }); + + ['field', 'buffer', 'stream'].forEach(function (method) { + [ + 'text/plain\rX-Injected: true', + 'text/plain\nX-Injected: true', + 'text/plain\r\nContent-Disposition: form-data; name="is_admin"\r\nContent-Type:' + ].forEach(function (mimeType, index) { + it('should reject unsafe MIME type ' + index + ' in ' + method, function (done) { + var form = formstream(); + var source = new Stream.PassThrough(); + assert.throws(function () { + if (method === 'stream') { + form.stream('public', source, 'normal.txt', mimeType); + } else { + append(form, method, 'public', 'normal.txt', mimeType); + } + }, { name: 'TypeError', message: 'MIME type must not contain CR or LF' }); + assert.strictEqual(source.listenerCount('error'), 0); + assert.strictEqual(source.listenerCount('data'), 0); + assert.strictEqual(form.listenerCount('destroy'), 0); + assert.strictEqual(form._streams.length, 0); + assert.strictEqual(form._buffers.length, 0); + form.field('public', 'true'); + collect(form, function (err, body) { + assert.ifError(err); + assert.strictEqual(body, '--' + form._boundary + '\r\n' + + 'Content-Disposition: form-data; name="public"\r\n\r\ntrue\r\n' + + '--' + form._boundary + '--\r\n'); + done(); + }); + }); + }); + }); + + it('should preserve ordinary metadata and field contents', function (done) { + var form = formstream(); + var name = '中文 %22; a\\b'; + var value = 'value\r\n"unchanged"'; + form.field(name, value, 'text/plain; charset="utf-8"'); + collect(form, function (err, body) { + assert.ifError(err); + assert.strictEqual(body, '--' + form._boundary + '\r\n' + + 'Content-Disposition: form-data; name="' + name + '"\r\n' + + 'Content-Type: text/plain; charset="utf-8"\r\n\r\n' + value + '\r\n' + + '--' + form._boundary + '--\r\n'); + done(); + }); + }); +});