Enjoy Sharing Technology!

Software,Develope,Devops, Security,TroubleShooting

Friday, November 12, 2021

fortify scan: XML External Entity Injection

An XML External Entity attack is a type of attack against an application that parses XML input. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.

The XML 1.0 standard defines the structure of an XML document. The standard defines a concept called an entity, which is a storage unit of some type. There are a few different types of entities, external general/parameter parsed entity often shortened to external entity, that can access local or remote content via a declared system identifier. The system identifier is assumed to be a URI that can be dereferenced (accessed) by the XML processor when processing the entity. The XML processor then replaces occurrences of the named external entity with the contents dereferenced by the system identifier. If the system identifier contains tainted data and the XML processor dereferences this tainted data, the XML processor may disclose confidential information normally not accessible by the application. Similar attack vectors apply the usage of external DTDs, external stylesheets, external schemas, etc. which, when included, allow similar external resource inclusion style attacks.

Attacks can include disclosing local files, which may contain sensitive data such as passwords or private user data, using file: schemes or relative paths in the system identifier. Since the attack occurs relative to the application processing the XML document, an attacker may use this trusted application to pivot to other internal systems, possibly disclosing other internal content via http(s) requests or launching a CSRF attack to any unprotected internal services. In some situations, an XML processor library that is vulnerable to client-side memory corruption issues may be exploited by dereferencing a malicious URI, possibly allowing arbitrary code execution under the application account. Other attacks can access local resources that may not stop returning data, possibly impacting application availability if too many threads or processes are not released.

Note that the application does not need to explicitly return the response to the attacker for it to be vulnerable to information disclosures. An attacker can leverage DNS information to exfiltrate data through subdomain names to a DNS server that they controls.



Explanation:

XML External Entities attacks benefit from an XML feature to build documents dynamically at the time of processing. An XML entity allows inclusion of data dynamically from a given resource. External entities allow an XML document to include data from an external URI. Unless configured to do otherwise, external entities force the XML parser to access the resource specified by the URI, e.g., a file on the local machine or on a remote system. This behavior exposes the application to XML External Entity (XXE) attacks, which can be used to perform denial of service of the local system, gain unauthorized access to files on the local machine, scan remote machines, and perform denial of service of remote systems.

The following XML document shows an example of an XXE attack.

