From a4e923b7fcc0313a0894740ba0ef60ba12ba9573 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Thu, 9 Oct 2014 13:55:29 -0700 Subject: [PATCH] Sanitize the string tag passed to DOM components Because we're using innerHTML to generate DOM Elements, we need to make sure that the tag is sane and doesn't try to do injection. This wouldn't be an issue if we used document.createElement instead. --- src/browser/ui/ReactDOMComponent.js | 17 ++++++++++++- .../ui/__tests__/ReactDOMComponent-test.js | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/browser/ui/ReactDOMComponent.js b/src/browser/ui/ReactDOMComponent.js index a7536c71c7..c7a93ab85c 100644 --- a/src/browser/ui/ReactDOMComponent.js +++ b/src/browser/ui/ReactDOMComponent.js @@ -121,6 +121,21 @@ var omittedCloseTags = { // NOTE: menuitem's close tag should be omitted, but that causes problems. }; +// We accept any tag to be rendered but since this gets injected into abitrary +// HTML, we want to make sure that it's a safe tag. +// http://www.w3.org/TR/REC-xml/#NT-Name + +var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset +var validatedTagCache = {}; +var hasOwnProperty = {}.hasOwnProperty; + +function validateDangerousTag(tag) { + if (!hasOwnProperty.call(validatedTagCache, tag)) { + invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag); + validatedTagCache[tag] = true; + } +} + /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are @@ -137,7 +152,7 @@ var omittedCloseTags = { * @extends ReactMultiChild */ function ReactDOMComponent(tag) { - // TODO: DANGEROUS this tag should be sanitized. + validateDangerousTag(tag); this._tag = tag; this.tagName = tag.toUpperCase(); } diff --git a/src/browser/ui/__tests__/ReactDOMComponent-test.js b/src/browser/ui/__tests__/ReactDOMComponent-test.js index bfe19a021a..a5854bb100 100644 --- a/src/browser/ui/__tests__/ReactDOMComponent-test.js +++ b/src/browser/ui/__tests__/ReactDOMComponent-test.js @@ -453,4 +453,28 @@ describe('ReactDOMComponent', function() { }); }); + describe('tag sanitization', function() { + it('should throw when an invalid tag name is used', () => { + var React = require('React'); + var ReactTestUtils = require('ReactTestUtils'); + var hackzor = React.createElement('script tag'); + expect( + () => ReactTestUtils.renderIntoDocument(hackzor) + ).toThrow( + 'Invariant Violation: Invalid tag: script tag' + ); + }); + + it('should throw when an attack vector is used', () => { + var React = require('React'); + var ReactTestUtils = require('ReactTestUtils'); + var hackzor = React.createElement('div> ReactTestUtils.renderIntoDocument(hackzor) + ).toThrow( + 'Invariant Violation: Invalid tag: div>