Semgrep csharp rules¶
csharp_deserialization_rule-InsecureDeserialization¶
Summary:
Deserialization of potentially untrusted data
Severity: High
CWE: CWE-502
Description:
The application uses insecure .NET deserialization through formatters like
BinaryFormatter.Deserialize(), SoapFormatter.Deserialize(),
NetDataContractSerializer.Deserialize(), or LosFormatter.Deserialize() with data
that may originate from untrusted sources such as HTTP requests, files, or environment
variables. These legacy .NET formatters can instantiate arbitrary types during
deserialization and execute code through type constructors, property setters, or
serialization callbacks, allowing attackers to achieve remote code execution by
providing specially crafted serialized payloads. Microsoft has officially deprecated
BinaryFormatter and related formatters due to unfixable security vulnerabilities, and
automated exploit tools like ysoserial.net can generate working exploits for these
deserialization vulnerabilities with minimal effort. Object injection through these
formatters can also enable mass assignment attacks where unexpected properties are set
on objects, bypassing security controls or modifying application state.
Remediation:
Consider migrating away from legacy .NET formatters to safer alternatives that do not support arbitrary type instantiation. Use System.Text.Json with JsonSerializer for JSON serialization, which is the recommended approach for new .NET applications and provides built-in security through restricted type handling. For applications requiring binary serialization, consider Protocol Buffers (protobuf-net), MessagePack (MessagePack-CSharp), or Bond, all of which use schema-based serialization without code execution risks. If you must deserialize complex types, use DataContractSerializer or DataContractJsonSerializer with explicitly configured known types through DataContractSerializer.KnownTypes or add types selectively using the knownTypes parameter. When using JSON.NET (Newtonsoft.Json), set TypeNameHandling to TypeNameHandling.None to prevent type information from being processed during deserialization. Never deserialize to base types like Object or dynamic, and always cast to specific expected types after validation. Implement allowlists of permitted types if custom deserialization is required, and consider using SerializationBinder to control type resolution. Apply the principle of least privilege by running deserialization operations with minimal permissions. For more information, see Microsoft's BinaryFormatter security guide at https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide and OWASP's Deserialization Cheat Sheet at https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html
OWASP:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
csharp_deserialization_rule-InsecureDeserializationNewtonsoft¶
Summary:
Deserialization of potentially untrusted data
Severity: High
CWE: CWE-502
Description:
Deserialization attacks exploit the process of reading serialized data and turning it back into an object. By constructing malicious objects and serializing them, an adversary may attempt to:
- Inject code that is executed upon object construction, which occurs during the deserialization process.
- Exploit mass assignment by including fields that are not normally a part of the serialized data but are read in during deserialization.
When using Newtonsoft deserialization, you should ensure that the TypeNameHandling property is set to None or
use ISerializationBinder to restrict types that can be deserialized.
OWASP:
- A8:2017-Insecure Deserialization
- A08:2021-Software and Data Integrity Failures
csharp_injection_rule-CommandInjection¶
Summary:
Improper neutralization of special elements used in an OS command ('OS Command Injection')
Severity: High
CWE: CWE-78
Description:
The application uses System.Diagnostics.Process.Start() or ProcessStartInfo with
dynamically constructed commands, which can lead to OS command injection. This critical
vulnerability allows adversaries to pass arbitrary commands or arguments to be executed
with the application's privileges, potentially leading to full system compromise. When
user input flows into ProcessStartInfo.FileName, ProcessStartInfo.Arguments, or
Process.Start() without proper validation, attackers can inject shell metacharacters
or modify the intended command execution flow.
Remediation:
Consider replacing OS command execution with native .NET libraries that implement
the same functionality, as this eliminates the risk of command injection entirely.
If OS commands must be executed, recommended to use a hardcoded allowlist of
executable paths and arguments, never allowing user input to influence the process
name or command structure. When passing data to commands, consider using indirect
references such as generating a random filename with Guid.NewGuid() or using a
lookup table where user input provides a key rather than the actual value. Always
set ProcessStartInfo.UseShellExecute to false to prevent shell interpretation
of metacharacters. Ensure full absolute paths are used for FileName (e.g.,
"C:\App\Tool.exe") to prevent untrusted search path vulnerabilities (CWE-426).
For more information, see OWASP's OS Command Injection Defense Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_other_rule-UnsafeXSLTSettingUsed¶
Summary:
XML injection (aka Blind XPath injection)
Severity: High
CWE: CWE-91
Description:
Detected XsltSettings with EnableScript or EnableDocumentFunction set to true.
These settings enable code execution within XSL stylesheets, allowing adversaries who
can influence the loaded XSL document to directly inject and execute malicious code.
This can lead to complete system compromise through arbitrary code execution.
Remediation:
Consider setting both XsltSettings.EnableScript and
XsltSettings.EnableDocumentFunction to false to prevent code execution within XSL
stylesheets. Recommended to never process user-supplied XSL style sheets. If the
application must calculate values from XML input, consider modifying the XML
document prior to running XslCompiledTransform.Transform() instead of using XSL
scripts to execute functions.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_crypto_rule-CertificateValidationDisabled¶
Summary:
Certificate validation disabled
Severity: Medium
CWE: CWE-295
Description:
The ServicePointManager.ServerCertificateValidationCallback event has been set
to always return true, which effectively disables the validation of server
certificates. This allows an adversary positioned between the application and the
target host to intercept potentially sensitive information or transmit malicious
data through man-in-the-middle attacks. When certificate validation is disabled,
the application cannot verify the identity of the server it's communicating with,
making it vulnerable to impersonation attacks.
Remediation:
Consider removing the callback function that unconditionally returns true to allow normal certificate validation to proceed. When no callback is provided, the .NET framework will validate that the certificate name matches the hostname used when creating the request, and that the certificate chain is trusted. If custom certificate validation is required for specific scenarios (such as accepting self-signed certificates in development environments), implement proper validation logic that checks certificate properties like issuer, subject, and expiration date rather than blindly accepting all certificates. For production environments, ensure that only certificates signed by trusted certificate authorities are accepted. Additional guidance available at: system.net.servicepointmanager.servercertificatevalidationcallback
OWASP:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
csharp_crypto_rule-WeakCipherAlgorithm¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application uses weak cryptographic algorithms through
DESCryptoServiceProvider, TripleDESCryptoServiceProvider, or
RC2CryptoServiceProvider classes, or their factory methods. DES uses a 56-bit
key which can be brute-forced with modern computing resources, while TripleDES
(3DES) is deprecated due to its small 64-bit block size making it vulnerable to
sweet32 birthday attacks after processing large amounts of data. RC2 similarly
suffers from a small effective key size and has known cryptanalytic weaknesses.
These algorithms should not be used for protecting sensitive data in modern
applications.
Remediation:
Consider migrating to ChaCha20Poly1305 for .NET 6.0 and later as it provides
authenticated encryption that is faster and easier to use correctly than
alternatives like AesGcm. ChaCha20Poly1305 eliminates the need for manual
cipher mode configuration and provides built-in message authentication. For
applications targeting older .NET Framework versions, AesGcm (AES-256-GCM) is
recommended, though it requires careful nonce management since nonce reuse leads
to catastrophic security failures. Both alternatives require generating
cryptographically secure random keys and nonces using
RandomNumberGenerator.Fill() rather than weaker random number generators. When
migrating legacy code, ensure that existing encrypted data is properly migrated
or that the application maintains backward compatibility for decryption while
encrypting new data with the stronger algorithm.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
csharp_crypto_rule-WeakCipherMode¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application configures cryptographic operations using weak CipherMode
settings (ECB, CBC, OFB, CFB, or CTS) which do not provide authenticated
encryption. Without built-in message integrity, an adversary can potentially
tamper with ciphertext to manipulate the resulting plaintext or mount padding
oracle attacks, particularly against CBC mode. ECB mode is especially problematic
as it encrypts identical plaintext blocks to identical ciphertext blocks,
revealing patterns in the encrypted data. These cipher modes require developers to
manually implement message authentication, which is error-prone and often done
incorrectly.
Remediation:
Consider migrating to authenticated encryption algorithms that provide built-in
message integrity rather than manually configuring CipherMode. For .NET 6.0
and later, ChaCha20Poly1305 is recommended as it combines encryption and
authentication in a single operation that is both faster and easier to use
correctly than older alternatives. For applications on older .NET Framework
versions, AesGcm provides AES-256-GCM authenticated encryption, though it
requires careful nonce management since reusing a nonce with the same key causes
catastrophic security failures. Both alternatives eliminate the need to
separately implement HMAC or other message authentication codes. When migrating
from CBC or other modes, ensure that nonces are generated using
RandomNumberGenerator.Fill() and stored alongside the ciphertext for
decryption.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
csharp_crypto_rule-WeakHashingFunction¶
Summary:
Use of a broken or risky cryptographic algorithm (SHA1/MD5)
Severity: Medium
CWE: CWE-327
Description:
The application uses cryptographically broken hash algorithms through
MD5CryptoServiceProvider, SHA1CryptoServiceProvider, or their factory methods
like System.Security.Cryptography.MD5.Create() and
System.Security.Cryptography.SHA1.Create(). MD5 is severely compromised with
practical collision attacks demonstrated since 2004, while SHA1 collision attacks
became practical in 2017. Both algorithms should never be used for security
purposes including password storage, digital signatures, certificate generation, or
integrity verification. An attacker can craft two different inputs that produce the
same hash output, allowing forgery and integrity bypass attacks.
Remediation:
Consider migrating to purpose-specific cryptographic functions rather than
general-purpose hash algorithms. For password storage, use Rfc2898DeriveBytes
(PBKDF2) with a high iteration count (at least 600,000 iterations for HMAC-SHA1,
or 210,000 for HMAC-SHA256/SHA512) rather than directly hashing passwords.
PBKDF2 applies salting and key stretching to resist brute-force attacks. For
general-purpose cryptographic hashing, use SHA-256 or SHA-512 from the
System.Security.Cryptography namespace. When comparing hash values, use
CryptographicOperations.FixedTimeEquals() to prevent timing attacks that could
leak information about the hash value. Note that while vetted Argon2id
implementations may become available in the future, PBKDF2 remains a secure
choice when configured with appropriate parameters. Additional guidance available
at https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
csharp_crypto_rule-WeakRNG¶
Summary:
Use of cryptographically weak Pseudo-Random Number Generator (PRNG)
Severity: Medium
CWE: CWE-338
Description:
The application uses the Random class to generate random values, which is a
pseudo-random number generator (PRNG) suitable only for non-security purposes like
gaming or simulations. The Random class uses a deterministic algorithm seeded
with the system clock, making its output predictable if an attacker can guess the
seed value. When these predictable values are used for security-sensitive
operations like generating cryptographic keys, initialization vectors, nonces,
session tokens, or password reset tokens, an attacker may be able to predict future
values and compromise the security of the application.
Remediation:
Consider using RandomNumberGenerator from System.Security.Cryptography for
all security-sensitive random value generation. The RandomNumberGenerator class
provides cryptographically secure random numbers using operating system entropy
sources that are suitable for generating cryptographic keys, nonces, tokens, and
other security-critical values. For generating random integers, use
RandomNumberGenerator.GetInt32(), and for random byte arrays, use
RandomNumberGenerator.Fill() to populate a pre-allocated buffer. These methods
are thread-safe and do not require instantiation or disposal. Reserve the
Random class exclusively for non-security purposes where predictability is
acceptable, such as procedural content generation or gameplay randomization.
Additional documentation available at: system.security.cryptography.randomnumbergenerator
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
csharp_csrf_rule-Csrf¶
Summary:
Potential Cross-Site Request Forgery (CSRF)
Severity: Medium
CWE: CWE-352
Description:
Detected HTTP method handler ([HttpPost], [HttpPut], [HttpDelete], or [HttpPatch])
without the [ValidateAntiForgeryToken] attribute. This allows Cross-Site Request
Forgery (CSRF) attacks where malicious sites can trick authenticated users into
performing unwanted state-changing actions. Attackers can exploit this by crafting forms
or links that submit requests with the victim's session credentials.
Remediation:
Consider adding the [ValidateAntiForgeryToken] attribute to all action methods that
handle state-changing operations (POST, PUT, DELETE, PATCH). This validates that
requests include a valid anti-forgery token, preventing CSRF attacks. Alternatively,
enable the [AutoValidateAntiforgeryTokenAttribute] globally to automatically protect
all state-changing endpoints. For defense-in-depth, also consider configuring session
cookies with the SameSite attribute to restrict cross-site request submission.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
csharp_injection_rule-LdapInjection¶
Summary:
Improper neutralization of special elements used in an LDAP query ('LDAP Injection')
Severity: Medium
CWE: CWE-90
Description:
The application uses System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(),
DirectoryEntry, DirectorySearcher, or SearchRequest with tainted input flowing from
method parameters. LDAP injection attacks exploit user-controlled data in LDAP queries to
manipulate how data is returned from LDAP or Active Directory servers. Even the modern
AccountManagement API remains vulnerable when user input contains LDAP filter
metacharacters such as *, (, ), or null bytes, which can alter query logic and
potentially bypass authentication or access unauthorized directory information.
Remediation:
Consider implementing an LDAP encoding function that escapes special characters before
passing user input to any LDAP query methods. Recommended to encode the backslash
character first (as "\5c"), followed by null ("\00"), open parenthesis ("\28"), close
parenthesis ("\29"), and asterisk ("\2a") to prevent filter injection. This encoding
applies to both the modern System.DirectoryServices.AccountManagement API and the
older DirectorySearcher API. When using UserPrincipal, apply encoding before
setting properties like SamAccountName or DisplayName that will be used in search
operations. For DirectorySearcher.Filter or SearchRequest.Filter, encode all
user-controlled portions of the LDAP filter string. Consider using FindOne() instead
of FindAll() when appropriate to limit result sets and reduce information exposure.
For more information, see OWASP's LDAP Injection Prevention Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_injection_rule-SQLInjection¶
Summary:
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
Severity: Medium
CWE: CWE-89
Description:
The application uses Entity Framework methods like ExecuteSqlRaw(), ExecuteSqlCommand(),
FromSqlRaw(), or database command objects like SqlCommand, OracleCommand, MySqlCommand,
or NpgsqlCommand with dynamically constructed SQL queries. SQL injection allows adversaries
to influence the logic of SQL statements by manipulating user input that flows into query
strings. This critical vulnerability can lead to unauthorized data access, data modification,
authentication bypass, and in some cases execution of operating system commands through
database server features like xp_cmdshell in SQL Server.
Remediation:
Consider using parameterized queries exclusively for all database operations, where
user input is passed as parameters rather than concatenated into SQL strings. For
SqlCommand and similar classes, use the Parameters.Add() method with explicit
SQL types like SqlDbType.NVarChar to safely bind user values. When using Entity
Framework, prefer ExecuteSqlInterpolated() or FromSqlInterpolated() which
automatically parameterize interpolated strings, or use ExecuteSqlRaw() with
explicit parameter objects. For scenarios requiring dynamic table or column names
that cannot be parameterized, recommended to use an allowlist approach with a
dictionary mapping user-supplied keys to valid database identifiers. For dynamic
operators like > or <, consider having users provide symbolic values like "gt"
or "lt" which are then mapped to the actual operators, rather than accepting the
operators directly. Avoid using CommandType.Text with concatenated strings and
never trust user input for database identifiers. For more information, see OWASP's
SQL Injection Prevention Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_injection_rule-XPathInjection¶
Summary:
Improper neutralization of data within XPath expressions ('XPath Injection')
Severity: Medium
CWE: CWE-643
Description:
The application uses XPath query methods like XPathNavigator.SelectNodes(),
XmlDocument.SelectSingleNode(), XPathExpression.Compile(), or LINQ extension methods
like XPathEvaluate(), XPathSelectElement(), and XPathSelectElements() with
dynamically constructed XPath expressions. XPath injection allows adversaries to modify
the structure of XML queries by injecting special characters or XPath syntax, potentially
leading to unauthorized data extraction, information disclosure, or in rare cases
authentication bypass when XPath is used for access control decisions.
Remediation:
Consider migrating to LINQ to XML (System.Xml.Linq) which provides type-safe querying
through methods like Descendants(), Elements(), and Where() that use .NET string
comparison rather than XPath expression evaluation. Recommended to use XDocument or
XElement with standard LINQ methods, where user input is treated as data in filter
predicates rather than as part of the query structure. Avoid using XPathEvaluate(),
XPathSelectElement(), and XPathSelectElements() extension methods from
System.Xml.XPath even within LINQ queries, as these still evaluate XPath expressions
and remain vulnerable to injection. If XPath must be used, consider implementing an
allowlist of valid query patterns and using parameterized approaches where user input
only influences data values, not query structure. Note that XDocument is also safe
from XXE attacks by default as the resolver is disabled. For more information, see
Microsoft's LINQ to XML security documentation at
https://learn.microsoft.com/en-us/dotnet/standard/linq/linq-xml-security and OWASP's
XML security guide at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_injection_rule-XmlDocumentXXEInjection¶
Summary:
Improper restriction of XML external entity reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses System.Xml.XmlDocument to load or parse XML data without explicitly
setting the XmlResolver property to null. XML External Entity (XXE) attacks exploit
XML parsers that resolve external entity references, allowing attackers to read arbitrary
files from the server filesystem, perform Server-Side Request Forgery (SSRF) to internal
network resources, exfiltrate sensitive data to external hosts, or cause Denial of Service
through billion laughs attacks. By default, XmlDocument.Load() and XmlDocument.LoadXml()
in older .NET Framework versions enable external entity resolution, making applications
vulnerable when processing untrusted XML input.
Remediation:
Consider migrating to System.Xml.Linq.XDocument which disables external entity
resolution by default and provides a safer, more modern API for XML processing with
built-in protection against XXE and DoS attacks. If XmlDocument must be used for
legacy compatibility, recommended to explicitly set XmlDocument.XmlResolver = null
immediately after instantiation and before calling any Load() or LoadXml() methods.
Ensure your application targets .NET Framework 4.5.2 or later (released in 2014) which
provides safer defaults, though explicit configuration is still recommended for defense
in depth. For applications processing untrusted XML from external sources, consider
validating XML structure and size before parsing to prevent resource exhaustion attacks.
Avoid using object initializer syntax without explicitly setting XmlResolver = null
in the initializer block. For more information, see OWASP's XML External Entity
Prevention Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_injection_rule-XmlReaderXXEInjection¶
Summary:
Improper restriction of XML external entity reference ('XXE')
Severity: Medium
CWE: CWE-611
Description:
The application uses System.Xml.XmlReader.Create() with XmlReaderSettings configured
to enable DTD processing by setting ProhibitDtd = false or DtdProcessing = DtdProcessing.Parse.
This configuration allows XML External Entity (XXE) attacks that can read arbitrary files,
perform Server-Side Request Forgery (SSRF), exfiltrate data, or cause Denial of Service
through entity expansion attacks. When DTD processing is enabled, attackers can include
malicious external entity declarations in XML documents that reference local files or
remote URLs, which the parser will attempt to resolve during document processing.
Remediation:
Consider setting XmlReaderSettings.DtdProcessing to DtdProcessing.Prohibit instead
of DtdProcessing.Parse to completely disable DTD processing and prevent XXE attacks.
For legacy code using the deprecated ProhibitDtd property, recommended to set it to
true to block DTD processing, though migrating to the DtdProcessing property is
preferred for modern applications. Ensure your application targets .NET Framework 4.5.2
or later (released in 2014) which provides safer XML parsing defaults. If DTD validation
is genuinely required for your use case, consider using DtdProcessing.Ignore which
skips DTD processing but allows the document to contain a DTD declaration, though this
still carries some risk. For maximum security when processing untrusted XML, recommended
to also set XmlReaderSettings.XmlResolver = null to prevent resolution of external
resources even if DTD processing is accidentally enabled. For more information, see
OWASP's XML External Entity Prevention Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_path_rule-PathTraversal¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Medium
CWE: CWE-22
Description:
The application uses user input in System.IO file operations such as
File.Open(), File.ReadAllText(), Directory.GetFiles(), or other file
system methods. If path information comes from user input, attackers can use
path traversal sequences like ../ to access sensitive files, read other users'
data, or gain unauthorized system access.
Remediation:
Consider never using user input directly in file system operations.
Recommended to replace user-supplied filenames with controlled identifiers
like GUIDs. Use Path.GetFullPath() to resolve the complete path and
validate it with StartsWith() against an allowed base directory before any
file operations. This ensures paths remain within restricted directories and
prevents traversal attacks.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
csharp_xss_rule-HtmlElementXss¶
Summary:
Improper neutralization of input during web page generation ('Cross-site Scripting')
Severity: Medium
CWE: CWE-79
Description:
The application is writing user-supplied data from ASP.NET request objects (Request.Form,
Request.QueryString, Request.Cookies, Request.Headers, etc.) directly to HTML output using
dangerous sinks like HtmlHelper.Raw(), IHtmlHelper.Raw(), Response.Write(), or
HtmlTextWriter methods (Write, WriteAttribute, AddAttribute, etc.). This creates a
Cross-Site Scripting (XSS) vulnerability where attackers can inject malicious JavaScript
that executes in victims' browsers. The rule detects taint flow from ASP.NET request
properties to rendering methods that bypass Razor's automatic HTML encoding. Without proper
output encoding, malicious scripts embedded in request parameters, cookies, or headers will
be rendered directly in the HTML, potentially leading to session hijacking, credential theft,
or defacement attacks.
Remediation:
Consider using Razor's automatic HTML encoding by rendering user data through standard
Razor syntax @Model.UserInput instead of @Html.Raw() or Response.Write(). For
ASP.NET Core applications, use System.Text.Encodings.Web.HtmlEncoder.Default.Encode()
to manually encode user input when necessary. If you must use HtmlHelper.Raw(), ensure
the data has been sanitized with a whitelist-based HTML sanitizer like HtmlSanitizer NuGet
package before passing it. For JavaScript contexts, use JavaScriptEncoder.Default.Encode(),
for URLs use UrlEncoder.Default.Encode(), and for HTML attributes use
HtmlEncoder.Default.Encode(). Implement Content Security Policy (CSP) headers with
restrictive directives as defense-in-depth. See Microsoft's XSS prevention guidance at
https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting for additional
context-specific encoding recommendations.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_xss_rule-ScriptXss¶
Summary:
Improper neutralization of input during web page generation ('Cross-site Scripting')
Severity: Medium
CWE: CWE-79
Description:
The application is injecting user-supplied data from ASP.NET request objects directly into
client-side JavaScript by passing it to ScriptManager.RegisterStartupScript(),
ScriptManager.RegisterClientScriptBlock(), or legacy RegisterStartupScript() /
RegisterClientScriptBlock() methods. This creates a Cross-Site Scripting (XSS)
vulnerability in JavaScript context, which is particularly dangerous because attackers can
execute arbitrary JavaScript code without needing to break out of HTML encoding. The rule
detects taint flow from request properties (Form, QueryString, Cookies, Headers, etc.) to
ASP.NET script registration methods. Without JavaScript-specific encoding, malicious input
can manipulate script behavior, access sensitive data, modify the DOM, or perform actions
on behalf of the user.
Remediation:
Consider using System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode() to properly
escape user input before embedding it in JavaScript registered through ScriptManager
methods. For ASP.NET Web Forms, ensure user data is serialized as JSON with proper escaping
using System.Web.Script.Serialization.JavaScriptSerializer or Newtonsoft.Json with
appropriate settings. Avoid string concatenation when building JavaScript - instead, pass
data as JSON objects and parse them client-side. For modern ASP.NET Core applications,
consider passing data through data attributes on HTML elements and reading them with
JavaScript, allowing Razor's automatic encoding to protect the values. Implement Content
Security Policy (CSP) headers with script-src 'self' to prevent inline script execution
as defense-in-depth. See Microsoft's guidance on JavaScript encoding at
https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting for additional
recommendations.
csharp_cookies_rule-CookieWithoutHttpOnlyFlag¶
Summary:
Sensitive cookie without 'HttpOnly' flag
Severity: Low
CWE: CWE-1004
Description:
Detected HttpCookie or Cookie created without the HttpOnly property set to true.
Without this flag, client-side JavaScript can access the cookie value through
document.cookie, enabling attackers to steal session data via Cross-Site Scripting (XSS)
attacks. This exposes sensitive session information to malicious scripts running in the
user's browser.
Remediation:
Consider setting the HttpOnly property to true on all cookies to prevent
client-side JavaScript access. This protects session cookies from XSS attacks by
blocking scripts from reading cookie values via document.cookie. For example, set
someCookie.HttpOnly = true; when creating HttpCookie instances. Additionally,
recommended to also set the Secure flag (HTTPS-only transmission) and SameSite
attribute (CSRF protection) for comprehensive cookie security.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
csharp_cookies_rule-CookieWithoutSSLFlag¶
Summary:
Sensitive cookie in HTTPS session without 'Secure' attribute
Severity: Low
CWE: CWE-614
Description:
Detected HttpCookie created without the Secure property set to true. Without this
flag, the cookie can be transmitted over unencrypted HTTP connections, exposing sensitive
session data to network attackers through man-in-the-middle attacks. This allows
eavesdroppers to intercept and steal cookie values transmitted over insecure channels.
Remediation:
Consider setting the Secure property to true on all cookies to enforce HTTPS-only
transmission. This ensures cookies are only sent over encrypted connections, protecting
them from interception on insecure networks. For example, set
someCookie.Secure = true; when creating HttpCookie instances. This protection is
essential for any application handling sensitive data or authentication tokens over
HTTPS.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
csharp_endpoint_rule-UnvalidatedRedirect¶
Summary:
URL redirection to untrusted site 'open redirect'
Severity: Info
CWE: CWE-601
Description:
Detected redirect methods (Redirect(), RedirectPermanent(), RedirectToRoute(),
RedirectToRoutePermanent(), or RedirectResult) using user-supplied input. Open
redirects are commonly abused in phishing attacks where a legitimate-looking URL
redirects users to malicious sites. This allows attackers to leverage the trusted
domain's reputation to deceive victims.
Remediation:
Consider validating redirect URLs using Url.IsLocalUrl() to ensure they target
the local application only. Recommended to implement an index-based redirect
approach where user input provides a numerical ID that maps to a server-side
maintained list of allowed redirect URLs. Consider maintaining an allowlist of
approved external domains if external redirects are required. Never redirect
clients based on raw user-supplied URLs.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
csharp_password_rule-PasswordComplexity¶
Summary:
Weak password requirements
Severity: Info
CWE: CWE-521
Description:
The application configures weak password requirements by setting properties like
RequiredLength to less than 8 characters, or disabling complexity requirements
such as RequireDigit, RequireLowercase, RequireUppercase, or
RequireNonAlphanumeric. Weak password policies make accounts vulnerable to
brute force and dictionary attacks.
Remediation:
Consider enforcing strong password policies in ASP.NET Core Identity
configuration. Recommended to set options.Password.RequiredLength to at
least 8 characters and enable all complexity requirements:
RequireDigit = true, RequireLowercase = true, RequireUppercase = true,
and RequireNonAlphanumeric = true. Additionally, set
RequiredUniqueChars to at least 1 to ensure password diversity.
OWASP:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
csharp_validation_rule-InputValidation¶
Summary:
ASP.NET input validation disabled
Severity: Info
CWE: CWE-554
Description:
The application uses the [ValidateInput(false)] attribute on a controller
method, which disables ASP.NET's built-in request validation. This prevents the
framework from examining requests for injection attacks such as Cross-Site
Scripting (XSS), leaving the application vulnerable to malicious input.
Remediation:
Consider removing the [ValidateInput(false)] attribute to re-enable ASP.NET
request validation, or explicitly set it to true. If disabling validation is
unavoidable for legitimate scenarios, recommended to implement manual input
validation and ensure proper output encoding is applied before rendering user
input in views. Never output unvalidated user input directly to prevent XSS
vulnerabilities.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration