C# OWASP Top 10: How to Discover Vulnerabilities in a C# Web Application

C# OWASP Top 10: How to Discover Vulnerabilities in a C# Web Application

In this article, you’ll learn the top 10 security issues in web applications, as defined by the Open Web Application Security Project (OWASP Top 10 – 2017). For each issue, you’ll see how C# code can be affected and the rules that Kiuwan applies when analyzing C# code. This post is part of our language-specific series that begins with Discovering Vulnerabilities in a Java Application.

How do you detect vulnerabilities in a C Sharp application? Security threats can lurk in any component of a production application, including insecure servers, network vulnerabilities, improper password management, etc. This article focuses on the top 10 vulnerabilities within the source code of C# web applications, and how you can detect and eliminate them — and even prevent them from occurring at all.

A1: Injection

Injection flaws occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.

There are several Kiuwan rules to verify that your code is not vulnerable to the most common security problems:

  • Avoid non-neutralized user-controlled input in LDAP search filters (OPT.CSHARP.LdapInjection): The software constructs all or part of an LDAP query using externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query when sent to LDAP server.
  • Improper neutralization of special elements used in a SQL Command ‘SQL Injection’ (OPT.CSHARP.SqlInjection): Avoid SQL code formed with non-neutralized user input (vulnerable to SQL Injection attacks). Learn more.
  • Improper neutralization of special elements used in an OS command ‘OS Command Injection’ (OPT.CSHARP.CommandInjection): The software constructs all or part of an operating system (OS) command using externally-controlled input, but it does not neutralize properly the input that could modify the intended command when it is sent to a function that executes the command (e.g. exec(), system(), or the backtick operator).
  • Improper neutralization of data within XPath expressions ‘XPath Injection’ (OPT.CSHARP.XPathInjection): The .NET framework offers an API to execute an XPath search on an XML DOM tree. If the location path depends on non-neutralized user-input, a potential XPath injection vulnerability could be present, enabling user control on the nodes returned by the XPath search functions.

The following video describes the A1 Injection issue in more detail:

A2: Broken authentication and session management

Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys or session tokens, or to exploit other implementation flaws to assume other users’ identities temporarily or permanently.

Kiuwan provides the following rule to verify the correct use of sessions and authentication:

  • Avoid checks on client-side hostname that are not reliable due to DNS poisoning (OPT.CSHARP.SEC.AvoidHostNameChecks): Avoid basing the security of a system on DNS names. Many DNS servers are susceptible to attacks. If your software is running on an affected server, attackers could redirect your network traffic through their computers or make it appear that their IP addresses are part of your domain.

A3: Sensitive data exposure

Many web applications and APIs do not properly protect sensitive data, such as financial, healthcare, tax IDs and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft or other crimes. Sensitive data deserves extra protection, such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.

To protect sensitive data against exposure, you must use secure protocols, like HTTPS. Kiuwan can help to find misconfigurations such as:

  • Insufficient RSA key length (OPT.CSHARP.WeakEncryption): Current cryptography guidelines suggest that key lengths of at least 1024 bits should be used with the RSA algorithm. However, increased computing power and advances in factoring techniques are challenging the security of 1024 bit RSA encryption.
  • Weak cryptographic hash (OPT.CSHARP.WeakCryptographicHash): MD5 and SHA-1 are popular cryptographic hash algorithms often used to verify the integrity of messages and other data. Recent advances in cryptanalysis have discovered weaknesses in both algorithms. Consequently, MD5 and SHA-1 should no longer be relied upon to verify the authenticity of data in security-critical contexts. Techniques for breaking MD5 hashes are advanced and widely available enough that the algorithm must not be relied upon for security. In the case of SHA-1, current techniques still require a significant amount of computational power and are more difficult to implement. However, attackers have found the Achilles heel for the algorithm and techniques for breaking it will likely lead to the discovery of even faster attacks.
  • Generate server-side cookies with adequate security properties (OPT.CSHARP.SEC.UnsafeCookieRule): Checks that cookies generated server-side have the following security properties:
    • Non-persistent – Cookie is not stored persistently by the browser (it is held in memory)
    • HttpOnly – Cookie is not accessible by client-side scripts (not all browsers support this)
    • Secure – Cookie is sent in HTTP/SSL communications only (more difficult to capture on the net)
    • Path – Path should not match certain patterns that allow the transmission to unintended web applications.
    • Domain – Domain should not be too wide so the cookie is sent to unintended servers.

