Showing posts with label iOS Security. Show all posts
Showing posts with label iOS Security. Show all posts

Wednesday, April 17, 2024

Semgrep Rules for iOS Application Security (Swift)


Swift_security

Nowadays, millions of people rely on iOS mobile applications for almost everything. As a result iOS devices manage a significant amount of data including sensitive ones, such as: credentials, health data, payment data and so on. 

For these reasons ensuring the security of iOS applications is more critical than ever when developing iOS applications. Securely handling sensitive data and minimizing vulnerabilities are essential core concepts for developers when coding iOS applications, using Swift and Objective-C languages.

Swift is an open-source object-oriented language mostly used on Apple platforms, which  allows to write software for various environments and devices such as: phones, tablets, desktops, servers, etc.

To harden the attack surface of the iOS applications it is crucial to analyze and test the code both manually and using automatic tools throughout the SDLC. 

This can be achieved by combining: 

  • SCA (Software Composition Analysis) is the process that aims to identify the versions of the open source dependencies used by the application, and then verify if there are known vulnerabilities related to them.
  • DAST (Dynamic Analysis Security Testing) is the process of testing an application while it is running in order to detect security weaknesses and vulnerabilities present on it.
  • SAST (Static Analysis Security Testing) is a testing process focused in the static analysis of the source code to find security flaws and marking their precise location.

SAST, Swift and Semgrep

SAST involves the comprehensive examination of an application's source code to identify and rectify security vulnerabilities, coding errors, and potential threats. 

This process aims to uncover weaknesses that could be exploited by malicious threat actors to compromise the integrity, confidentiality, or availability of the application and its associated data.

In particular, focusing on SAST tools for iOS applications, currently it is difficult to find an efficient automated tool able to analyze adequately Swift code-bases (especially regarding open-source SAST tools). In fact, in some cases performing source code analysis of iOS applications could be complicated and cumbersome. 

In the information security landscape various SAST tools are available (open and closed source software), in these recent years undoubtedly Semgrep (semantic grep) is the one that is gaining increasing fame.

Semgrep OSS is a fast, open-source, static analysis tool for searching code, finding bugs, and enforcing code standards at editor, commit, and CI time. It supports many different languages and package managers, and it comes with a number of other tools to help make static analysis intuitive, accessible and integrated into CI/CD pipelines. 

Semgrep OSS permit to perform intra-file analysis, and together with it also is provided a collection of pre-written rules and testing code excerpts in its public-free Registry. Additionally, any "semgrepper" user could create his custom rules for any of the supported languages and test/enhance them using the public-free Semgrep Playground.

This SAST tool could be useful during secure source code review activities, in particular are appreciable its efficiency, speed, ease of use/configuration and rule's customization. 

For instance, supposing you want detect all the occurrences of a peculiar vulnerability that has been found during manual code analysis. If this vulnerability is not recognized by the public Semgrep rules, it would be very helpful writing a custom rule to identify the other occurrences of the same vulnerable code pattern, especially when analyzing large volumes of code.

No Country for Old Rules

Due the complete absence of Semgrep rules regarding iOS applications security for Swift code (Objective-C is not yet supported), in late 2022 I decided to create and publish my first Semgrep rule-set for Swift based mobile applications: 

akabe1-semgrep-rules

with the aim to fill this gap, and of course to improve my knowledge on how Semgrep works and to speed-up source code analysis activities during my work at IMQ MindedSecurity.

With pleasure I noticed that the project has aroused interest in the security community, maybe because it was the first one for Swift.. 

Even better! The rules are also currently used by some security products that integrate code scanners to CI/CD pipelines.

For each Semgrep rule, as other tools, points for improvement can be identified during their usage. In fact, a Semgrep rule-set could necessitate periodic tuning in terms of efficiency and code coverage, then new rules could be added and existent ones could be improved. Furthermore the rules should evolve as the Semgrep syntax/features change and the target code evolve. 

For these reasons, I spent some spare time this year to add new rules and make some improvements to the existing ones for the Swift security rule-set. 

The newly released rules not only increase the coverage of iOS mobile apps security issues and improve the speed, but they also further reduce the percentage of false negatives/positives.

For the sake of completeness, it should be pointed out that currently writing Semgrep rules for Swift is not so easy. In fact, there are some obstacles to overcome during development and testing phases:

  • the Semgrep support for Swift language is still experimental, this means that some specific pattern syntax necessary to write the Swift rules are not yet completely available and functioning
  • the fact that almost all iOS mobile apps have closed source code reduces the opportunities to test extensively the Swift rules (there are few open-source Swift repos)

These problems, as can be guessed, make the development of efficient and effective Swift security rules for Semgrep a quite slow and effort-intensive process. As a result, there's always room for further improvements to my Swift rule set.

Project Details

The "akabe1-semgrep-rules" project is a collection of Semgrep rules for Swift language - there's also some rule for Java - that are based on my experiences in the security field.

The Swift rule-set cover many of the checklist of the OWASP Mobile Security Testing Guide for iOS and has been developed by studying the Apple documentation, analyzing Swift source code, and sometimes writing purposely vulnerable Swift code by myself.

For developers and testers working with Swift-based iOS applications, these Semgrep rules could be a useful resource to include into SDLC processes, in order to detect in Swift code-bases:

  • Vulnerabilities
  • Coding bad-practices
  • Security misconfiguration issues 

The rules cover a wide range of topics for iOS apps security, including:

  • Biometric Authentication issues
  • Certificate Pinning issues
  • External XML Entities (XXE) issues
  • SQL Injection issues
  • Cryptographic issues
  • Log Injection issues
  • NoSQL Injection issues
  • WebView issues
  • Insecure Storage issues
  • Keychain Settings issues
  • Critical Device Feature issues
  • Hardcoded Sensitive Data issues


Below is reported a summary table:

Security Issue Rule Name Rule Description OWASP MASTG Category
1 Biometric Authentication improper_biometric_auth Find insecure biometric authentication mechanisms MASVS-AUTH
2 Certificate Pinning afnetworking_pinning Find security misconfigurations for certificate pinnijng via AFNetworking libraries MASVS-NETWORK
3 Certificate Pinning alamofire_pinning Find security misconfigurations for certificate pinnijng via Alamofire libraries MASVS-NETWORK
4 Certificate Pinning trustkit_pinning Find security misconfigurations for certificate pinnijng via Trustkit libraries MASVS-NETWORK
5 XXE xxe Detect if the resolution of XML external entities is enabled MASVS-CODE
6 SQL Injection sqli_query Detect SQL queries built insecurely MASVS-CODE
7 Hardcoded Secrets hardcoded_secret Detect secrets hardcoded into Swift source code MASVS-STORAGE
8 Log Injection log_inj Detect if logs are written using untrusted input MASVS-CODE
9 NoSQL Injection nosql_inj Detect NoSQL queries built insecurely MASVS-CODE
10 WebView Misconfiguration improper_wkwebview Detect security misconfigurations on WKWebview MASVS-PLATFORM
11 WebView Deprecation insecure_webview Find usages of insecure/deprecated webviews (UIWebview and SFSafariViewController) MASVS-PLATFORM
12 Insecure Storage insecure_storage Find usages of cleartext storage mechanisms MASVS-STORAGE
13 Insecure Storage none_file_protection_part1 Find occurrences of some specific insufficient data protection classes MASVS-STORAGE
14 Insecure Storage none_file_protection_part2 Find occurrences of some specific insufficient data protection classes MASVS-STORAGE
15 Insecure Storage weak_file_protection_part1 Find occurrences of some specific weak data protection classes MASVS-STORAGE
16 Insecure Storage weak_file_protection_part2 Find occurrences of some specific weak data protection classes MASVS-STORAGE
17 Keychain Settings exportable_keychain Find exportable configurations of iOS Keychain MASVS-STORAGE
18 Keychain Settings weak_keychain Find weak configurations of iOS Keychain MASVS-STORAGE
19 Critical Device Features critical_device_features Find the usages of critical device features (SMS/Mail sending, phone calls) MASVS-PLATFORM
20 Broken Cryptography broken_commoncrypto Find usages of insecure cryptography MASVS-CRYPTO
21 Broken Cryptography broken_crypto_idz Find usages of insecure cryptography MASVS-CRYPTO
22 Broken Cryptography broken_cryptoswift Find usages of insecure cryptography MASVS-CRYPTO
23 Broken Cryptography broken_rncrypt Find usages of insecure cryptography MASVS-CRYPTO
24 Broken Cryptography broken_swiftcrypto_sodium Find usages of insecure cryptography MASVS-CRYPTO


Conclusions

The secure source code analysis plays a pivotal role in bolstering the security of software development, including iOS mobile applications. 

By conducting thorough static code analysis, developers/testers can identify and remediate security vulnerabilities, promote compliance with industry standards and best practices, and enhance the overall resilience of their applications against emerging threats. 

Nevertheless the manual analysis performed by security professional people remains indispensable, the introduction of SAST automated instruments with tailored rule-sets facilitates and speeds-up the secure source code reviews. 

As the mobile landscape continues to evolve, integrating secure source code analysis into the development workflow remains essential for safeguarding user data, maintaining user trust, and mitigating the risk of security breaches and cyber attacks.


Thursday, May 27, 2021

Mobile Screenshot Prevention Cheatsheet - Testing and Fixing

Mobile Screenshot Prevention Cheat Sheet - Testing and Fixing



The following article will explain how to test mobile applications against any implemented screenshot prevention mechanism and then it will try to propose mitigations to such problem according to the context.

The following article is the second part of Mobile Screenshot Prevention Cheat Sheet - Risks and Scenarios published on IMQ Minded Security blog.

TLDR; None of the proposed solutions will provide a full protection against screenshotting. Therefore all of them shall be considered as mitigations.

Auditing Screenshot Prevention

In this section we will focus on testing and preventing mobile screenshot via static (e.g. perform a secure code review or a mobile application reverse engineering task) and dynamic (e.g. test a mobile application in its execution environment) contexts.

First things first: anyone approaching mobile application security should carefully read the OWASP Mobile Security Testing Guide (MSTG)[1][2].

Static Analysis

Assuming we have the source code of a mobile application and we have to check if the app implements any mitigation against screenshot attacks, either user or system generated. 
What should we look for?

Android

Usually the common remediation is to set FLAG_SECURE to LayoutParam, hence the first step is to search for it in the codebase. 
But, if we have access to the source code of an application somehow decompiled from a packaged application, it might be possible that the FLAG_SECURE keyword could have been obfuscated or replaced with its integer value.

Therefore, the values to search for, are:
  • FLAG_SECURE (high level symbol)
  • 8192 (numeric value)
  • 0x00002000 (hexadecimal numeric value)
If any of those values are found, it must be checked whether it is used as parameter set to the WindowManager LayoutParams

It should be noted that this flag must be set in all the Android Activities involved in the application and it would be effective for both user and system generated screenshots.

iOS

Since in iOS it is not possible to prevent user generated screenshots, we have to search for any code related to the notification system which can be used to provide awareness about the taken screenshot.
It is then possible to search for the following keywords:
  • userDidTakeScreenshotNotification (Swift)
  • UIApplicationUserDidTakeScreenshotNotification (Objective-C)
If any of the following keywords is found, it would be possible to then observe a function callback being executed after a user generated screenshot has been created.

