Thursday, July 30, 2020

Implementing Secure Biometric Authentication on Mobile Applications


Nowadays, almost every mobile device has a biometric sensor that allows developers to implement local authentication and also store sensitive data securely through dedicated APIs.
Biometric authentication is generally more secure than classic username/password approach. Anyway it must be considered that a wrong implementation could allow an attacker to easily bypass authentication mechanisms by using hooking techniques which can be performed with tools like Frida, Objection, and other similar utilities.

In this article we are going to expose some common mistakes that developers can make while implementing  biometric authentication and how to implement it in the correct way.


Biometric Authentication in Android

The Android platform introduced the biometric authentication in Android 6.0 (API level 23) with the class FingerprintManager which supported only fingerprint authentication.
In Android 9 (API level 28), the FingerprintManager was deprecated due to the release of android.hardware.biometrics.BiometricPrompt.
Lastly, In Android 10 (API level 29) the biometric authentication is managed through android.hardware.biometrics.BiometricManager.

It is worth considering that the Android platform introduces also the classes androidx.biometric.BiometricManager and androidx.biometric.BiometricPrompt that could be used instead of the previous ones. These classes will automatically query the BiometricManager on devices running Android 10 (API 29) and FingerprintManagerCompat on Android 9.0 (API 28) and prior versions.

The Android platform, unlike iOS, does not allow to save arbitrary data within Keystore. However, it allows to create encryption keys, which are saved in the Keystore. For every key it is possible to define the access criteria.
In order to implement effective biometric authentication, it is therefore necessary to create a key that can be used only after a successful biometric authentication. This key should be used to encrypt and decrypt a sensitive data such as an authentication token.

In order to use the biometric authentication all of the following requirements must be fulfilled:

1) Require the proper permission in the Android Manifest:

<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />


2) Check if the user can authenticate using biometrics:
This includes having a protected lock screen enabled, a biometric hardware available and a biometric identity registered (For instance a fingerprint). The following piece of code shows a sample implementation:

import androidx.biometric.BiometricManager;
. . .
BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate()) {
    case BiometricManager.BIOMETRIC_SUCCESS:
        // User can authenticate using biometrics
        break;
    case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
        // No biometric features available on this device
        break;
    case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
        // Biometric features are currently unavailable
        break;
    case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
        // The user hasn't associated any biometric credentials with their account
        break;
}



3) Check if the application has the correct permissions:

context.checkSelfPermission(Manifest.permission.USE_FINGERPRINT) == PermissionResult.PERMISSION_GRANTED;

context.checkSelfPermission(Manifest.permission.USE_BIOMETRIC) == PermissionResult.PERMISSION_GRANTED;

The most important methods which must be used in order to implement the biometric authentication in Android are the following ones:


1) authenticate (which starts the authentication flow):

biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));


2) onAuthenticationSucceeded (which is called upon a successful authentication):

@Override
public void onAuthenticationSucceeded(
        @NonNull BiometricPrompt.AuthenticationResult result) {
// . . . .
}


The cipher referred in the first parameter of the authenticate method should be used in order to decrypt a secret data which has been previously stored in the device. Such cipher can use both asymmetric and symmetric algorithm.

In the following example we are going to create a key for a cipher which uses AES-CBC-PKCS7.

KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, “AndroidKeyStore”);
keyGenerator.init(new KeyGenParameterSpec.Builder (KEY_ALIAS,
        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
        .setUserAuthenticationRequired(true)
        .setUserAuthenticationValidityDurationSeconds(-1)
        .setInvalidatedByBiometricEnrollment(true)
        .build()
);
keyGenerator.generateKey();


When creating the key for the cipher that will be used in the biometric authentication flow, the most important options are the following ones:

1) setUserAuthenticationRequired(true): available from API level 23, when set to true, the key can be used only if the user has been authenticated. Additionally, the key will become irreversibly invalidated once the secure lock screen is disabled, or when the secure lock screen is forcibly reset. 

2) setUserAuthenticationValidityDurationSeconds(-1): available from API level 23, when set to -1 the key can only be unlocked using a biometric identity. If it is set to a different value, the key can be unlocked using a device screenlock too.

3) setInvalidatedByBiometricEnrollment(true): available only from API level 24, when set to true, the key is irreversibly invalidated when a new biometric is enrolled, or when all existing biometrics are deleted. Consider that the value is true by default.


Before authenticating the user with biometrics, the cipher should be initialized in order to check if the key is still valid. This can be done as follows:

