What does it mean when they say React is XSS protected? - reactjs

I read this on the React tutorial. What does this mean?
React is safe. We are not generating HTML strings so XSS protection is the default.
How do XSS attacks work if React is safe? How is this safety achieved?

ReactJS is quite safe by design since
String variables in views are escaped automatically
With JSX you pass a function as the event handler, rather than a string that can contain malicious code
so a typical attack like this will not work
const username = "<img onerror='alert(\"Hacked!\")' src='invalid-image' />";
class UserProfilePage extends React.Component {
render() {
return (
<h1> Hello {username}!</h1>
);
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
but ...
❗❗❗Warning❗❗❗
There are still some XSS attack vectors that you need to handle yourself in React!
1. XSS via dangerouslySetInnerHTML
When you use dangerouslySetInnerHTML you need to make sure the content doesn't contain any javascript. React can't do here anything for you.
const aboutUserText = "<img onerror='alert(\"Hacked!\");' src='invalid-image' />";
class AboutUserComponent extends React.Component {
render() {
return (
<div dangerouslySetInnerHTML={{"__html": aboutUserText}} />
);
}
}
ReactDOM.render(<AboutUserComponent />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
2. XSS via a.href attribute
Example 1: Using javascript:code
Click on "Run code snippet" -> "My Website" to see the result
const userWebsite = "javascript:alert('Hacked!');";
class UserProfilePage extends React.Component {
render() {
return (
<a href={userWebsite}>My Website</a>
)
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Example 2: Using base64 encoded data:
Click on "Run code snippet" -> "My Website" to see the result
const userWebsite = "data:text/html;base64,PHNjcmlwdD5hbGVydCgiSGFja2VkISIpOzwvc2NyaXB0Pg==";
class UserProfilePage extends React.Component {
render() {
const url = userWebsite.replace(/^(javascript\:)/, "");
return (
<a href={url}>My Website</a>
)
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
3. XSS via attacker controlled props
const customPropsControledByAttacker = {
dangerouslySetInnerHTML: {
"__html": "<img onerror='alert(\"Hacked!\");' src='invalid-image' />"
}
};
class Divider extends React.Component {
render() {
return (
<div {...customPropsControledByAttacker} />
);
}
}
ReactDOM.render(<Divider />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Here are more resources
Exploiting Script Injection Flaws in ReactJS Apps
The Most Common XSS Vulnerability in React.js Applications
How Much XSS Vulnerability Protection is React Responsible For?
https://github.com/facebook/react/issues/3473#issuecomment-90594748
https://github.com/facebook/react/issues/3473#issuecomment-91349525
Avoiding XSS in React is Still Hard
Avoiding XSS via Markdown in React

React automatically escapes variables for you... It prevents XSS injection via string HTML with malicious Javascript.. Naturally, inputs are sanitized along with this.
For instance let's say you have this string
var htmlString = '<img src="javascript:alert('XSS!')" />';
if you try to render this string in react
render() {
return (
<div>{htmlString}</div>
);
}
you will literally see on the page the whole string including the <span> element tag. aka in the browser you will see <img src="javascript:alert('XSS!')" />
if you view the source html you would see
<span>"<img src="javascript:alert('XSS!')" />"</span>
Here is some more detail on what an XSS attack is
React basically makes it so you can't insert markup unless you create the elements yourself in the render function... that being said they do have a function that allows such rendering its called dangerouslySetInnerHTML... here is some more detail about it
Edit:
Few things to note, there are ways to get around what React escapes. One more common way is when users define props to your component. Dont extend any data from user input as props!

Related

using state in dangerouslySetInnerHTML react component

I have a string about html builded by react.
I'm trying to implement render this html string through react, and looking for solution to manage state.
below is simple example.
const App = (props) => {
let code = '<b>Will This Work?</b>';
return (
<div dangerouslySetInnerHTML={ {__html: code} }>
</div>
);
}
I want to manage the state of component rendered with dangerouslySetInnerHTML option.
Can i get any ideas about how approach?
What is dangerouslySetInnerHTML?
It is a way to set the children of the component (as text/html).
Can state be used in it?
Yes state can be used with it; However, the innerHTML MUST be vanilla HTML, NOT JSX. An example of this can be seen below:
(click the button to change the state from text to a red div)
The way this is working is because the state can be inserted into a string literal which will then be handled as HTML encoded text.
const App = (props) => {
const [state,setState] = React.useState("something I set with state");
let code = `<b>Will This Work? ${state}</b>`;
return (
<React.Fragment>
<button onClick={()=>{setState("<div style=\"background-color: red; width:50px; height:50px;\"><div>")}}>Click to change state from pure text to an html element</button>
<div dangerouslySetInnerHTML={ {__html: code} }>
</div>
</React.Fragment>
);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.querySelector('.react')
);
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div class='react'></div>
Should you do this?
Probably not. There is a reason it is called dangerouslySetHTML and not safelySetInnerHTML.
See more in the React Docs

Rendering a 'multiple' page App from one React file

Hello fellow SO users !
I have a question about react and trying to display a multiple page application all in one html document but not loading everything at the beginning of course but whenever each one page is accessed.
So here's an example:
return(
<div>{
if something<*MainPage/>
else<*SecondPage/>}
</div> );
Is something like this possible ?
Thank you in advance !
Have a great day !
Yes it is possible, Consider the example code below
class User extends React.Component {
render() {
if (this.props.isGuest) {
return <h1>You are guest</h1>
}else {
return <h1>You are logged in</h1>
}
}
}
ReactDOM.render(<User isGuest={false} />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
As you can see the line: this.props.isGuest
I have passed it false, So you are able to see:
You are logged in

How to add multiple React components to HTML

I wonder if we can add multiple react components into HTML without having the related files usually downloaded with npm, or added to a normal HTML but we add a certain component for a chat app as my attempt here, here is a long example:
<html lang="en">
<head>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component{
state={
messages:[
{ }
],
userId:''
}
addMessage=(message)=>{
message.num = Math.random();
message.id=this.state.messages.id;
let messages = [...this.state.messages, message];
this.setState({
messages })
}
addId=(userId)=>{
this.setState({
userId
})
}
render() {
return (
<div className="appContainer">
<User userId={this.addId} />
<TopSection Users={this.state.userId}/>
<Messages userId = {this.state.userId} messages={this.state.messages}/>
<AddMessage addMessage={this.addMessage} />
</div>
);
}
}
}
const Messages = ({messages, userId}) =>{
const messageList= (messages.length)? (messages.slice(1).map(message=>{
return(
<div className="message" key={message.num}>
<span key={userId.num}>{message.content?(userId):(null)}</span>
<p>{message.content}</p>
</div>
)
})) : (null);
return(
<div className="textContainer">
{messageList}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
</body>
</html>
please let me know if there is away to get this to work.
You mean add components to different dom nodes ?
import {render} from 'reactDOM'
import React from 'react'
import AppOne from './appOne'
import AppTwo from './appTwo'
render(<AppOne />, document.getElementById('appOne'));
render(<AppTwo />, document.getElementById('appTwo'));
React v16 has portals as well for adding componnets to differnt parts of the dom tree

How to embed React Components in html pages

I want build a React component like
class MyComponent extends React.Component {
render(){
return (<div>This is a simple component</div>);
}
}
and use it like
<MyComponent></MyComponent>
in several different pages and even multiple times in a single html page.
I dont want to create a SPA just to enhance my web application's UI with React components.
Use
ReactDOM.render(<MyComponent />, document.getElementById('id'));
You can render in your HTML like this:
<div id="id"></div>
What you are asking for is not possible right now with React, you want to use what is known as web components.
https://webdesign.tutsplus.com/articles/how-to-create-your-own-html-elements-with-web-components--cms-21524
Read this to learn how to.
The other method is obviously
ReactDOM.render(<MyComponent />, document.getElementById('id'));
If you have to stick with React.
In index.jsx change the typical search for element root getElementById and change the logic to a getElementsByTagName scheme.
let elements=document.getElementsByTagName('MyComponent');
for (element of elements){
ReactDOM.render( <MyComponent />, element );
}
Simply adding React components into HTML code is not possible, because <MyComponent></MyComponent> is not HTML at all, it is JSX.
Explaination
JSX is a special syntax that can be 'transpiled' to Javascript, so in essence <MyComponent></MyComponent> will end up beeing Javascript code, which obviously can not just be put into HTML code.
The Javascript code generated from JSX then will be executed and generates actual HTML code.
It is possible to add HTML tags into JSX, because HTML can be interpreted as JSX (and will be transpiled to Javascript as well), like:
class MyComponent extends React.Component {
render(){
return <div>
<h2>HTML in JSX works</h2>
<SomeOtherJsxComponent />
</div>;
}
}
But it is not possible to add JSX into HTML, like:
<body>
<div>
<JsxInHtmlDoesNotWork />
</div>
</body>
React is Javascript, so everything that is necessary to add Javascript functionality to HTML also applies to adding React to HTML.
(nearest) Solution
So what you could do is to move your existing HTML into to some JSX wrapper (which is probably not what you would like to do, because this goes in the direction of creating a SPA, what you don't want), e.g.:
<html><head>
<title>My web site</title>
</head><body>
<h1>Some HTML title</h1>
<p>Some HTML content.</p>
<!-- add a container, where you want to include react components -->
<div id="injected-react-content"></div>
<!-- import the react libraray -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<!-- setup react root component other components -->
<script type="text/babel">
class RootComponent extends React.Component {
render(){
return <div>
<MyComponent />
</div>;
}
}
class MyComponent extends React.Component {
render(){
return (<div>This is a simple component</div>);
}
}
const domContainer = document.querySelector('#injected-react-content');
ReactDOM.render( React.createElement(RootComponent), domContainer );
</script>
</body></html>
For some more background information on how to add React to an existing HTML website, see e.g.:
stackoverflow.com/questions/65917670/how-to-use-react-components-as-part-of-legacy-html-js-app
stackoverflow.com/questions/69607103/react-component-not-displayed-in-html
There are couple of options which can be explored here
parcel bundle
https://javascriptpros.com/creating-react-widgets-embedded-anywhere/
direflow bundle
https://jhinter.medium.com/using-react-based-web-components-in-wordpress-f0d4097aca38

How to render ReactElement in ReactClass?

I want to render some ReactElement in React.creatClass, but it show nothing. Here is my code:
var Users=React.createClass({
render:function () {
var id=React.createElement('span',null,"hello");
var name=React.createElement('input',null,null);
var updateBtn=React.createElement('button',null,'Change');
var deleteBtn=React.createElement('button',null,'Delete');
var ent=React.createElement('br',null,null);
return (
React.createElement('div',{},[id,name,updateBtn,deleteBtn,ent])
);
}
});
And I use this ReactClass in other function like:
var showUsers=React.createElement('Users',{key:"ka",id:"users"},null);
ReactDOM.render(
showUsers,
document.getElementById('show')
);
Why does it not work? Any help will be appreciate!!
Before providing a solution to your problem, I have to say that what you are trying to do here is rather odd. There are many strange and/or bad practices here and you might want to reconsider reading up on tutorials and the documentation before continuing.
The createClass() approach is deprecated as of version 15.5.
You are not using JSX which, while still technically valid, is rather peculiar as it makes coding much easier. Using React without JSX in larger projects might become incredibly cumbersome.
You don't need to provide a key to your Users component, and probably not an id either.
That said, the reason your code doesn't work is because you are passing in a String to the createElement() function instead of the reference to your Users component. Remove the quotes, and it will work:
var Users=React.createClass({
render:function () {
var id=React.createElement('span',null,"hello");
var name=React.createElement('input',null,null);
var updateBtn=React.createElement('button',null,'Change');
var deleteBtn=React.createElement('button',null,'Delete');
var ent=React.createElement('br',null,null);
return (
React.createElement('div',{},[id,name,updateBtn,deleteBtn,ent])
);
}
});
var showUsers=React.createElement(Users, {key:"ka",id:"users"},null);
ReactDOM.render(
showUsers,
document.getElementById('show')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="show"></div>
Here's a snippet of how I would write your app:
class Users extends React.Component {
render() {
return (
<div>
<span>hello</span>
<input />
<button>Change</button>
<button>Delete</button>
<br />
</div>
);
}
}
ReactDOM.render(<Users />, document.getElementById('show'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="show"></div>

Resources