A4: XML external entities (XXE)

Many older or poorly configured XML processors evaluate external entity references within XML documents. External entities can be used to disclose internal files using the file URI handler, internal file shares, internal port scanning, remote code execution, and denial of service attacks.

Kiuwan helps mitigate this vulnerability with the following rule:

  • XML entity injection (OPT.CSHARP.SEC.XMLEntityInjection): In XML parsers, when XML document to parse could be altered by untrusted input, and the untrusted input may alter the Document Type Definition (DTD, embedded or external), the parser should be configured to avoid two kinds of potential attacks:
    • XML entity expansion DoS (XML bomb or “billion laughs attack”), CWE-776, where well-formed DTD with internal entities are expanded exponentially until they exhaust memory.
    • XML external entity injection (XXE), CWE-611, where an external entity controlled by the attacker refers to the URL of a resource that gives unauthorized access to sensitive files on the server machine, or to a resource like /dev/random in Unix systems that, when entity is expanded, leads to a denial-of-service condition.  A variant of this attack is the server-side request forgery (SSRF), where the URL for external DTD or XML-Schema is processed by the URL handler used by the XML parser, allowing the attacker access to an unexpected network resource (for cross-site request forgery attacks or port-scanning enumeration).

Please note that most .Net parsers are not vulnerable by default to XML entity injection attacks because their default settings have both entity expansion and external entity resolution disabled.

XML parsing could be hidden in other frameworks and libraries. For example, with REST, when a resource has an XML representation, the REST framework typically uses an underlying XML parser for processing the request message, which is fully under control of a potential attacker.

To be safe during XML processing coming from untrusted sources, several XML features should be not enabled when configuring the parser.

A5: Broken access control

Restrictions on what authenticated users are allowed to do are often not properly enforced. Attackers can exploit these flaws to access unauthorized functionality and/or data, such as access to other users’ accounts, view sensitive files, modify other users’ data, change access rights, etc

The application code should protect unauthorized data access. Kiuwan supplies the following rule:

  • External control of file name or path (OPT.CSHARP.PathTraversal): Software uses external input to construct a pathname that is intended to identify a file or directory located underneath a restricted parent directory, but the software does not properly neutralize elements within pathname, which may cause the pathname to resolve to a location outside the restricted directory.

A6: Security misconfiguration

Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented and maintained, as defaults are often insecure. Additionally, software should be kept up to date.

Preventing this vulnerability requires paying attention to the source code, but you can also keep in mind:

  • Generate server-side cookies with adequate security properties (OPT.CSHARP.SEC.UnsafeCookieRule): Internet Explorer supports HttpOnly attribute in cookies which prevents client-side scripts from accessing the cookie and therefore local or modify these values. Script attacks often access cookies to steal session identifiers or the authentication token. When the HttpOnly attribute is not set or configured in a Web.Config file using the httpOnlyCookies attribute of the httpCookies element, attackers can more easily access the cookies of the user.

A7: Missing function level access control

XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites or redirect the user to malicious sites.