public Cipher getCipherForBiometrics() {
    try {
        final Cipher cipher = Cipher.getInstance(
                       KeyProperties.KEY_ALGORITHM_AES + "/"
                        + KeyProperties.BLOCK_MODE_CBC + "/"
                        + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        final SecretKey key;
        final KeyStore keyStore =  KeyStore.getInstance(“AndroidKeyStore”);
        keyStore.load(null);
        key = (SecretKey) keyStore.getKey(KEY_ALIAS, null);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher;
    } catch (KeyPermanentlyInvalidatedException e) {
        return null;
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to init Cipher", e);
}


Once the cipher is properly initialised it should be used as an argument for the authenticate method in order to start the biometric authentication flow.

. . .
Cipher cipher = getCipherForBiometrics();
if (cipher != null) {
    biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));
. . .


The biometric authentication flow is then managed by the Android platform, and the method onAuthenticationSucceeded is called upon a successful authentication.

It is worth considering that this method can also be called by using hooking techniques and tools such as Frida. The difference between a valid authentication flow and a tampered authentication flow is the BiometricPrompt.CryptoObject.

Indeed, when a valid authentication flow is performed the Android platform properly instantiate the cipher contained within the BiometricPrompt.CryptoObject, and then this must be used to decrypt critical data such as the aforementioned authentication token.

Instead, when this method is called by using hooking techniques the cipher is not properly instantiated and when using it to decrypt the data, an exception will be raised.


@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
        Cipher cipher = result.getCryptoObject().getCipher();
        byte[] decrypted = cipher.doFinal(// get here authentication token encrypted);
        String authenticationToken = decrypted.toString();
        // save the authentication token somewhere
       . . . 
}

This implementation is secure even against hooking techniques because when calling the onAuthenticationSucceeded callback with Frida, the AuthenticationResult object does not contain a valid cipher instance since the used key, that has been defined as accessible only after a biometric authentication, has not been unlocked by the Android OS and the cipher will raise an Exception when trying to decrypt the data.

During the various assessments performed on mobile applications we’ve found different insecure implementation of the biometric authentication that looks like the following one:

@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
        enterApplication(); 
}

This kind of implementation is insecure since does not make use of the  BiometricPrompt.CryptoObject contained in the AuthenticationResult object, but it assumes that the authentication has been properly validated since the method onAuthenticationSucceeded has been called and allows the user to enter the application.

It is worth considering that even implementation that makes use of the BiometricPrompt.CryptoObject could be insecure if they do not decrypt data that are necessary to login the user (such as an authentication token, JWTs and so on). Indeed even Exceptions could be captured using hooking techniques and could be ignored in order to continue the application flow. 


Biometric Authentication in iOS

The iOS platform introduced the biometric authentication starting from iPhone 5s in 2013. At that time it supported only the fingerprint authentication known as Touch ID.

When Apple released the iPhone X, the Face ID was added as biometric option that could be used to authenticate a user.

The biometric authentication flow is usually implemented with the LocalAuthentication framework. It is worth considering however that the LocalAuthentication framework is an event-based procedure and can be bypassed with hooking techniques and tools such as Frida or Objection.

Unlike Android, the iOS platform allows to save arbitrary data within the Keychain defining the access criteria for every stored item.

In order to implement an effective biometric authentication, it is suggested to use the Keychain methods instead of the LocalAuthentication framework. Such approach consists in storing sensitive data (such as an authentication token) within the Keychain, and defining the proper access criteria so that the data can be used only after a successful biometric authentication.

In order to use the biometric authentication, it is required to check if the biometric hardware is available and if the user has enrolled biometric identitites. This can be done using the canEvaluatePolicy method as shown below:

var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { // handle biometric authentication . . .

The canEvaluatePolicy method with the deviceOwnerAuthenticationWithBiometrics flag, returns true only if the hardware to authenticate the user through biometrics is available and if the user has enrolled biometric factors.

When storing sensitive data for a biometric authentication within the Keychain it is recommended to use the following flags:

1) kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly: requires that a passcode is set on the device. The data is accessible only with the device unlocked and it is deleted when the user deactivates the passcode.

2) kSecAccessControlBiometryCurrentSet/kSecAccessControlBiometryAny: requires a user to authenticate with biometrics (e.g. Face ID or Touch ID) before accessing the data in the Keychain item. When using kSecAccessControlBiometryCurrentSet, whenever the user adds a fingerprint or facial representation to the device, it will automatically invalidate the entry in the Keychain. This makes sure that the keychain item can only be unlocked by users that were enrolled when the item was added to the keychain.