<?xml version="1.0" encoding="ISO-8859-1"?>

 <!DOCTYPE foo [

  <!ELEMENT foo ANY >

  <!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo>

This example could crash the server (on a UNIX system), if the XML parser attempts to substitute the entity with the contents of the /dev/random file.

Recommendations:

The XML unmarshaller should be configured securely so that it does not allow external entities as part of an incoming XML document.

To avoid XXE injection do not use unmarshal methods that process an XML source directly as java.io.File, java.io.Reader or java.io.InputStream. Parse the document with a securely configured parser and use an unmarshal method that takes the secure parser as the XML source as shown in the following example:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

DocumentBuilder db = dbf.newDocumentBuilder();

Document document = db.parse(<XML Source>);

Model model = (Model) u.unmarshal(document);


Share:

fortify scan: Resource Injection

This attack consists of changing resource identifiers used by an application in order to perform a malicious task. When an application defines a resource type or location based on user input, such as a file name or port number, this data can be manipulated to execute or access different resources. The resource type affected by user input indicates the content type that may be exposed. For example, an application that permits input of special characters like period, slash, and backslash is risky when used in conjunction with methods that interact with the filesystem.

The resource injection attack differs from Path Manipulation as resource injection focuses on accessing resources other than the local filesystem, while Path Manipulation focuses on accessing the local filesystem.

Explanation:

A resource injection issue occurs when the following two conditions are met:

1.An attacker is able to specify the identifier used to access a system resource.

For example, an attacker may be able to specify a port number to be used to connect to a network resource.

2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted.

For example, the program may give the attacker the ability to transmit sensitive information to a third-party server.

Note: Resource injections involving resources stored on the file system are reported in a separate category named path manipulation. See the path manipulation description for further details of this vulnerability.

Example 1: The following code uses a port number read from an HTTP request to create a socket.

String remotePort = request.getParameter("remotePort");

...

ServerSocket srvr = new ServerSocket(remotePort);

Socket skt = srvr.accept();

...

Some think that in the mobile world, classic web application vulnerabilities, such as resource injection, do not make sense -- why would the user attack themself? However, keep in mind that the essence of mobile platforms is applications that are downloaded from various sources and run alongside each other on the same device. The likelihood of running a piece of malware next to a banking application is high, which necessitates expanding the attack surface of mobile applications to include inter-process communication.

Example 2: The following code uses a URL read from an Android intent to load the page in WebView.

...

WebView webview = new WebView(this);

setContentView(webview);

        String url = this.getIntent().getExtras().getString("url");

webview.loadUrl(url);

...

The kind of resource affected by user input indicates the kind of content that may be dangerous. For example, data containing special characters like period, slash, and backslash are risky when used in methods that interact with the file system. Similarly, data that contains URLs and URIs is risky for functions that create remote connections.

Recommendations:

The best way to prevent resource injection is with a level of indirection: create a list of legitimate resource names that a user is allowed to specify, and only allow the user to select from the list. With this approach the input provided by the user is never used directly to specify the resource name.

In some situations this approach is impractical because the set of legitimate resource names is too large or too hard to maintain. Programmers often resort to implementing a deny list in these situations. A deny list is used to selectively reject or escape potentially dangerous characters before using the input. However, any such list of unsafe characters is likely to be incomplete and will almost certainly become out of date. A better approach is to create a list of characters that are permitted to appear in the resource name and accept input composed exclusively of characters in the approved set.

Tips:

1. If the program is performing custom input validation you are satisfied with, use the Fortify Custom Rules Editor to create a cleanse rule for the validation routine.

2. Implementation of an effective deny list is notoriously difficult. One should be skeptical if validation logic requires implementing a deny list. Consider different types of input encoding and different sets of metacharacters that might have special meaning when interpreted by different operating systems, databases, or other resources. Determine whether or not the deny list can be updated easily, correctly, and completely if these requirements ever change.

3. A number of modern web frameworks provide mechanisms to perform user input validation (including Struts and Spring MVC). To highlight the unvalidated sources of input, Fortify Secure Coding Rulepacks dynamically re-prioritize the issues Fortify Static Code Analyzer reports by lowering their probability of exploit and providing pointers to the supporting evidence whenever the framework validation mechanism is in use. We refer to this feature as Context-Sensitive Ranking. To further assist the Fortify user with the auditing process, the Fortify Software Security Research group makes available the Data Validation project template that groups the issues into folders based on the validation mechanism applied to their source of input.



Share:

fortify scan: Log Forging

In the most benign case, an attacker may be able to insert false entries into the log file by providing the application with input that includes appropriate characters. If the log file is processed automatically, the attacker can render the file unusable by corrupting the format of the file or injecting unexpected characters. A more subtle attack might involve skewing the log file statistics. Forged or otherwise, corrupted log files can be used to cover an attacker’s tracks or even to implicate another party in the commission of a malicious act.

Explanation:

Log forging vulnerabilities occur when:

1. Data enters an application from an untrusted source.

2. The data is written to an application or system log file.

Applications typically use log files to store a history of events or transactions for later review, statistics gathering, or debugging. Depending on the nature of the application, the task of reviewing log files may be performed manually on an as-needed basis or automated with a tool that automatically culls logs for important events or trending information

Interpretation of the log files may be hindered or misdirected if an attacker can supply data to the application that is subsequently logged verbatim. In the most benign case, an attacker may be able to insert false entries into the log file by providing the application with input that includes appropriate characters. If the log file is processed automatically, the attacker may be able to render the file unusable by corrupting the format of the file or injecting unexpected characters. A more subtle attack might involve skewing the log file statistics. Forged or otherwise, corrupted log files can be used to cover an attacker's tracks or even to implicate another party in the commission of a malicious act. In the worst case, an attacker may inject code or other commands into the log file and take advantage of a vulnerability in the log processing utility

Example 1: The following web application code attempts to read an integer value from a request object. If the value fails to parse as an integer, then the input is logged with an error message indicating what happened.

...

String val = request.getParameter("val");

try {

  int value = Integer.parseInt(val);

}

catch (NumberFormatException nfe) {

  log.info("Failed to parse val = " + val);

}

...

If a user submits the string "twenty-one" for val, the following entry is logged:

INFO: Failed to parse val=twenty-one

However, if an attacker submits the string "twenty-one%0a%0aINFO:+User+logged+out%3dbadguy", the following entry is logged:

INFO: Failed to parse val=twenty-one

INFO: User logged out=badguy

Clearly, attackers may use this same mechanism to insert arbitrary log entries.

Some think that in the mobile world, classic web application vulnerabilities, such as log forging, do not make sense -- why would the user attack themself? However, keep in mind that the essence of mobile platforms is applications that are downloaded from various sources and run alongside each other on the same device. The likelihood of running a piece of malware next to a banking application is high, which necessitates expanding the attack surface of mobile applications to include inter-process communication.

Example 2: The following code adapts Example 1 to the Android platform.

...

String val = this.getIntent().getExtras().getString("val");

try {

int value = Integer.parseInt();

}

catch (NumberFormatException nfe) {

Log.e(TAG, "Failed to parse val = " + val);

        }

...

Recommendations:

Prevent log forging attacks with indirection: create a set of legitimate log entries that correspond to different events that must be logged and only log entries from this set. To capture dynamic content, such as users logging out of the system, always use server-controlled values rather than user-supplied data. This ensures that the input provided by the user is never used directly in a log entry.

Example 1 can be rewritten to use a pre-defined log entry that corresponds to a NumberFormatException as follows:

...

public static final String NFE = "Failed to parse val. The input is required to be an integer value."

...

String val = request.getParameter("val");

        try {

                int value = Integer.parseInt(val);

        }

        catch (NumberFormatException nfe) {

                log.info(NFE);

        }

..

And here is an Android equivalent:

...

public static final String NFE = "Failed to parse val. The input is required to be an integer value."

...

        String val = this.getIntent().getExtras().getString("val");

        try {

                int value = Integer.parseInt();

        }

        catch (NumberFormatException nfe) {

                Log.e(TAG, NFE);

        }

...

In some situations this approach is impractical because the set of legitimate log entries is too large or complicated. In these situations, developers often fall back on implementing a deny list. A deny list is used to selectively reject or escape potentially dangerous characters before using the input. However, a list of unsafe characters can quickly become incomplete or outdated. A better approach is to create a list of characters that are permitted to appear in log entries and accept input composed exclusively of characters in the approved set. The most critical character in most log forging attacks is the '\n' (newline) character, which should never appear on a log entry allow list.

Tips:

1. Many logging operations are created only for the purpose of debugging a program during development and testing. In our experience, debugging will be enabled, either accidentally or purposefully, in production at some point. Do not excuse log forging vulnerabilities simply because a programmer says "I don't have any plans to turn that on in production".

2. A number of modern web frameworks provide mechanisms to perform user input validation (including Struts and Spring MVC). To highlight the unvalidated sources of input, Fortify Secure Coding Rulepacks dynamically re-prioritize the issues Fortify Static Code Analyzer reports by lowering their probability of exploit and providing pointers to the supporting evidence whenever the framework validation mechanism is in use. We refer to this feature as Context-Sensitive Ranking. To further assist the Fortify user with the auditing process, the Fortify Software Security Research group makes available the Data Validation project template that groups the issues into folders based on the validation mechanism applied to their source of input.


Share:

Appscan:The Secure Attribute is Missing in the Encrypted Session (SSL) Cookie

The Secure Attribute is Missing in the Encrypted Session (SSL) Cookie

  Recently, Appscan has scanned a vulnerability. The Secure attribute is missing in the encrypted session (SSL) cookie, which has been fixed. The summary is as follows:

1.1, attack principle

Any information such as cookies, session tokens, or user credentials sent to the server in clear text may be stolen and later used for identity theft or user disguise. In addition, several privacy regulations point out that user credentials and other information are sensitive Information must always be sent to the Web site in an encrypted manner.

1.2, repair suggestions

   add secure attribute to cookie

1.3, fix the code example

  1) The server is configured as HTTPS SSL

  2) Servlet 3.0 (Java EE 6) web.xml is configured as follows:

  <session-config>

   <cookie-config>

    <secure>true</secure>

   </cookie-config>

  </session-config>

  3) Configure as follows in ASP.NET Web.config:

   <httpCookies requireSSL="true" />

  4) Configure as follows in php.ini

 Session.cookie_secure = True

  or

  Void session_set_cookie_params (int $lifetime [, string $path [, string $domain

                                  [, bool $secure= false [, bool $httponly= false ]]]])

  or

  Bool setcookie (string $name [, string $value [, int $expire = 0 [, string $path

                 [, string $domain [, bool $secure= false [, bool $httponly= false ]]]]]])

  5) Configure as follows in weblogic:

  <wls:session-descriptor>

      <wls:cookie-secure>true</wls:cookie-secure>

       <wls:cookie-http-only>true</wls:cookie-http-only>

   </wls:session-descriptor>