Kiuwan provides the following rule:

  • Improper neutralization of input during web page generation (‘Cross-site Scripting’) (OPT.CSHARP.CrossSiteScripting): Software places user-controlled input in page content. An attacker could inject a browser script code that is executed in the client browser. The end-user is the attacked subject and the software is the vehicle for the attack. There are two kinds of XSS:
    • Reflected XSS: Attacker causes the victim to supply malicious content to a vulnerable web application, which renders HTML content embedding a malicious script executed in the victim’s browser. A variation of this is named DOM-based XSS, where the vulnerable software does not generate content depending on user input but includes script code that uses user-controlled input.
    • Persistent XSS: Attacker provides malicious content to a vulnerable application, which is stored somewhere. When another user accesses vulnerable pages that embed without proper neutralization the attacker content, script code is executed in the victim’s browser. For this, you should add other input kinds (e.g. file_input and/or database_input) to the ‘inputs’ rule property. The script executed in the victim’s browser could perform malicious activities, like stealing active authentication tokens (sometimes in the form of cookies) and performing operations on an insecure web app (on behalf of the victim) that trusts too much identity artifacts in browser and do not request additional authorization for operations (‘Cross-Site Request Forgery attack’, CSRF). Many browsers could limit the damage via security restrictions (e.g. ‘same-origin policy’), but user browsers generally allow scripting languages (e.g. JavaScript) in their browsers (disabling JavaScript severely limits a web site). For remediation, you must perform data validation (to ensure that user input is valid), data sanitization (to remove HTML tags from user input) and above all output escaping (to remove characters from user input that could make the browser interpret any part of it as executable code). To perform input validation, it is recommended to keep active request validation provided by .NET and constrain the user input depending on expected content. To escape output properly, the context in which content will be rendered is the key. Depending on the context, different techniques should be used, such as:
      – HTML content
      – Attributes in HTML tags.
      – JavaScript.
      – CSS.
      – URLs.

The Microsoft Anti-Cross Site scripting library is a powerful tool for escaping data. Besides a utility set for escaping data in your code, it provides the Security Runtime Engine, an HTTP module that hooks into the page lifecycle and encodes server controls before they appear on the page. Remember that the attacker may encode special HTML/JavaScript characters in rather imaginative ways to escape any “reject bad characters” validation strategy.

A8: Insecure deserialization

Insecure deserialization often leads to remote code execution. Even if deserialization flaws do not result in remote code execution, they can be used to perform attacks, including replay attacks, injection attacks, and privilege escalation attacks.

Kiuwan can detect misconfigurations, such as:

  • Dynamic code injection during object deserialization (OPT.CSHARP.CodeInjectionWithDeserialization): When a serialization library deserializes untrusted content from a certain exchange format (binary, XML, JSON…) to recover the original object graph, attackers may provide attack payloads that may result in unexpected code execution or a denial-of-service condition. (De)serialization of object graphs is a complex issue, due to the object-oriented nature of such graphs: generics, interface fields, polymorphism… Default constructors need to be invoked, fields and properties should be set reflectively, and special constructors, type converters, or serialization callbacks need to be invoked. By controlling the deserialized field values, attackers may abuse the logic of these methods to run arbitrary code. The deserialization library may be abused, so attackers may control the type of reconstructed objects, the library or the GC might call methods on reconstructed objects. Many libraries perform a simple type of control, often involving cast after deserialization.

A9: Using components with known vulnerabilities

Components, such as libraries, frameworks and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.

Kiuwan Insights helps you mitigate these issues by providing a complete inventory of 3rd party software used by your applications, and detailed information on the security, obsolescence and licensing risks of those components.

A10: Insufficient logging & monitoring

Insufficient logging and monitoring, coupled with missing or ineffective integration with incident response, allows attackers to further attack systems, maintain persistence, pivot to more systems, and tamper, extract, or destroy data. Most breach studies show time to detect a breach is over 200 days, typically detected by external parties rather than internal processes or monitoring.

The exploitation of insufficient logging and monitoring is the bedrock of nearly every major incident. Attackers rely on the lack of monitoring and timely response to achieve their goals without being detected. One strategy for determining if you have sufficient monitoring is to examine the logs following penetration testing. The testers’ actions should be recorded sufficiently to understand what damages they may have inflicted.

Learn more in our complete OWASP Top 10 2017 series:

Share this Article

 SUBSCRIBE© 2021 Kiuwan

Get Your FREE Demo of Kiuwan Application Security Today!

Identify and remediate vulnerabilities with fast and efficient scanning and reporting. We are compliant with all security standards and offer tailored packages to mitigate your cyber risk within the SDLC.

Related Posts

© 2024 Kiuwan. All Rights Reserved.