Skip to content

Commit 7bef1b7

Browse files
committed
http: strictly forbid invalid characters from headers
PR-URL: nodejs-private/node-private#26 Reviewed-By: Rod Vagg <r@va.gg> Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
1 parent 4f4c8ab commit 7bef1b7

File tree

5 files changed

+92
-97
lines changed

5 files changed

+92
-97
lines changed

doc/api/http.markdown

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -649,8 +649,8 @@ response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
649649
response.end();
650650
```
651651

652-
Attempting to set a trailer field name that contains invalid characters will
653-
result in a [`TypeError`][] being thrown.
652+
Attempting to set a header field name or value that contains invalid characters
653+
will result in a [`TypeError`][] being thrown.
654654

655655
### response.end([data][, encoding][, callback])
656656

@@ -721,8 +721,8 @@ or
721721
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
722722
```
723723

724-
Attempting to set a header field name that contains invalid characters will
725-
result in a [`TypeError`][] being thrown.
724+
Attempting to set a header field name or value that contains invalid characters
725+
will result in a [`TypeError`][] being thrown.
726726

727727
When headers have been set with [`response.setHeader()`][], they will be merged with
728728
any headers passed to [`response.writeHead()`][], with the headers passed to
@@ -836,8 +836,8 @@ response.writeHead(200, {
836836
This method must only be called once on a message and it must
837837
be called before [`response.end()`][] is called.
838838

839-
If you call [`response.write()`][] or [`response.end()`][] before calling this, the
840-
implicit/mutable headers will be calculated and call this function for you.
839+
If you call [`response.write()`][] or [`response.end()`][] before calling this,
840+
the implicit/mutable headers will be calculated and call this function for you.
841841

842842
When headers have been set with [`response.setHeader()`][], they will be merged with
843843
any headers passed to [`response.writeHead()`][], with the headers passed to
@@ -860,6 +860,9 @@ should be used to determine the number of bytes in a given encoding.
860860
And Node.js does not check whether Content-Length and the length of the body
861861
which has been transmitted are equal or not.
862862

863+
Attempting to set a header field name or value that contains invalid characters
864+
will result in a [`TypeError`][] being thrown.
865+
863866
## Class: http.IncomingMessage
864867

865868
An `IncomingMessage` object is created by [`http.Server`][] or

lib/_http_common.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,3 +231,20 @@ function checkIsHttpToken(val) {
231231
return typeof val === 'string' && token.test(val);
232232
}
233233
exports._checkIsHttpToken = checkIsHttpToken;
234+
235+
/**
236+
* True if val contains an invalid field-vchar
237+
* field-value = *( field-content / obs-fold )
238+
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
239+
* field-vchar = VCHAR / obs-text
240+
**/
241+
function checkInvalidHeaderChar(val) {
242+
val = '' + val;
243+
for (var i = 0; i < val.length; i++) {
244+
const ch = val.charCodeAt(i);
245+
if (ch === 9) continue;
246+
if (ch <= 31 || ch > 255 || ch === 127) return true;
247+
}
248+
return false;
249+
}
250+
exports._checkInvalidHeaderChar = checkInvalidHeaderChar;

lib/_http_outgoing.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,8 +305,10 @@ function storeHeader(self, state, field, value) {
305305
throw new TypeError(
306306
'Header name must be a valid HTTP Token ["' + field + '"]');
307307
}
308-
value = escapeHeaderValue(value);
309-
state.messageHeader += field + ': ' + value + CRLF;
308+
if (common._checkInvalidHeaderChar(value) === true) {
309+
throw new TypeError('The header content contains invalid characters');
310+
}
311+
state.messageHeader += field + ': ' + escapeHeaderValue(value) + CRLF;
310312

311313
if (connectionExpression.test(field)) {
312314
state.sentConnectionHeader = true;
@@ -341,8 +343,10 @@ OutgoingMessage.prototype.setHeader = function(name, value) {
341343
if (value === undefined)
342344
throw new Error('"value" required in setHeader("' + name + '", value)');
343345
if (this._header)
344-
throw new Error('Can\'t set headers after they are sent');
345-
346+
throw new Error('Can\'t set headers after they are sent.');
347+
if (common._checkInvalidHeaderChar(value) === true) {
348+
throw new TypeError('The header content contains invalid characters');
349+
}
346350
if (this._headers === null)
347351
this._headers = {};
348352

@@ -515,6 +519,9 @@ OutgoingMessage.prototype.addTrailers = function(headers) {
515519
throw new TypeError(
516520
'Trailer name must be a valid HTTP Token ["' + field + '"]');
517521
}
522+
if (common._checkInvalidHeaderChar(value) === true) {
523+
throw new TypeError('The header content contains invalid characters');
524+
}
518525
this._trailer += field + ': ' + escapeHeaderValue(value) + CRLF;
519526
}
520527
};

test/parallel/test-http-header-response-splitting.js

Lines changed: 0 additions & 87 deletions
This file was deleted.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const http = require('http');
5+
const net = require('net');
6+
const url = require('url');
7+
const assert = require('assert');
8+
9+
// Response splitting example, credit: Amit Klein, Safebreach
10+
const str = '/welcome?lang=bar%c4%8d%c4%8aContent­Length:%200%c4%8d%c4%8a%c' +
11+
'4%8d%c4%8aHTTP/1.1%20200%20OK%c4%8d%c4%8aContent­Length:%202' +
12+
'0%c4%8d%c4%8aLast­Modified:%20Mon,%2027%20Oct%202003%2014:50:18' +
13+
'%20GMT%c4%8d%c4%8aContent­Type:%20text/html%c4%8d%c4%8a%c4%8' +
14+
'd%c4%8a%3chtml%3eGotcha!%3c/html%3e';
15+
16+
// Response splitting example, credit: Сковорода Никита Андреевич (@ChALkeR)
17+
const x = 'fooഊSet-Cookie: foo=barഊഊ<script>alert("Hi!")</script>';
18+
const y = 'foo⠊Set-Cookie: foo=bar';
19+
20+
var count = 0;
21+
22+
const server = http.createServer((req, res) => {
23+
switch (count++) {
24+
case 0:
25+
const loc = url.parse(req.url, true).query.lang;
26+
assert.throws(common.mustCall(() => {
27+
res.writeHead(302, {Location: `/foo?lang=${loc}`});
28+
}));
29+
break;
30+
case 1:
31+
assert.throws(common.mustCall(() => {
32+
res.writeHead(200, {'foo' : x});
33+
}));
34+
break;
35+
case 2:
36+
assert.throws(common.mustCall(() => {
37+
res.writeHead(200, {'foo' : y});
38+
}));
39+
break;
40+
default:
41+
assert.fail(null, null, 'should not get to here.');
42+
}
43+
if (count === 3)
44+
server.close();
45+
res.end('ok');
46+
});
47+
server.listen(common.PORT, () => {
48+
const end = 'HTTP/1.1\r\n\r\n';
49+
const client = net.connect({port: common.PORT}, () => {
50+
client.write(`GET ${str} ${end}`);
51+
client.write(`GET / ${end}`);
52+
client.write(`GET / ${end}`);
53+
client.end();
54+
});
55+
});

0 commit comments

Comments
 (0)