The usage of the other flags should be avoided when storing data relative to biometric authentication since they do not mandatory require the usage of biometric factors to retrieve the data when accessing the application.


Following it is reported an example on how to securely save data in the Keychain for biometric authentication:

var error: Unmanaged<CFError>?
guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                                          kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
                                                          SecAccessControlCreateFlags.biometryCurrentSet,
                                                          &error) else {
    // failed to create AccessControl object
    return
}
var query: [String: Any] = [:]
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrLabel as String] = "label_for_auth_token" as CFString
query[kSecAttrAccount as String] = "App Account" as CFString
query[kSecValueData as String] = "here_goes_auth_token".data(using: .utf8)! as CFData
query[kSecAttrAccessControl as String] = accessControl

let status = SecItemAdd(query as CFDictionary, nil)
if status == noErr {
    // successfully saved
} else {
    // error while saving
}

When requesting the sensitive data, the iOS platform will ask for biometric authentication returning data or nil depending if the biometric authentication was successful or not.

During the various assessments performed on mobile applications we’ve found different insecure implementation of the biometric authentication that make use of the evaluatePolicy method and are similar to the following one:

let context = LAContext()
var error: NSError?
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Authenticate with biometrrics to access the application") { success, evaluationError in
    guard success else {
        // Authentication Failed
    }
   enterApplication();
}


This kind of implementation is insecure since does not make use of the Keychain, but it assumes that the authentication has been properly validated since the success condition has been met and allows the user to use the application.

Using hooking techniques or tools such as Frida or Objection this kind of implementation could be bypassed without providing a valid biometric authentication.

It is worth considering that even implementations that make use of the Keychain could be bypassed if the proper flags are not set when storing the data in it.

Specifically the usage of the flag kSecAttrAccessibleWhenUnlockedThisDeviceOnly and kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly should be avoided since they do not require that a passcode has been previously set on the device and does not delete the data when the passcode is disabled. Furthermore if the device has no passcode, the data is always accessible since the device is considered always unlocked.

Finally the usage of the other SecAccessControlCreateFlags, except for the aforementioned kSecAccessControlBiometryCurrentSet/kSecAccessControlBiometryAny should be avoided since they do not mandatory require a biometric authentication. Indeed the device passcode could be used as well.



Conclusions

When implementing biometric authentication on mobile application it is recommended to always use solutions that relies on cryptography and secure hardware such as the Keystore for Android and the Keychain for iOS.

Event-based authentication implementation should be considered insecure since they could be easily bypassed on rooted or jailbroken devices by using hooking techniques or tools such as Frida or Objection.

Highly sensitive applications such as banking apps or financial related applications should always rely on strong implementations when using biometric authentication and they should delete the sensitive data when the biometric set is changed or completely disabled.

Finally, for sensitive applications it is also suggested to implement frameworks in order to enhance their resiliency by detecting rooted/jailbroken device or attacks that make use of hooking techniques in order to reduce the risks of being exploited.


References

Android


iOS


