Understanding Cross-Site Scripting (XSS) Attacks and Prevention in .NET Core

Cross-Site Scripting (XSS) is a common security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. These scripts execute in the context of the victim’s browser, potentially stealing sensitive information or performing unauthorized actions. In this blog, we’ll explore different types of XSS attacks and discuss prevention techniques using .NET Core.
Types of XSS Attacks
- Stored XSS:
- Attacker injects malicious code (e.g., JavaScript) into a web application’s database.
- When other users view the affected page, the script executes.
- Example: Posting a comment with a script that steals session cookies.
2. Reflected XSS:
- Attacker tricks a user into clicking a specially crafted link.
- The server reflects the input back to the user without proper sanitization.
- Example: A search query that triggers a script execution.
3. DOM-based XSS:
Malicious script manipulates the Document Object Model (DOM) directly.
- Malicious script manipulates the Document Object Model (DOM) directly.
- The attack occurs on the client side.
- Example: Modifying the page’s content using JavaScript.
Prevention Techniques
1. Input Validation
- Validate and sanitize user input:
- Use libraries like
HtmlSanitizer
to strip dangerous tags and attributes. - Avoid using
innerHTML
orouterHTML
directly.
var sanitizer = new HtmlSanitizer();
string userInput = "<script>alert('XSS');</script>";
string safeInput = sanitizer.Sanitize(userInput);
// safeInput will be an empty string as the script tag is removed
2. Output Encoding
- Encode dynamic content before rendering:
- Use Razor syntax (
@Html.Raw
or@Html.Encode
) to prevent script execution.
<p>@Html.Encode(Model.Description)</p>
// This will encode any HTML tags in Model.Description
3. Contextual Output Encoding
- Apply encoding based on the context:
- Use
@Html.AttributeEncode
for attribute values. - Use
@Html.TextArea
for user-generated content within text areas.
<a href="@Html.AttributeEncode("http://example.com?param=<script>alert('XSS');</script>")">Link</a>
// The script tag will be encoded as <script>alert('XSS');</script>
4. Content Security Policy (CSP)
- Implement a CSP header to restrict allowed sources for scripts, styles, and other resources.
- Specify allowed domains and disallow inline scripts.
app.Use(async (context, next) => {
context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; script-src 'self' cdn.example.com");
await next();
});
// This CSP header allows scripts only from the same origin and cdn.example.com
5. AntiXss Library
- Use the
Microsoft.Security.Application.AntiXss
library to sanitize input.
Example:
var sanitizedInput = Sanitizer.GetSafeHtmlFragment(input);
// This will sanitize the input to prevent XSS attacks
6. HttpOnly Cookies
- Set cookies as HttpOnly to prevent client-side script access.
Example:
Response.Cookies.Append("session", sessionId, new CookieOptions { HttpOnly = true });
7. Regular Security Updates
- Keep your .NET Core version up to date to benefit from security patches.
- Regularly review and update third-party libraries.
By following these best practices, you can significantly reduce the risk of XSS attacks in your .NET Core applications. Remember that security is an ongoing process, and staying informed about the latest threats and mitigation techniques is crucial.
I hope this blog help to understand XSS and its prevention techniques.