1.4, the actual repair plan

  Solution 1: The project uses the WebShpere server, this can be set in the server:

   In fact, this repair method is the same as 5.2 repair suggestion 2) adding configuration to web.xml. Both of these repair methods can definitely be scanned by Appscan, but the 19 environment needs to support both https and http protocols. The above two solutions will cause the cookies under the http protocol to not be transmitted, resulting in the part under the http protocol The function cannot be used. For the time being, this scheme has been scanned at the expense of not using the functions under the http protocol.

 example2:

   If the cookie is configured with the secure attribute, then the cookie can be transmitted in the https protocol, but not in the http protocol. In the actual system application, two protocols must be supported. Here you can get which protocol is through request.getScheme() (this way https protocol is also http, strange, you can judge whether it is https protocol in the following way)

  String url = req.getHeader("Referer");

  If(url.startsWith("https")){}

   Then judge whether to add this attribute: cookie.setSecure(true).

   With this scheme, you can only set the cookies that your own code responds later, but not the cookies that the container automatically responds to. Therefore it is not used here.

Share:

fortify scan: SQL Injection

SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. use the method  invokes a SQL query built with input that comes from an untrusted source. This call could allow an attacker to modify the statement's meaning or to execute arbitrary SQL commands. 



Explanation:

SQL injection errors occur when:

1. Data enters a program from an untrusted source.

2. The data is used to dynamically construct a SQL query.

Example 1: The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user.

...

string userName = ctx.getAuthenticatedUserName();

string query = "SELECT * FROM items WHERE owner = '"

+ userName + "' AND itemname = '"

+ ItemName.Text + "'";

sda = new SqlDataAdapter(query, conn);

DataTable dt = new DataTable();

sda.Fill(dt);

...

The query intends to execute the following code:

SELECT * FROM items

WHERE owner = <userName>

AND itemname = <itemName>;

However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string "name' OR 'a'='a" for itemName, then the query becomes the following:

SELECT * FROM items

WHERE owner = 'wiley'

AND itemname = 'name' OR 'a'='a';

The addition of the OR 'a'='a' condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:

SELECT * FROM items;

This simplification of the query allows the attacker to bypass the requirement that the query must only return items owned by the authenticated user. The query now returns all entries stored in the items table, regardless of their specified owner.

Example 2: This example examines the effects of a different malicious value passed to the query constructed and executed in Example 1. If an attacker with the user name wiley enters the string "name'); DELETE FROM items; --" for itemName, then the query becomes the following two queries:

SELECT * FROM items

WHERE owner = 'wiley'

AND itemname = 'name';

DELETE FROM items;

Many database servers, including Microsoft(R) SQL Server 2000, allow multiple SQL statements separated by semicolons to be executed at once. While this attack string results in an error on Oracle and other database servers that do not allow the batch-execution of statements separated by semicolons, on databases that do allow batch execution, this type of attack allows the attacker to execute arbitrary commands against the database.

Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder of the statement is to be treated as a comment and not executed [4]. In this case the comment character serves to remove the trailing single-quote left over from the modified query. On a database where comments are not allowed to be used in this way, the general attack could still be made effective using a trick similar to the one shown in Example 1. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a", the following three valid statements will be created:

SELECT * FROM items

WHERE owner = 'wiley'

AND itemname = 'name';


DELETE FROM items;


SELECT * FROM items WHERE 'a'='a';

One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from an allow list of safe values or identify and escape a list of potentially malicious values (deny list). Checking an allow list can be an effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, implementing a deny list is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers may:

    - Target fields that are not quoted

    - Find ways to bypass the need for certain escaped metacharacters

    - Use stored procedures to hide the injected metacharacters

Manually escaping characters in input to SQL queries can help, but it will not make your application secure against SQL injection attacks.

Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to protect against many others. Stored procedures typically help prevent SQL injection attacks by limiting the types of statements that can be passed to their parameters. However, there are many ways around the limitations and many interesting statements that can still be passed to stored procedures. Again, stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks.


Recommendations:

The root cause of a SQL injection vulnerability is the ability of an attacker to change context in the SQL query, causing a value that the programmer intended to be interpreted as data to be interpreted as a command instead. When a SQL query is constructed, the programmer knows what should be interpreted as part of the command and what should be interpreted as data. Parameterized SQL statements can enforce this behavior by disallowing data-directed context changes and preventing nearly all SQL injection attacks. Parameterized SQL statements are constructed using strings of regular SQL, but when user-supplied data needs to be included, they create bind parameters, which are placeholders for data that is subsequently inserted. Bind parameters allow the program to explicitly specify to the database what should be treated as a command and what should be treated as data. When the program is ready to execute a statement, it specifies to the database the runtime values to use for the value of each of the bind parameters, without the risk of the data being interpreted as commands.