This article is the result of research through the official Android and iOS developer guides, the OWASP Mobile Security Testing Guide (https://owasp.org/www-project-mobile-security-testing-guide/) and the assessment activities on mobile applications performed by Minded Security’s consultants.



Authors

  • Michele Tumolo 
  • Giuseppe Porcu

Tuesday, June 30, 2020

Behave! A monitoring browser extension for pages acting as "bad boi".

Browsing: What Could Go Wrong?

There's so much literature about client side attacks, but most of the focus is usually about classical malware attacks, exploiting software vulnerabilities.

Malicious scripts happen to be executed every day by thousands of people and most of the times Malware/Virus/Malvertising try to exploit vulnerabilities or to lure the user to install software on his own machine with the intent of staying undetected as much as possible in order to do its criminal business. 
That's what AntiMalware/Virus/[...] are for.

It's the principle of minimum energy: usual malware wants comfortable, smooth, local execution. 

However, there's quite a number of alternative attacks on the client side, with minimal fingerprint that tend to drag less attention and that might go unnoticed on several environments.

Indeed there's a history of  such alternative attacks as:
  • Local Port Scan: Impact: Information Gathering which could be used to perform further client side attacks (Malware) or to have a better unique user profile (Advertising/RiskAnalysis).
  • Cross Protocol attacks: Impact: according to the protocol there might be an abuse of specific features. Such as SMTP abuse etc.
  • DNS rebinding: Impact: SOP bypass resulting in reading sensitive information of internal network servers.

which are not news at all. They are, indeed, quite old attacks that are still as reliable as difficult to completely "fix" by browser vendors because they abuse core features of the Web ecosystem.

Behave! A Monitoring Extension for pages acting as "bad boi"

With those attacks in mind, we thought that, by taking advantage of the browser API at extension layer, a browser extension might help monitoring HTML pages behavior.
That's Behave!
Available as an extension for:

It monitors and warn if a web page performs any of following actions:

  • Browser based Port Scan
  • Access to Private IPs
  • DNS Rebinding attacks to Private IPs
Here's Behave! pointing its finger to a malicious page hosted by at.tack.er host performing access to local IPs:



image


Behave! Future Plans 

There's a quite a bunch of stealth&malicious client side techniques that could be abused at several levels of security that might be monitored by Behave! in the future.

Monday, May 18, 2020

Remote Working - Web Chats: Threats and countermeasures

Introduction

With recent worldwide events, a sharply increasing number of companies are offering remote services to their customers. Even traditional businesses are implementing new features or pushing the migration of existing features to new needs of dematerialization of human-to-human relationships. 
Web chats are an example of such trends.

Web chats

Rich messages web chats are a common feature implemented by companies to overcome the need of social distancing, while maintaining a close relationship with customers.
An example of rich messages web chat would be a graphical widget loaded by web site visitors to establish a chat session with a human operator, with the objective of sharing documents in a multimedia environment: users can share PDF files (e.g. personal documents, scans), video or audio files (e.g. vocal record of a formal declaration, acceptance of conditions and clauses for contracts, identity recognition) or even unpredicted formats, to deal with the abundance of multimedia files offered by end-user environments.
To do so, preview feature has a crucial role.

Scenario

As shown below, a typical scenario is a web server exposing chat capabilities, allowing human operators in a trusted network (e.g. a LAN) to interact with remote customers.
Usually, customers interact with the chat using a common browser over an untrusted network (the Internet, their own device); chat operators interact with customers using a browser or the backoffice component of the web chat, which commonly offers rich features, such as document viewing, session management, multiple channels interaction and capabilities to interact with customers in an "enhanced" manner.

This article will describe several attack vectors from potentially malicious remote customers against targeted chat operators and the software they use to interact with customers: the objective of described workflows is attacking the trusted internal corporate network.



Rich data exchange interaction

Backoffice chat components trie to recognize messages, files and URLs submitted by chat users with the aim of previewing them or offering operators with advanced tools to manipulate data.
Different recognition approaches are usually in place: parse file extensions, MIME type of uploaded files, and actually reading the real content of the file prior to supplying it to the operator.
If the recognition procedure does not thoroughly include a secure implementation of all the mentioned approaches, chat operators and internal resources may be prone to security threats.

Threats

Web chats can accept several formats for files, sent by users (e.g. with drag & drop) or submitting URLs.

HTML payloads

The simplest and most known attack vector is abusing the HTML parser of web chats:

Customer enters <b>ciao!</b>
Operator sees ciao!

Customer enters <script>alert("XSS!")</script>
Operator sees:


Malformed PDF file upload

User supplied PDF files can be opened by chat operators in embedded viewers in the backoffice component of the web chat or downloaded on their workstation, within the trusted corporate network.
Such files can be vehicle of arbitrary code (e.g. JavaScript or other active code), which can therefore be executed on the endpoint of chat operators, exploiting known vulnerabilities in the browser or in any other software used by operators to view the file.

As an example, PDF files can contain dynamic JavaScript code, very similar to how XSS attacks work:



Thus, malformed PDFs, especially if loaded with an outdated Adobe Acrobat version, can be an attack vector for further exploits (e.g. meterpreter payloads, malwares, droppers..) against the internal network, the browser, the operating system or other components in the trusted backoffice environment.

Note: any security concern for PDF files should be extended to Office documents (Word, Excel, Powerpoint), especially if older and/or not hardened versions of Microsoft Office are in use.
For example threats may include malwares embedded in Office documents or CSV Formula Injection attacks.

Malicious URLs (Abusing preview feature)

Web chats tries to parse URLs pasted by users' messages, with the aim of previewing their content.
If the parsing procedure is executed correctly, the PDF is previewed by an embedded viewer, and it can therefore lead to scenarios described above.
On the contrary, if the parsing procedure is not correctly executed, the preview mechanism (triggered by the presence of ".PDF" string in the URL) can lead to unexpected events.

For example, if the URL ends with ".pdf" string, the web chat may attempt to dynamically load any preview module. As shown below, ".pdf" in the URL does not indicate a real PDF file, but a folder named ".pdf" on an arbitrary web server.

Content of the attacker's web site:


$ ls ./.pdf -1
minded (executable file)
minded.html (malicious HTML file)
minded.pdf (malicious PDF file)


Behaviour of the preview on chat operator's software:



Several social engineering scenarios can be constructed over this behaviour, for example convincing the chat operator (whose job is trying to efficently interact with a customer) to download other files.

Semi-automatic scenarios, on the other hand, can include the execution of arbitrary code in HTML files, abusing the preview feature. For example, it would be possible to spawn a BeEF HTML hook against the browser in use by the chat operator:



The command & control server (used by the attacker / evil customer) would look similar to the following:



Consequently, the attacker can use a large plethora of social engineering / hijacking techniques.

For example, spawning fake system messages / Java Applet load requests:



Or even spawning fake Clippy Office Assistants:



Embedded players

Web chats may also include MP3 players, which, depending on the library in use by the chat software, may be prone to vulnerabilities related to outdated software modules.



Mitigations

  • Validate any uploaded file according to a predefined list of expected file types:
- Extension
- Content Type
- Actual content of the file
  • Rescale / Resize with a 1:1 ratio any multimedia file, before allowing chat operators to open the file, in the attempt of removing any metadata
  • Properly hardening procedures should be applied to any software in use by chat operators:
- Update PDF viewer software to the latest available version
- Apply proper security options (e.g. Enhanced security and protected mode in Adobe Acrobat) to harden PDF viewer software
  • Define a list of allowed file types for the preview feature, avoiding any other format: if chat operators are expected to receive only URLs, documents and images, define a list where only PDFs and JPGs/PNGs are allowed, while any other extension is excluded from previewing components.

References

https://acrobatusers.com/assets/collections/tutorials/legacy/tech_corners/javascript_corner/tips/2006/popup_windows_part2/AlertBoxExamples.pdf
https://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/enhanced.html
https://owasp.org/www-community/attacks/CSV_Injection
https://beefproject.com/

Thursday, April 30, 2020

OWASP SAMM v2: lessons learned after 9 years of assessment


OWASP SAMM v2 is out!


OWASP SAMM (Software Assurance Maturity Model) is the OWASP framework to help organizations assess, formulate, and implement, through our self-assessment model, a strategy for software security that can be integrated into their existing Software Development Lifecycle (SDLC).

The new OpenSAMM


The original model OpenSAMM 1.0 was written by Pravir Chandra and dates back to 2009. Over the last 10 years, it has proven a widely distributed and effective model for improving secure software practices in different types of organizations. With SAMM v2, further improvements have been made to deal with some of its perceived limitations.

For those organizations using earlier versions of SAMM, it is important to take the time to understand how the framework has evolved in favor of automation and better alignment with development teams.

The new model supports maturity measurements both from coverage and quality perspectives. It added new quality criteria for all the activities. There is an updated scoring SAMM toolbox designed to help assessors and organizations with their software assurance assessments and roadmaps.

What about your development models?


The new SAMM model is development paradigm agnostic. It supports waterfall, iterative, agile, and DevOps development. The model is flexible enough to allow organizations to take a path based on their risk tolerance and the way they build and use software. The model is built upon the core business functions of software development, with security assurance practices.

What’s changed with SAMM v2?


The version 2.0 of the model now supports frequent updates through small incremental changes on specific parts of the model with regular updates to explanations, tooling, and guidance by the community.

The 3 maturity levels remain as they were. Level 1 is initial implementation; level 2, structured realization; and level 3, optimized operation.

This is the updated SAMM version 2 model:





The major changes are the following:

    - From 4 to 5 business functions and from 12 to 15 Security Practices.
    - The 4 business functions of version 1.5 now become 5 core business functions:

    - Governance
    - Design (which used to be Construction)
    - Implementation
    - A redesigned Verification function
    - Operations

    - Implementation, to represent a number of core activities in the build and deploy domains of an organization. It also includes a new security practice that deals with Defect Management or fixing process.
    - New security practices are: Secure Build, Secure Deployment, Defect Management, Architecture Analysis, Requirements-driven Testing.
    - A new concept appears with version 2, called Streams: activities are now presented in logical flows throughout each of the now 15 security practices, divided into two streams, which aligns and links the activities in the practice over the different maturity levels. Each stream has an objective that can be reached in increasing levels of maturity.

    - The model now supports maturity measurements both from a coverage and a quality perspective. There are new quality criteria for all the SAMM activities, and an updated scoring model to help SAMM assessors and organizations with their software assurance.

What we learned in the last 9 years of assessments

Minded Security did many Software Security Assessments based on SAMM v1 and v1.5.  The following diagram shows the results of  the assessments:



We collected SAMM assessment results performed until 2012 (blue line) and then from 2013 to 2015 (orange line) and then from 2016 to 2018 (gray line).

As you can see from the 2012’s results, the first answer of a Company to the software security issues is: testing, testing, testing!

What we learned during these years is that testing is NOT the solution of Software Security. Testing is just a part of your Software Security journey.

The security efforts of software developers are currently being stymied by time constraints, complexity, and deployment frequency.

The timeline for reporting and fixing critical vulnerabilities – up to one month to share, up to six months to fix – remains unacceptably long.

Today we need instant security feedback: key to achieving a fix within hours of discovery are new standards, more automation, and promptly sharing vulnerability information internally.

That’s why you need to improve all the security practices of the SAMM model in order to manage Software Security properly. A SAMM assessment permits you to have a complete vision of the problem: today the SAMM framework has become crucial to build an efficient, solid Software Security Roadmap in the Companies.





Tuesday, March 17, 2020

How to Path Traversal with Burp Community Suite


Introduction


A well-known, never out of fashion and highly impact vulnerability is the Path Traversal. This technique is also known as dot-dot-slash attack (../) or as a directory traversal, and it consists in exploiting an insufficient security validation/sanitization of user input, which is used by the application to build pathnames to retrieve files or directories from the file system that is located underneath a restricted parent directory.
By manipulating the values through special characters an attacker can cause the pathname to resolve to a location that is outside of the restricted directory.

In OWASP terms, a path traversal attack falls under the category A5 of the top 10 (2017): Broken Access Control, so as one of top 10 issues of 2017 we should give it a special attention.

In this blog post we will explore an example of web.config exfiltration via path traversal using Burp Suite Intruder Tool.

Previous posts about path traversal:
How to prevent Path Traversal in .NET
From Path Traversal to Source Code in Asp.NET MVC Applications

Testing Step-by-Step

First, get a copy of Burp Suite Community Edition, a useful testing tool that provides many automated and semi-automated features to improve security testing performances.
In particular, Burp Intruder feature can be very useful to exploit path traversal vulnerabilities.

Suppose there's a DotNet web application vulnerable to path traversal. In order to exploit the issue the attacker can try to download the whole source code of the application by following this tutorial.

Once the attacker finds a server endpoint that might be vulnerable to Path Traversal, it's possible to send it to Burp Intruder as shown in the following screenshot.



On the Intruder tab, the target has been set with the request that it will be used to manipulate in order to find the web.config file.

Make sure that the payload is correctly injected in the right attribute position, if not, perform a "Clear §" action, then select the attribute to fuzz and click on "Add §" button. 



To set the payloads that Burp Intruder will use to perform the requests, download  file traversals-8-deep-exotic-encoding.txt  from fuzzdb project  and provide it to Burp Intruder by executing the following actions:
  • go to the "Payloads" sub-tab;
  • select from dropdown list "Payload type" the value "Simple List";
  • in the panel "Payload Options" click on "Load..." button and select the fuzzing path traversal file (as shown in following screenshot).


Next step is to add a Payload Processing rule in order to match and replace the placeholder "{FILE}" with the filename we want to exfiltrate (in our example "web.config"), so click on "Add button".



In the paylod processing rule modal, add the Match for string "{FILE}" and the Replace for string "web.config", as shown in following screenshot:


In order to improve the probability of a successful attack, it is possible to add a Grep-Match value (if known), in order to easily identify a positive response.

Remove all already existing rules:



Then add a new Grep-Match rule for "<configuration>" string, that indicates web.config file has been found.




Finally, it's suggested to tune the Request Engine options basing on web server limitations (anti-throttling, firewall system, etc) in order to avoid false negative results, for example increasing retry delay.




Let's launch the attack. 

If the endpoint will result vulnerable to path traversal, the column "configuration" will be checked.