Skip to content

Commit

Permalink
fix: xss security issue under invalid json data
Browse files Browse the repository at this point in the history
  • Loading branch information
chenckang committed Mar 13, 2019
1 parent 8976384 commit 66526b9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
4 changes: 4 additions & 0 deletions example/app/Example.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ ReactDOM.render(
<h4>Custom theme:</h4>
<JSONPretty className="test-3" themeClassName="custom-json-pretty" data={obj3}></JSONPretty>
</div>
<div>
<h4>XSS pretection</h4>
<JSONPretty id="json-pretty" style={{fontSize: "1.1em"}} data={{data: "<img onerror='alert(document.cookie)' src='invalid-image' />"}}></JSONPretty>
</div>
</div>,
document.getElementById('example')
);
27 changes: 25 additions & 2 deletions src/JSONPretty.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,31 @@ interface IProps {
silent?: boolean;
}

function getStyleValue(name: string, theme: ITheme): string {
return theme ? theme[name] || '' : '';
}

function getStyle(name: string, theme: ITheme): string {
return theme ? theme[name] ? ` style="${theme[name]}"` : '' : '';
const value = getStyleValue(name, theme);
return value ? ` style="${value}"` : '';
}

const xssmap: {[key: string]: string} = {
'"': '&quot;',
'\'': '&apos;',
'&': '&amp;',
'>': '&gt;',
'<': '&lt',
};

function xss(s: string): string {
if (!s) {
return s;
}

return s.replace(/<|>|&|"|'/g, (m) => {
return xssmap[m];
});
}

class JSONPretty extends React.Component<IProps, {}> {
Expand Down Expand Up @@ -52,7 +75,7 @@ class JSONPretty extends React.Component<IProps, {}> {
return(
<div {...rest} dangerouslySetInnerHTML={
{__html:
`<pre class=${themeClassName}${getStyle('main', theme)}>${obj}</pre>`
`<pre class=${themeClassName}${getStyle('main', theme)}>${xss(obj)}</pre>`
}
}>
</div>
Expand Down
8 changes: 6 additions & 2 deletions tests/JSONPretty.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,6 @@ test('invalid json', () => {
test('invalid space', () => {
const box = shallow(<JSONPretty json={'12345'} space={NaN}></JSONPretty>);

console.log(box.html());

`<div><pre class=__json-pretty__><span class=__json-value__>12345</span></pre></div>`
.split('\n')
.map((line) => line.trim())
Expand Down Expand Up @@ -288,3 +286,9 @@ test('complex object with format', () => {
expect(box.html()).to.include(line);
});
});

test('xss pretection', () => {
const data = `{data: \"<img onerror='alert(document.cookie)' src='invalid-image' />}`;
const box = shallow(<JSONPretty json={data}></JSONPretty>);
expect(box.html()).to.eql('<div><pre class=__json-pretty__>{data: &quot;&ltimg onerror=&apos;alert(document.cookie)&apos; src=&apos;invalid-image&apos; /&gt;}</pre></div>');
});

0 comments on commit 66526b9

Please sign in to comment.