|
| 1 | +--- |
| 2 | +description: Enforces security best practices for .NET applications built with ASP.NET Core, focusing on preventing top CWEs. |
| 3 | +globs: **/*.cs, **/*.cshtml, **/*.json, **/*.xml # Target .NET specific files |
| 4 | +alwaysApply: false |
| 5 | +--- |
| 6 | +# Security Best Practices for .NET/ASP.NET Core Applications |
| 7 | + |
| 8 | +As a security-aware developer, generate secure .NET code using ASP.NET Core that inherently prevents top security weaknesses. |
| 9 | +Focus on making the implementation inherently safe rather than merely renaming methods with "secure_" prefixes. |
| 10 | +Use inline comments to clearly highlight critical security controls, implemented measures, and any security assumptions made in the code. |
| 11 | +Adhere strictly to best practices from OWASP, with particular consideration for the OWASP ASVS guidelines. |
| 12 | +**Avoid Slopsquatting**: Be careful when referencing or importing packages. Do not guess if a package exists. Comment on any low reputation or uncommon packages you have included. |
| 13 | + |
| 14 | +### CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') |
| 15 | +**Summary:** The application allows untrusted input to be rendered directly in a web page without proper encoding, leading to execution of malicious scripts in the user's browser. |
| 16 | +**Mitigation Rule:** Always perform context-sensitive output encoding for all untrusted data before rendering it in HTML, JavaScript, CSS, or URLs. For HTML output, rely on ASP.NET Core Razor's automatic encoding or explicitly use `System.Net.WebUtility.HtmlEncode`. For JavaScript contexts, use `System.Text.Encoders.Web.JavaScriptEncoder.Default.Encode`. For URL encoding, use `System.Net.WebUtility.UrlEncode`. Additionally, implement robust input validation to restrict data to expected formats and values, although validation does not replace output encoding. |
| 17 | + |
| 18 | +### CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') |
| 19 | +**Summary:** The application constructs SQL queries using concatenated untrusted input, allowing attackers to manipulate database queries. |
| 20 | +**Mitigation Rule:** Prevent SQL injection by using parameterized queries or object-relational mappers (ORMs) like Entity Framework Core for all database interactions. Never concatenate untrusted user input directly into SQL strings. When using ADO.NET, always define `SqlParameter` objects and assign user input to their values. |
| 21 | + |
| 22 | +### CWE-352: Cross-Site Request Forgery (CSRF) |
| 23 | +**Summary:** The application lacks mechanisms to verify that a web request was intentionally sent by the authenticated user, allowing attackers to trick users into performing unwanted actions. |
| 24 | +**Mitigation Rule:** Protect against CSRF attacks on state-changing requests (e.g., POST, PUT, DELETE) by implementing ASP.NET Core's Anti-Forgery tokens. Include the `[ValidateAntiForgeryToken]` attribute on controller actions and ensure the token is present in the form or request headers. For API endpoints that cannot use cookies (e.g., SPA, mobile), implement custom token-based CSRF protection (e.g., custom header tokens). |
| 25 | + |
| 26 | +### CWE-306: Missing Authentication for Critical Function |
| 27 | +**Summary:** The application allows access to sensitive functions or resources without requiring proper authentication, enabling unauthorized access. |
| 28 | +**Mitigation Rule:** Enforce authentication and authorization on all sensitive endpoints and resources. Use ASP.NET Core Identity for robust user management and authentication. Apply `[Authorize]` attributes to controllers and actions that require authenticated access, and implement policy-based authorization for fine-grained access control based on roles, claims, or custom logic. |
| 29 | + |
| 30 | +### CWE-502: Deserialization of Untrusted Data |
| 31 | +**Summary:** The application deserializes untrusted data, which can lead to remote code execution, denial of service, or privilege escalation if the deserialized objects have exploitable constructors or properties. |
| 32 | +**Mitigation Rule:** Avoid deserializing untrusted or untrusted data using unsafe deserializers like `BinaryFormatter`, `NetDataContractSerializer`, or `SoapFormatter`. Prefer secure-by-default serialization mechanisms such as `System.Text.Json` or `Newtonsoft.Json` with appropriate security configurations (e.g., `TypeNameHandling.None` for Newtonsoft.Json). Only deserialize data from trusted sources, and validate the integrity and authenticity of serialized data if possible. |
| 33 | + |
| 34 | +### CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') |
| 35 | +**Summary:** The application uses untrusted input to construct file paths without proper validation, allowing attackers to access or modify arbitrary files outside the intended directory. |
| 36 | +**Mitigation Rule:** Sanitize and validate all user-supplied input used in file path operations. Do not concatenate user input directly into file paths. Use `Path.Combine()` to construct paths safely and then canonicalize and validate the resulting path using `Path.GetFullPath()` to prevent directory traversal. Ensure file operations are performed within a strictly defined and isolated directory, and implement proper access control (ACLs) on file system resources. |
| 37 | + |
| 38 | +### CWE-259: Use of Hard-coded Password |
| 39 | +**Summary:** The application contains sensitive credentials or secrets directly embedded within the source code, making them easily discoverable and compromising security. |
| 40 | +**Mitigation Rule:** Never hardcode secrets, passwords, API keys, or connection strings directly in the source code. Manage all sensitive configuration through secure external mechanisms. For development, use the .NET Secret Manager. For production, leverage secure credential stores like Azure Key Vault, AWS Secrets Manager, or environment variables. Access secrets securely via ASP.NET Core's configuration system, ensuring they are loaded at runtime from protected sources. |
0 commit comments