The previous example can be rewritten to use parameterized SQL statements (instead of concatenating user supplied strings) as follows:

...
string userName = ctx.getAuthenticatedUserName();
conn = new SqlConnection(_ConnectionString);
conn.Open();
SqlCommand query = new SqlCommand(
             "SELECT * FROM items WHERE itemname=@ItemName
              AND owner=@OwnerName", conn);
query.Parameters.AddWithValue("@ItemName", ItemName.Text);
query.Parameters.AddWithValue("@OwnerName", userName);
SqlDataReader objReader = query.ExecuteReader();
...

More complicated scenarios, often found in report generation code, require that user input affect the command structure of the SQL statement, such as the addition of dynamic constraints in the WHERE clause. Do not use this requirement to justify concatenating user input into query strings. Prevent SQL injection attacks where user input must affect statement command structure with a level of indirection: create a set of legitimate strings that correspond to different elements you might include in a SQL statement. When constructing a statement, use input from the user to select from this set of application-controlled values.
Share:

Thursday, November 11, 2021

fortify scan: Weak Cryptographic Hash (Security Features, Semantic)

 Weak cryptographic hashes cannot guarantee data integrity and should not be used in security-critical contexts.

Explanation:

MD2, MD4, MD5, RIPEMD-160, and SHA-1 are popular cryptographic hash algorithms often used to verify the integrity of messages and other data. However, as recent cryptanalysis research has revealed fundamental weaknesses in these algorithms, they should no longer be used within security-critical contexts.

Effective techniques for breaking MD and RIPEMD hashes are widely available, so those algorithms should 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.

Recommendations:

Discontinue the use of MD2, MD4, MD5, RIPEMD-160, and SHA-1 for data-verification in security-critical contexts. Currently, SHA-224, SHA-256, SHA-384, SHA-512, and SHA-3 are good alternatives. However, these variants of the Secure Hash Algorithm have not been scrutinized as closely as SHA-1, so be mindful of future research that might impact the security of these algorithms.


Share:

fortify scan: Server-Side Request Forgery (SSRF)

In a Server-Side Request Forgery (SSRF) attack, the attacker can abuse functionality on the server to read or update internal resources. The attacker can supply or modify a URL which the code running on the server will read or submit data to, and by carefully selecting the URLs, the attacker may be able to read server configuration such as AWS metadata, connect to internal services like http enabled databases or perform post requests towards internal services which are not intended to be exposed. 



Server-Side Request Forgery occurs when an attacker can influence a network connection made by the application server. The network connection will originate from the application server's internal IP and an attacker can use this connection to bypass network controls and scan or attack internal resources that are not otherwise exposed.

Example: In the following example, an attacker can control the URL to which the server is connecting.

string url = Request.Form["url"];

HttpClient client = new HttpClient();

HttpResponseMessage response = await client.GetAsync(url);

The attacker's ability to hijack the network connection depends on the specific part of the URI that can be controlled, and on the libraries used to establish the connection. For example, controlling the URI scheme lets the attacker use protocols different from http or https like:

- up://

- ldap://

- jar://

- gopher://

- mailto://

- ssh2://

- telnet://

- expect://


An attacker can leverage this hijacked network connection to perform the following attacks:

- Port Scanning of intranet resources.

- Bypass firewalls.

- Attack vulnerable programs running on the application server or on the intranet.

- Attack internal/external web applications using Injection attacks or CSRF.

- Access local files using file:// scheme.

- On Windows systems, file:// scheme and UNC paths can allow an attacker to scan and access internal shares.

- Perform a DNS cache poisoning attack.

Recommendations:

Do not establish network connections based on user-controlled data and ensure that the request is being sent to the expected destination. If user data is necessary to build the destination URI, use  a level of indirection: create a list of legitimate resource names that a user is allowed to specify, and only allow the user to select from the list. With this approach the input provided by the user is never used directly to specify the resource name.

In some situations this approach is impractical because the set of legitimate resource names is too large or too hard to maintain. Programmers often resort to implementing a deny list in these situations. A deny list is used to selectively reject or escape potentially dangerous characters before using the input. However, any such list of unsafe characters is likely to be incomplete and will almost certainly become out of date. A better approach is to create a list of characters that are permitted to appear in the resource name and accept input composed exclusively of characters in the approved set.

Also, if required, make sure that the user input is only used to specify a resource on the target system but that the URI scheme, host, and port is controlled by the application. This way the damage that an attacker is able to do will be significantly reduced.


Share:

Search This Blog

Weekly Pageviews

Translate