On the other hand, for system generated screenshots, it would be necessary to analyze pieces of code which are responsible to handle the transitions between foreground and background application statuses.
Since the system generated screenshots are generated just before the application has been put in the background status, in these portions of code, if any remediation has been implemented, we are expecting to find some mechanism which would hide or obfuscate sensitive parts of the UI just before the screenshot has been generated.
It would then be possible to search for the possible values:
  • applicationWillResignActive (here we should find pieces of code hiding parts of the UI, e.g. by setting the hidden property on a view)
  • applicationDidBecomeActive (here we should find pieces of code showing parts of the UI, e.g. by unsetting the hidden property on a view)

    Dynamic Analysis

    TLDR; Let's try to generate a screenshot of the application and let's check if the application UI is shown in the device task manager.

    User Generated Screenshots

    First of all, let's focus on how we can generate a screenshot of our running application. Basically it will depend on which OS and device type we are testing.

    On a variety of Android devices, it is possible to generate a screenshot by using device specific combo keys. The most common combinations are:
    • VOLUME DOWN + POWER
    • VULUME UP + POWER
    It would be also possible to generate a screenshot by using the function tile in the system tray, but it strongly depends on the OS customizations.

    If we are using the Android emulator, we can use the specific button on the emulator toolbar:


    On iOS it depends on which physical keys are available on the target device. The two possible combo keys are:
    • POWER + HOME
    • VOLUME UP + POWER
    Finally, if we are using the iOS simulator, we can use the combo key CMD + S or we can use the drop down menu entry under File -> New Screen Shot.

    In all the above cases, the positive probe is the successful generation of a screenshot containing the same views actually on the device's screen, without any kind of modification and without any kind of notification generated on the device.

    If the running application is properly secured, we will see the following notification being generated on Android:

    On the other hand, since in iOS it is not possible to prevent a user to generate a screenshot of the application, if the running app is implementing a mitigation against screenshot generation it is not actually possible to define which behavior a pentester would see. 
    Some possible mitigations are:
    • The screenshot is partially obfuscated
    • A notification warns the user about the just generated screenshot
    • The application shows a message which informs the user about the just generated screenshot
    Beware that also a transparent and invisible mechanism could be implemented on iOS in order to warn the user about the screenshot generation, so dynamic analysis could not be sufficient in order to fully understand if an app is implementing some mitigation mechanism.

    System Generated Screenshots (AKA Task Manager Screenshots)

    On both the operating systems, the test is the same and is pretty straightforward:
    • Open the target application
    • Send the application in background by pressing the HOME button
    • Open the system task manager (e.g. by tapping the dedicated button on Android or by double tapping the home button on iOS, etc)
    At this point, if an application screenshot is shown identical as it was possible to observe when the app was in foreground, it means that no prevention mechanism was implemented.
    On the other hand, if a blank screen is shown or if the image is partially obfuscated, it does mean that the app is actually implementing some sort of full or partial prevention mechanism against system generated screenshots.

    Fixing Screenshot Issues


    Which APIs are provided to prevent or mitigate the issue?


    Android

    One flag to rule them all.
    Basically Android offers the LayoutParam FLAG_SECURE [3] which can be used to prevent both user and system generated screenshots.

    Simple and straightforward.

    iOS

    On iOS the developer is not provided the ability to prevent user generated screenshots. This is due to the strict UI/UX guidelines provided by Apple which are preventing developers from interfering with the standard OS behavior.
    Two kinds of APIs are interesting from the security point of view, when talking about screenshot prevention mechanisms.

    For user generated screenshots it is possible to use the userDidTakeScreenshotNotification [4] system wide notification. In this way, it would be possible to run code just after a screenshot was generated. 
    The most common approach is to generate a notification or an alert which warns the user about the generated screenshot. This would inform the user and will raise a red flag in case of the screenshot was not explicitly and voluntarily generated.

    On the other hand, for system generated screenshots, it is possible to refer to the applicationWillResignActive [5] application's lifecycle callback. This callback is invoked just before any application is moved from the foreground to the background and enables developers to execute code just before the system generated screenshots are created.
    These operations can include:
    • Putting an overlay over the whole application window
    • Hiding/masking sensitive parts of the UI
    • Navigating to other application parts which are not showing sensitive information

    Stop talking! Show me the code!

    This section is intentionally left without any comment, since explanations have been provided in the above sections.
    Just the source code that can be used in various scenarios and situations.
    Pro tip: If some data is VERY sensitive, such as the combination of a credit card PAN, its PIN code and the CVV2 code, don't put it in your views. If some data is not displayed on the screen, it can't be screenshotted!

    But since in the real world such approach is very often not applicable, let's dig into some mitigation implementations.

    Android

    Protects from:
    • User generated screenshots: ✔️
    • System Generated screenshots: ✔️

    Kotlin

    import android.os.Bundle
    import android.support.v7.app.AppCompatActivity
    import android.view.WindowManager

    class MainActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.setFlags(
          WindowManager.LayoutParams.FLAG_SECURE,
          WindowManager.LayoutParams.FLAG_SECURE
        )
      }
    }


    Java


    import android.os.Bundle;
    import android.view.WindowManager;

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_SECURE,
                WindowManager.LayoutParams.FLAG_SECURE
            );
      }
    }


    References: [6]

    iOS

    Protects from:
    • User generated screenshots: ðŸ¤· (partial)
    • System Generated screenshots: ❌

    Swift

    NotificationCenter.default.addObserver(
        forName: UIApplication.userDidTakeScreenshotNotification,
        object: nil,
        queue: .main) { notification in
            //Notify the user, log the action, etc...
    }

    Objective-C

    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
                                                      object:nil
                                                       queue:mainQueue
                                                  usingBlock:^(NSNotification *note) {
                                                     //Notify the user, log the action, etc...
                                                  }];

    References: [6] [7]


    Protects from:
    • User generated screenshots: ❌
    • System Generated screenshots: ✔️

    - (void)applicationWillResignActive:(UIApplication *)application {
        
        // hide main window
        self.window.hidden = YES;
    }

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        
        // show window back
        self.window.hidden = NO;
    }

    References: [8]

    React Native

    Protects from:
    • Android User generated screenshots: ✔️
    • Android System Generated screenshots: ✔️
    • iOS User generated screenshots: ðŸ¤· (partial)
    • iOS System Generated screenshots: ❌

    Android

    import android.os.Bundle;
    import com.facebook.react.ReactActivity;
    import android.view.WindowManager;

    public class MainActivity extends ReactActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_SECURE,
                WindowManager.LayoutParams.FLAG_SECURE
            );
      }
    }


    iOS

    import React from 'react'
    import { AppState, Platform, View } from 'react-native'

    const SecurityScreen = () => <View />

    const showSecurityScreenFromAppState = appState =>
      ['background', 'inactive'].includes(appState)

    const withSecurityScreenIOS = Wrapped => {
      return class WithSecurityScreen extends React.Component {
        state = {
          showSecurityScreen: showSecurityScreenFromAppState(AppState.currentState)
        }

        componentDidMount () {
          AppState.addEventListener('change', this.onChangeAppState)
        }
      
        componentWillUnmount () {
          AppState.removeEventListener('change', this.onChangeAppState)
        }
      
        onChangeAppState = nextAppState => {
          const showSecurityScreen = showSecurityScreenFromAppState(nextAppState)

          this.setState({ showSecurityScreen })
        }  

        render() {
          return this.state.showSecurityScreen
            ? <SecurityScreen />
            : <Wrapped {...this.props} />
        }
      }
    }

    const withSecurityScreenAndroid = Wrapped => Wrapped

    export const withSecurityScreen = Platform.OS === 'ios'
      ? withSecurityScreenIOS
      : withSecurityScreenAndroid


    Then, in your App component:

    import { withSecurityScreen } from './withSecurityScreen'
    ...
    export default withSecurityScreen(App);


    Pre bundled libraries are also available on NPM [10].

    References: [9] [10]

    Cordova / Ionic

    There are many Cordova plugins which can help on achieving the goal. 
    A good place to start is the cordova-plugin-prevent-screenshot-coffice open source repository.

    Protects from:
    • Android User generated screenshots: ✔️
    • Android System Generated screenshots: ✔️
    • iOS User generated screenshots: ðŸ¤· (partial)
    • iOS System Generated screenshots: ❌
    References: [11]

    Commercial Solutions

    Several commercial solutions are available on the market, however since there was no easy way to test any of them, this blog post will not promote or endorse any commercial tool.

    Conclusions - Wrapping it up

    TLDR; None of the proposed solutions will provide a full protection against screenshotting, therefore all of them should be considered as mitigations.

    Since all the OSs handle the application status transitions in a different way, and different versions of  OSs behave in a different way, it will always be possible to generate some sort of bypass of any implemented mitigation mechanism.
    Moreover, let's say that if an application is running on an untrusted - jailbroken or rooted - device  environment it is easy for an attacker to hook and bypass any kind of protection with some effort.

    The chosen mitigation should then be biased on which data the application is showing on the screen and how much sensitive is this data.
    Examples of such mitigation bypass are available in literature, such as [12].

    References


    Thursday, October 15, 2020

    Mobile Screenshot prevention Cheat Sheet - Risks and Scenarios

    Mobile Screenshot Prevention Cheat Sheet - Risks and Scenarios

    The following article will try to analyze and explain risks and attack scenarios affecting mobile applications without any implemented prevention mechanism against screenshotting.

    Briefly, what is the problem?

    Extremely summarizing, mobile applications need to implement screenshot prevention mechanisms in order to avoid an attacker to steal sensitive data, such as credentials or private information, that are shown on the screen during the application execution.

    The attacker could act by directly accessing the victim’s device, generating a screenshot using the device specific combo keys and then he would be able to send the generated screenshot to himself over the network. This kind of attack does not need any specific privilege or compromised device capability in order to get exploited. Just physical access to the device.

    On the other hand, the attacker could act by using a malware delivered on the victim’s device in some successful way, such as an untrusted application that may be downloaded from an unofficial store or that can be sent directly to the victim. As soon as the victim’s device gets infected, the attacker is now able to access private data and, based on the privileges acquirable on the infected device, he would be able to generate screenshots and/or access system generated screenshots which are stored on the device and may contain useful information to carry on further attacks.

    Attack Scenarios

    Basically the following three attack scenarios can be used by an attacker in order to successfully exploit the vulnerability, based on which access level is achievable on the targeted device:

    - The attacker has physical access to the targeted device: let’s assume the victim left his device unlocked at his desktop with a running application which is showing sensitive information. In this scenario it would be possible for an attacker to generate a screenshot using the device specific combo keys sending it to its own device through the network.  
     
    - The attacker has planted a background running malware on the targeted device: let’s assume that the attacker has delivered a malicious application on the victim’s device by uploading a compromised application on the store or by getting the victim to download an application from an untrusted source and the target device has a compromised status that can allow the malware to have privileged access to system calls. In this scenario the attacker would be able to silently generate device screenshots that can be then sent to the attacker himself through the network, exfiltrating sensitive data. 
     
    - The attacker has planted a foreground running malware on the targeted device: let’s assume that the attacker has delivered a malicious application on the victim’s device by uploading a compromised application on the store or by getting the victim to download an application from an untrusted source and the target device has modified status that can allow the attacker to read files outside of the application sandbox. In this scenario the attacker would be able to access system generated screenshots that may contain sensitive information and can then exfiltrate these files through the network.

     

    Risks

    The main risk related to this kind of vulnerability is sensitive information stealing.
    Any information shown on the device display can be stolen if not explicitly protected.

    So if an application is displaying private information in any of its views, it must be protected.

    An attacker can use automated OCR (Optical Character Recognition) analyzers in order to automatically process the gathered screenshots and extract any information contained therein.

    Any extracted information can then be then exfiltrated to an attacker controlled target in several possible ways, which would not be covered by this article.


    The following list is just an example of which kind of data can be stolen:

    • - Passwords
    • - PII (Personal Identifiable Information)
    • - PHI (Personal Healthcare Information)
    • - Private data such as appointments, notes, etc.
    • - Contacts
    • - Email and message contents
    • - [...]

    Real world: a concrete attack

    As already stated, there are two kinds of approaches an attacker can use, based on how his device is  accessed. Both of them will be explained in the following paragraphs.

    In both scenarios, we will assume that the Bill, the victim, is using the SuperSecureMail application. Bill resets his password, and the SuperSecureMail application generates a set of temporary credentials, showing them on the screen so that Bill will be able to copy them and access back to his mail account.

    Scenario 1: The attacker has physical access to victim’s device

    Bill is in his office, and he has just generated temporary credentials in his SuperSecureMail application. Now, since the application has generated a complex and strong password, Bill wants to write them on a piece of paper in order to later perform a login to his mailbox, but unfortunately he ran out of paper, so he decides to go to the office next door in order to borrow some. Doing this, Bill leaves his mobile device unlocked on his desk.

    At this point the attacker can pick Bill’s device, and he can see the credentials on the screen. He has a little time before Bill’s return, so he decides to pick a screenshot of what is on the screen using the key combination that is specific to that device and then he sends himself the generated screenshot over a Bluetooth connection.

    Since the application was not implementing any screenshotting countermeasure, the attacker now has a screenshot containing Bill’s credentials on its device and he can use the obtained information to access Bill’s mailbox and/or perform further attacks.

    Scenario 2: The attacker has access to victim’s device through a malware

    This scenario is a bit more complex than the previous one since the attacker needs to plant a malware to Bill’s device before starting the attack, moreover Bill has a device which is running a mobile operating system which implements a permissive access control policy and allows processes to perform privileged operations (e.g. the device is rooted or jailbroken).

    There are many ways an attacker could use in order to trick Bill to install an attacker controlled malware. In this case the attacker knows that Bill loves to play with mobile games which are full of cute kittens.
    Using this information, the attacker creates a real mobile game with the desired look but he also inserts malicious pieces of code into the application. These pieces of code will run in a specific mode in order to retrieve system generated screenshots of any mobile application installed on Bill’s device. 

    After generating this mobile game, the attacker sends an email to Bill saying “Hey Bill, attached there is a mobile game that we think you would love! It is a preview and we care about your opinion, so it is free at this time but it is only for you!”.

    Bill loves cute kittens. 

    Bill installs the game and gets infected unknowingly by the attacker’s malware.

    At this point, as in the previous scenario Bill has just generated temporary credentials in his SuperSecureMail application. Now, since the application has generated a complex and strong password Bill copies this password on the Notes application of his device.

    Now, when Bill switches between the SuperSecureMail application and the Notes application, while bringing the SuperSecureMail application to the background the mobile operating system generates a screenshot of what the application is displaying in that moment. 
    The screenshot is a standard image that will be shown in the device’s task manager and that will be stored in a specific path on the device’s file system that varies based on the operating system version.

    Finally, the malware can scan the file system searching for operating system generated screenshots. When it finds them, it would be possible to exfiltrate these images to an attacker controlled domain where the data can be processed and the contained sensitive information can be extracted.

    It must be noted that the aforementioned scenarios are only two of many kind of attacks that may take an attacker to exploit this kind of vulnerability. However they are two really common scenarios that can happen in the real world.

    How to do this? Let's see the code!

    The following sample of code[1] is showing how is it possible to generate a screenshot from an Android background service, using superuser’s privileges:

    Process sh = Runtime.getRuntime().exec("su", null,null); 
    OutputStream os = sh.getOutputStream(); 
    os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII")); 
    os.flush(); 
    os.close(); 
    sh.waitFor();

    Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ File.separator +"img.png");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes); 
    File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg"); 
    f.createNewFile(); 
    FileOutputStream fo = new FileOutputStream(f); fo.write(bytes.toByteArray());
    FileOutput fo.close();

    In a similar way the following example of iOS code [2] can be used in a Mobile Substrate module, running in a jailbroken device, to generate a screenshot of any application:

    UIKIT_EXTERN CGImageRef UIGetScreenImage();
    CGImageRef ref = UIGetScreenImage(); 
    UIImage* img = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);


    The following library developed by Google can be used to generate screenshots from an Android background service without having access to superuser’s privileges:
    • https://code.google.com/archive/p/android-screenshot-library/
    In a similar way, if the attacker is targeting Android versions 21+, the following native framework can be used in order to achieve the same result, getting a screenshot generated on a standard device:
    • https://developer.android.com/reference/android/media/projection/MediaProjection

    Example - 1: accessing system generated screenshots

    In this paragraph is shown how an attacker can access system generated screenshots for the Safari application.
    For this example, the Safari application has been opened and then it has been put on the background. This action resulted in the following image being shown in the iOS task manager:



    System generated screenshots are located at the following location on iOS 12:
    /var/mobile/Containers/Data/Application/{APPLICATION_BUNDLE_ID}/Library/Caches/Snapshots/{APPLICATION_PACKAGE_NAME}

    For example, in this case, Safari system generated screenshots are located at the following location:
    /var/mobile/Containers/Data/Application/B9008870-3F72-4B0E-ADEC-D867FBA060A2/Library/Caches/Snapshots/com.apple.mobilesafari

    The following screenshot is showing the content of the above folder:



    Finally, opening the file named E341AE9B-B12A-4E8B-AB08-1DA156CDF9E2@2x.ktx we can see that the content is the screenshot that was shown in the iOS task manager shown before:

    Example - 2: accessing user generated screenshots

    In a similar way, user generated screenshots can be accessed from any application which the permission to access the device photo library was granted.
    In this example, we are explicitly generating a screenshot of the Safari application.

    User generated screenshots can be found at the following location in iOS12:
    /var/mobile/Media/DCIM/100APPLE/

    Accessing this location, and opening the file named IMG_0039.PNG we can finally access the previously generated screenshot:


    Conclusions and next steps

    This article analyzed which risks and scenarios are afflicting mobile applications which are not explicitly implementing mobile screenshotting prevention, trying to clearly explain what an attacker can do in order to gather personal data and sensitive information.

    What can a user do in order to prevent sensitive data from being stolen leveraging this kind of attack? 

    It must be noted that the user by itself can not totally prevent these types of attacks, but he can mitigate them by using the following best practices:
    • Do not let people to have unauthorized physical access to the device
    • Do not install any application coming from a untrusted sources such as email attachments, unofficial application stores or any other source available on the web.
    • Do not modify the device and operating system statuses by using procedures such as rooting, jailbreaking or installing modified versions of the mobile operating system.

    The next question would be: how can a mobile application be checked if it implements Mobile Screenshot countermeasures? How can this issue be fixed?

    These topics will be covered in one of the next blog posts with the title: “Mobile Screenshot Prevention Cheat Sheet - Testing and Fixing”.

    Wednesday, May 2, 2018

    Antitamper Mobile - Minded Security's Magik Quadrant for Mobile Code Protection (2018 Edition)


    Minded Security's Magik Quadrant for Mobile Code Protection shows our evaluation of the top vendors in this market, based on our research and experience, updated to 2018.

    Magik Quadrant

     

    Why care about Code Protection?

    The main reason lies in the fact that Mobile Applications runs within an environment that is not under the control of the organization producing the code.

    Lack of Code Protection could have the following consequences:
    • Malicious users or competitors could decompile the application and gain knowledge about proprietary algorithms or intellectual property
    • Using this information, it could be possible to modify the code, repackage it and redistribute it to create a "trojanized" clone of the App
    • Revenue loss due to piracy
    • Reputational damage

    Since 2016, the OWASP Mobile Top 10 has included two new categories related to that, that is M8-Code Tampering and M9-Reverse Engineering.

    Code Tampering

    Code Tampering is the process of changing a mobile app (either the compiled app or the running process) or its environment to affect its behavior.
    The most common code tampering techniques are:
    • Code Injection
    • Binary Patching
    • Local Resource Modification
    • Method hooking
    • Method Swizzling
    • Dynamic Memory Modification  
    Tools and frameworks like Frida, Substrate, Cycript, Xposed and FLEX could give an attacker direct access to process memory and important structures such as live objects instantiated by the app. 
    They come with many utility functions that are useful for resolving loaded libraries, hooking methods and native functions, and more.
    This can provide the attacker a direct method of subverting the intended use of the software for personal or monetary gain.

    Code Tampering could be prevented by detecting at runtime that code has been added or changed since compile time.

    Reverse Engineering

    Reverse engineering a mobile app is the process of analyzing the compiled app to extract information about its source code. 
    An app is said to be susceptible to reverse engineering if an attacker can derive a reasonably accurate reconstruction of the source code from the binary.
    Reverse Engineering could be prevented by using an obfuscation tool that implements controls like:
    • String Encryption
    • Name obfuscation
    • Control flow obfuscation
    • Arithmetic obfuscation


    Also to that, it is important to implement anti-debugging techniques and verify if the application is running on a rooted/jailbroken device.


    Some commercial tools provides code protection without requiring developers to implement their own custom controls.
    The remaining of this blog post is going into details about the tools available in the market in 2018.

    Interpreting the Magik Quadrant

    The Magik Quadrant study performed on Code Protection solutions takes into account multiple criteria based on Ability to Execute and Completeness of Vision.

    Ability to Execute
    Vendors must deliver strong functionality in the following areas of capability:
    • Techniques implemented
    • After Sale Support

    Completeness of Vision
    Completeness of vision in the Code Protection market considers a vendor’s vision and plans for addressing buyer needs in the future:
    • Cross-platform support
    • Innovation
    • Sale Strategy

    Before proceeding, it is worth noting that focusing on the leaders' quadrant isn't always the best choice. There are good reasons to consider market challengers. Moreover a niche player may support a specific needs better than a market leader.


    Leaders
    Leaders offer products and services that best cover current scenarios and are well positioned for the future. They provide solutions that are cross-platform, so with one vendor is possible to protect many platforms. Their complex solutions provide protection (through obfuscation, encryption, call hiding etc.), detection and reaction (in case an attack is detected).

    Visionaries
    In general, in any Magik Quadrant the Visionaries are the innovators. They understand well where the market is going and therefore they can provide innovative techniques to protect the applications in a cross-platform environment.

    Niche Players
    Niche Players, in our research, are vendors that do not offer, at the moment, a cross-platform solution but they are focused on a small segment. Since they are offering platform-specific solutions, in some case they are able to provide innovative and specific solutions for that specific target.


    Vendor Strengths and Cautions

    Arxan

    This analysis pertains to Arxan's Application Protection.

    Arxan is one of the most trusted names in application security. They provide protection against a widest range of static and dynamic attacks. The protection, provided by Application Protection, is implemented on different layers giving the chance to select the desired level of security.

    Strengths:
    • Cross-platform: Android, iOS (Objective-C and Swift applications)
    • No changes to the source code 
    • Protection from reverse engineering and disassembly through obfuscation
    • Sophisticated Anti Code Tampering techniques
    • Threat Analytics feature
    • Latest OS versions supported

    Cautions:
    • Price could be higher than expected
    • Strong binary obfuscation may interfere with the application functionalities

    Company website: www.arxan.com


    Inside Secure

    This analysis pertains to Inside Secure Code Protection and WhiteBox.
    Inside Secure is one of the leaders in the application security market. They provide a cross-platform solution based on different "modules".

    Strengths:
    • Cross-platform: Android, iOS (Objective-C and Swift applications)
    • Strong Code and Flow obfuscation
    • Anti-tampering techniques
    • Strong cryptographic key protection

    Cautions:
    • Price could be higher than expected
    • Strong binary obfuscation may interfere with the application functionalities

    Company website: https://www.insidesecure.com/


    Intertrust

    This analysis pertains to Intertrust whiteCryption.
    Intertrust is relatively new on this market but offers an innovative product that is designed to protect applications at all levels.

    Strengths:
    • Pioneers in Whitebox Crypto 
    • Cross-platform: Android, iOS (Objective-C and Swift applications)
    • Tamper Resistance
    • Self-defending code
    • Code obfuscation
    • Anti-debugging techniques
    • Cross-checking of shared libraries 

    Cautions:
    • Price could be higher than expected

    GuardSquare

    This analysis pertains to GuardSquare DexGuard and iXGuard.
    GuardSquare is very famous since they develop and support ProGuard, that is the successful open source obfuscator for the Java language used for Android application. DexGuard is derived from that, while offering more advanced and sophisticated protections.
    They have a great experience in Java and Android platform and recently they started offering also iOS support through the iXGuard software.

    Strengths:
    • Solution is solid and one of the most used thanks also to the Proguard integration in Android Studio
    • Cross-platform: Android (Cordova and PhoneGap supported), iOS (Objective-C and Swift applications)
    • Large adoption among our customers
    • Strong code optimization and obfuscation 
    • Anti-tamper detection available for the Android platform

    Cautions:
    • At this time iXGuard is offering only reverse engineering and not Anti-tampering protections for the iOS platform
    • As demo policy seems to be changed during 2017, it's harder to obtain evaluation versions; this could be a factor to consider if you have a time-constraint project
    • Price also has increased
    • Solution is one of the most used so it may be easier to find deobfuscation tools/information comparing to other solutions in the market

    Company website: https://www.guardsquare.com


    Licel

    This analysis pertains to Licel's DexProtector.
    Licel is a new competitor in code protection. Its product, DexProtector, is designed for comprehensive protection of Android applications mainly against reverse engineering, clone protection and tampering.

    Strengths:
    • Affordable for our clients
    • Strong code obfuscation
    • Clone protection
    • SSL Pinning support
    • Root and Debug Detection

    Cautions:
    • Available only for the Android platform
    • Some feature like Hooks Detection are additional features of the Enterprise version and priced separately

    Company website: www.licelus.com


    Bangcle - SecNeo

    This analysis pertains to Bangcle AppShield, AppSCO and WhiteCrypto.

    Strengths:
    • AppShield offers protections against debuggers, tampering, decompilation and malware insertion for Android applications
    • AppSCO offers reverse engineering protections (Android and iOS platform)
    • WhiteCrypto offers strong key protections (Android and iOS platform)

    Cautions:
    • Anti Code tampering techniques are only offered for the Android platform 

    Company website: http://www.bangcle.co.kr - https://www.secneo.com


    Zelix

    This analysis pertains to Zelix KlassMaster.
    Zelix has a long story and experience in code obfuscation. Since its release in 1997, the Zelix KlassMaster Java code obfuscator has been continually developed to keep it at the forefront of obfuscation technology.
    This solution provides a Java code obfuscator but it does not implement other protections such as those against code tampering attempts.

    Strengths:
    • Strong code and flow obfuscation
    • Strong Call Hiding
    • Affordable for our clients

    Cautions:
    • Available only for Java (Android)
    • Only code protection/obfuscation

    Company website: www.zelix.com


    Promon

    This analysis pertains to Promon SHIELD.
    Promon is a Norwegian firm specializing in app hardening focusing largely on Runtime Application Self-Protection (RASP).

    Strengths:
    • Cross-platform: Android, iOS (Objective-C and Swift applications)
    • Rooting and Jailbreak detection
    • Repackaging Detection
    • Protections against Runtime App Tampering
    • Debugger Detection
    • SSL Pinning
    • Hook Detection

      Cautions:
      • New player in 2018 Magik Quadrant
      • "RASP" acronym usually applies to solutions that protect applications from vulnerabilities at runtime, it could not fit 100% this solution

      Company website: https://promon.co


      Important note: it is worth noting that all these security controls do not give a guarantee that mobile applications are going to be 100% secure, but they can provide additional protection and make very hard for an attacker to carry on reverse engineering, tampering and runtime attacks.


      Wednesday, April 29, 2015

      Antitamper Mobile - Minded Security's Magik Quadrant for Mobile Code Protection


      Minded Security's Magik Quadrant for Mobile Code Protection shows you our evaluation of the top vendors in this market, based on our research and experience.

      Magik Quadrant





      Why care about Code Protection?

      There are a lot of reasons to care about Code Protection when dealing with Mobile Applications.
      Every year a lot of money is lost due to piracy, intellectual property theft, cracked copyright mechanisms, tampered software, malware, and so on.
      Mobile Apps are obviously installed client-side, therefore they are under the user's control.
      For example, malicious users or competitors could decompile the application and analyse the result.
      This could reveal valuable data as proprietary algorithms or intellectual property or allow the attackers to use that information to modify the code, repackage and redistribute it to create a "trojanized" clone of the App in a rapid fashion.
      Moreover, if the App needs to run on untrusted devices, any malware could interact with the App at runtime level to steal data (credentials, credit card number etc.) or bypass security logic (local authentication, geo-restrictions, custom cryptography etc.).
      As you can see a mobile App could be attacked at various layers and with very different goals in mind, creating a very complex problem for those who want to protect their products.
      The following diagram shows some of the main attack types.



      Why Apps reverse-engineering and tampering are easy?

      Many developers do not know how easy mobile application reverse-engineering and tampering are. 
      Since mobile Apps reside on user's devices and include valuable data inside  -  metadata, resources and even the code itself -, attackers could gather important information just by using publicly available tools.
      In fact, according to the OWASP Top 10 Mobile Risks 2014,
      “...it is extremely common for apps to be deployed without binary protection. The prevalence has been studied by a large number of security vendors, analysts and researchers.”

      Without protections, it is quite easy to decompile an App to analyse its code (particularly on the Android platform) or to interact with it at runtime level on rooted/jailbroken devices.

      How to make it harder?

      To make the life harder to the attackers and help protecting valuable data, developers should:
      • Harden DRM systems and licensing modules
      • Reduce piracy
      • Protect intellectual property and personal data
      • Secure proprietary algorithms against analysis and reverse engineering
      • Harden firmware and OS
      • Protect cryptographic keys
      • Protect the client side of encrypted communication
      • Prevent malware intrusion
      Therefore they have to deploy mobile applications with some kind of protection. To do this they could implement the following techniques:
      • Code and Flow Obfuscation
      • String and Class Encryption
      • Debug code stripping
      • Method Call Hiding (Reflection)
      • Resource Encryption
      • Debug Detection
      • Root/Jailbreak Detection
      • Runtime Injection Detection (Swizzle/Hook Detection)
      • Tamper Detection
      • Certificate Pinning
      • Watermarking
      There are many technical resources on Internet that describe at some level of detail how to implement one or more of the preceding techniques.
      Moreover, there is some commercial tool which provides binary protection without requiring developers to implement their own custom controls.
      Before going into detail about these tools it is worth noting that all these security controls do not give a guarantee that mobile applications are going to be 100% secure, but they can provide additional protection and make very hard to carry on reverse engineering, tampering and runtime attacks.

      Interpreting the Magik Quadrant

      The Magik Quadrant study performed on Code Protection solutions takes into account multiple criteria based on:
      • Ability to Execute
      • Completeness of Vision

      Ability to Execute

      Vendors must deliver strong functionality in the following areas of capability:
      • Techniques implemented 
      • After Sale Support

      Completeness of Vision

      Completeness of vision in the Code Protection market considers a vendor’s vision and plans for addressing buyer needs in the future.
      • Cross-platform support
      • Innovation
      • Sale Strategy
      Before proceeding it is worth noting that focusing on the leaders' quadrant isn't always the best choice. There are good reasons to consider market challengers. Moreover a niche player may support a specific needs better than a market leader.

      Leaders

      Leaders offer products and services that best cover current scenarios and are well positioned for tomorrow. They provide solutions that are cross-platform, and therefore with one vendor it is possible to protect many platforms.
      Their complex solutions provide protection (through obfuscation, encryption, call hiding etc.), detection and reaction (in case an attack is detected).

      Visionaries

      In general, in any Magic Quadrant the Visionaries are the innovators. They understand well where the market is going and therefore they can provide innovative techniques to protect Apps in a cross-platform environment.

      Niche Players

      Niche Players, in our research, are vendors that do not offer, at the moment, a cross-platform solution but they are focused on a small segment.
      Since they are offering platform-specific solutions, in some case they are able to provide innovative and specific solutions for that particular target.

      Free and Open Source Solutions

      The preceding analysis was done on commercial tools available on market.
      In addition to this, we have also analyzed a free and open source solutions available for iOS: iMAS.
      This solution has the main disadvantage that, since it is free and open source, it does not guarantee support. Nevertheless, we want to spend some words about it since it has some interesting features.

      Vendor Strengths and Cautions

      Arxan

      This analysis pertains to Arxan's GuardIT.
      Arxan is one of the most trusted names in application security. They provide protection against a widest range of static and dynamic attacks. The protection, provided by GuardIT, is implemented on different layers giving  the chance to select the desired level of security.

      Strengths
      • Cross-platform (Android, iOS, Windos Phone)
      • Strong code protection
      • Strong detection
      • Capability to repair after damage

      Cautions
      • Price could be higher than expected

      Company website: www.arxan.com

      Metaforic

      This analysis pertains to Metaforic Core, Authenticator, Concealer and WhiteBox.
      Metaforic is one of the leaders in the application security market. They provide a cross-platform solution based on different "modules" (Core, Authenticator, Concealer and WhiteBox).

      Strengths
      • Cross-platform (Android, iOS)
      • Strong Code and Flow obfuscation
      • Strong cryptographic key protection

      Cautions
      • Price could be higher than expected

      Company website: www.metaforic.com

      WhiteCryption

      This analysis pertains to whiteCryption's Cryptanium.
      WhiteCryption provides code protection solutions since 2009, so they are relatively new on this market compared to Arxan or Metaforic. However they offer an innovative product that is designed to protect applications at all levels.

      Strengths
      • Cross-platform (Android, iOS)
      • Strong Code and Flow Obfuscation
      • Strong anti-tampering protection
      • Anti-debug and anti-piracy features

      Cautions
      • White-box cryptography techniques are still adopted very little

      Company website: www.whitecryption.com

      PreEmptive

      This analysis pertains to DashO and .NET Obfuscator.
      The first version of DashO was released in 1998 and .NET Obfuscator was initially released few years later. Therefore PreEmptive has a long experience in Code protection.


      Strengths
      • Cross-platform (Android and Windows Phone)
      • Strong code and flow obfuscation
      • Watermarking
      • Tamper prevention and reaction

      Cautions
      • No iOS support

      Company website: www.preemptive.com

      GuardSquare - Saikoa

      This analysis pertains to DexGuard.
      GuardSquare is very famous since they develop and support ProGuard, that is the successful open source obfuscator for the Java language. DexGuard is derived from it.
      They have a great experience in Java and Android platform.

      Strengths
      • Large adoption among our customers
      • Strong code optimization and obfuscation 
      • Anti-tamper detection

      Cautions
      • Available only for Android

      Company website: www.saikoa.com

      Licel

      This analysis pertains to Licel's DexProtector.
      Licel is a new competitor in code protection. Its product, DexProtector, is designed for comprehensive protection of Android-applications against reverse engineering and tampering.

      Strengths
      • Affordable for our clients
      • Strong code obfuscation
      • Anti-tamper detection

      Cautions
      • Available only for Android

      Company website: www.licelus.com

      Bangcle - SecNeo

      This analysis pertains to AppShield service. Bangcle provides a service that permits to developers to upload its APK on Bangcle's server and they provide fully automated App shield services. The whole process takes about one hour or less to complete.

      Strengths
      • Very simple use
      • Anti-debug and Anti-tamper features
      • App Data Encryption

      Cautions
      • Available only for Android

      Company website: www.secneo.com

      Smardec

      This analysis pertains to Smardec's Allatori.
      Smardec's main goal is to offer you high quality services and products at a reasonable price. Allatori first version was released in 2006 and it has reached these goals.

      Strengths
      • Strong code and flow obfuscation
      • Watermarking
      • StackTrace restoring

      Cautions
      • Available only for Android
      • Only code protection/obfuscation   

      Company website: www.smardec.com

      Zelix

      This analysis pertains to Zelix KlassMaster.
      Zelix has a long story and experience in code obfuscation. Since its release in 1997, the Zelix KlassMaster Java code obfuscator has been continually developed to keep it at the forefront of obfuscation technology.
      This solution provides a Java code obfuscator but it does not implement other protections such as those against tampering tries.

      Strengths
      • Strong code and flow obfuscation
      • Strong Call Hiding
      • Affordable for our clients

      Cautions
      • Available only for Java (Android)
      • Only code protection/obfuscation

      Company website: www.zelix.com

      iMAS

      This analysis pertains to iMAS.
      This solution is free and open source, available on GitHub, and it provides modularity as the main feature. In particular the iMAS project is composed of many components that developers could include inside their project and every module provides a different feature. So it is up to the developers selecting the desired components and include them in the project.

      Strengths
      • Free
      • Anti-tampering protections
      • Code encryption

      Cautions
      • Available only for iOS
      • No after sale support

      Company website: project-imas.github.io