From aa578f14a08bdaf67a36f36b5e81fe0f1035fe38 Mon Sep 17 00:00:00 2001 From: chenguanyu Date: Fri, 3 Dec 2021 20:10:11 +0800 Subject: [PATCH 1/3] feat: check http header is invalid before set --- lib/middlewares/csp.js | 9 +++++++-- lib/utils.js | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/middlewares/csp.js b/lib/middlewares/csp.js index f5a37c0..ee16bb1 100644 --- a/lib/middlewares/csp.js +++ b/lib/middlewares/csp.js @@ -62,7 +62,12 @@ module.exports = options => { } } const headerString = bufArray.join(';'); - ctx.set(finalHeader, headerString); - ctx.set('x-csp-nonce', ctx.nonce); + + if (utils.checkInvalidHeaderChar(headerString)) { + ctx.set(finalHeader, headerString); + ctx.set('x-csp-nonce', ctx.nonce); + } else { + console.warn('Invalid character in header content :', finalHeader); + } }; }; diff --git a/lib/utils.js b/lib/utils.js index 22a6aa3..9892daa 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -165,3 +165,9 @@ function getContains(ip) { } return IP.cidrSubnet(ip).contains; } + +const HEADER_CHAR_REGEX = /[^\t\x20-\x7e\x80-\xff]/; + +exports.checkInvalidHeaderChar = function(val) { + return HEADER_CHAR_REGEX.test(val); +}; From 5614326f683655458ad27a21e529232a687a5c9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E7=85=AE=E9=85=92?= <501205587@qq.com> Date: Sun, 5 Dec 2021 10:56:11 +0800 Subject: [PATCH 2/3] fix: checkInvalidHeaderChar conditions --- lib/middlewares/csp.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/middlewares/csp.js b/lib/middlewares/csp.js index ee16bb1..dcf29d9 100644 --- a/lib/middlewares/csp.js +++ b/lib/middlewares/csp.js @@ -63,7 +63,7 @@ module.exports = options => { } const headerString = bufArray.join(';'); - if (utils.checkInvalidHeaderChar(headerString)) { + if (!utils.checkInvalidHeaderChar(headerString)) { ctx.set(finalHeader, headerString); ctx.set('x-csp-nonce', ctx.nonce); } else { From 1a71cbfeeb032194e8707e45798cbc2b8aba0971 Mon Sep 17 00:00:00 2001 From: chenguanyu Date: Sun, 5 Dec 2021 11:17:51 +0800 Subject: [PATCH 3/3] feat: add utils.checkInvalidHeaderChar unit test --- test/utils.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/utils.test.js b/test/utils.test.js index cab62d1..48d43d3 100644 --- a/test/utils.test.js +++ b/test/utils.test.js @@ -251,4 +251,17 @@ describe('test/utils.test.js', function() { }); }); }); + + describe('utils.checkInvalidHeaderChar', function() { + it('Invalid character return true', function() { + utils.checkInvalidHeaderChar('aaaaa\naaaaaa').should.equal(true); + utils.checkInvalidHeaderChar('aaaa\raaaaa').should.equal(true); + }); + + it('character return false', function() { + utils.checkInvalidHeaderChar('aaaaa').should.equal(false); + utils.checkInvalidHeaderChar('aaaa aaaaa').should.equal(false); + utils.checkInvalidHeaderChar('aaaaaaaaa').should.equal(false); + }); + }); });