Showing posts with label semgrep. Show all posts
Showing posts with label semgrep. 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.


Monday, October 23, 2023

Semgrep Rules for Android Application Security

Introduction

The number of Android applications has been growing rapidly in recent years. In 2022, there were over 3.55 million Android apps available in the Google Play Store, and this number is expected to continue to grow in the years to come. The expansion of the Android app market is being driven by a number of factors, including the increasing popularity of smartphones, the growing demand for mobile apps, and the ease of developing and publishing Android apps. At the same time, the number of Android app
downloads is also growing rapidly. In 2022, there were over 255 billion Android app downloads worldwide.

For this reason, introducing automatic security controls during Mobile Application Penetration Testing (MAPT) activity and the CI phase is necessary to ensure the security of Android apps by scanning for vulnerabilities before merging into the main repository.


Decompiling Android Packages

The compilation of Android applications is a multi-step process that involves different bytecodes, compilers, and execution engines. Generally speaking, a common compilation flow is divided into three phases:

  1. Precompilation: The Java source code(".java") is converted into Java bytecode(".class").
  2. Postcompilation: The Java bytecode is converted into Dalvik bytecode(".dex").
  3. Release: The ".dex" and resource files are packed, signed and compressed into the Android App Package (APK)

Finally, the Dalvik bytecode is executed by the Android runtime (ART) environment.

Generally, the target of a Mobile Application Penetration Testing (MAPT) activity is in the form of an APK file. The decompilation of the both aforementioned bytecodes is possible and can be performed through the use of tools such as Jadx.

jadx -d ./out-dir target.apk


OWASP MAS

The OWASP MAS project is a valuable resource for mobile security professionals, providing a comprehensive set of resources to enhance the security of mobile apps. The project includes several key components:
  • OWASP MASVS: This resource outlines requirements for software architects and developers who aim to create secure mobile applications. It establishes an industry standard that can be used as a benchmark in mobile app security assessments. Additionally, it clarifies the role of software protection mechanisms in mobile security and offers requirements to verify their effectiveness.
  • OWASP MASTG: This comprehensive manual covers the processes, techniques, and tools used during mobile application security analysis. It also includes an exhaustive set of test cases for verifying the requirements outlined in the OWASP Mobile Application Security Verification Standard (MASVS). This serves as a foundational basis for conducting thorough and consistent security tests.
  • OWASP MAS Checklist: This checklist aligns with the tests described in the MASTG and provides an output template for mobile security testing.
OWASP MAS
https://mas.owasp.org/


Semgrep

Semgrep is a Static Application Security Testing (SAST) tool that performs intra-file analysis, allowing you to define code patterns for detecting misconfigurations or security issues by analyzing one file at a time in isolation. Some advantages of using Semgrep include:

  • It does not require that the source code is uploaded to an external cloud.
  • It does not require that the target source code is buildable and have all dependencies. It can work only with a single source file.
  • It is exceptionally fast.
  • It allows you to write your custom patterns very easily.
Once Semgrep is integrated into your CI pipeline, it automatically scans your code for potential vulnerabilities every time you commit changes. This helps identify and address vulnerabilities early in the development process, improving your software's security.

Key Insights on Semgrep

First of all, install Semgrep with the following command:
python3 -m pip install semgrep
Semgrep accepts two fundamental input:
  • Rules collection: A collection is composed by ".yaml" files, alternatively referred to as "rules". A rule includes a series of patterns designed to identify or exclude specific elements within the target source code.
  • Target source code: This denotes the source code subject to analysis. It may also encompass partial code or code with certain dependencies omitted.
The four main elements you can find inside a Semgrep rule yaml file are:
...Match a sequence of zero or more items such as arguments, statements, parameters, fields, characters.
"..."Match any single hardcoded string.
$AMatch variables, functions, arguments, classes, object methods, imports, exceptions, and more.
<... e ...>Match an expression ("e") that could be deeply nested within another expression.

Moreover, Semgrep provides several experimental modes that could be really useful in more difficult situations:
  • taint: It enables the data-flow analysis feature allowing to specify sources and sinks.
  • join: It allows to use multiple rules on more than one file and to join the results.
  • extract: It allows work with source file that contains different programming languages.
Suppose to have a rules collection in the directory "myrules/" and a target source code "mytarget/". To launch a Semgrep scan is very simple:
semgrep -c ./myrules ./mytarget

Wednesday, June 21, 2023

A Cool New Project: Semgrep Rules for Android Apps Security

Android Logo with a key like shape to introduce security.

In today's digital landscape, mobile application security has become an paramount concern

With the increasing number of threats targeting Android applications and the stored personal data, developers and security professionals alike are seeking robust solutions to fortify their code against potential vulnerabilities. 

That's why speeding up the time and minimizing the effort in the identification of mobile security issues has become definitely important.

We are excited to introduce our new project, focused on creating Semgrep rules specifically designed to enhance the security of Android apps.

Semgrep Rules for Android Application Security

The project provides a new set of specific rules for OWASP Mobile Security Testing Guide (MSTG), that will help to find security issues using static code analysis (SAST).

The Project

The OWASP Mobile Security Testing Guide (MSTG) is an invaluable resource for assessing the security posture of mobile applications. It provides comprehensive guidelines and best practices to identify and address potential security weaknesses. However, manually conducting these tests can be time-consuming and prone to human error. 

This is where this project come into play. 

By creating a set of Semgrep rules based on the OWASP Mobile Security Testing Guide, we aim to automate and streamline the security testing process for Android applications. 

These rules act as a way to shift left in the SDLC of Mobile apps, enabling developers and security practitioners to efficiently identify and mitigate vulnerabilities in their code. 

With Semgrep's static analysis capabilities and the knowledge base of the MSTG, we can significantly enhance the effectiveness and efficiency of mobile apps security assessments. 

Our project bridges the gap between theory and practice, empowering developers to build robust and resilient Android applications while ensuring that security remains a top priority.

Status

Since the beginning of the project to the present stage, we have continuously strived to deliver a solution to empower developers and security practitioners and defend against evolving threats and safeguard user data. 

The actual status of our project shows where it's going to be improved and where the semgrep version limitation is a blocker to create a useful rule is shown here, and every improvement will be updated as soon as it will be implemented.




Check it out now!

How to contribute:

In future posts we'll give some insight and explain how everyone can contribute to the project, in the meantime, your feedback is absolutely welcome! 

We strongly believe in the power of collaboration and community involvement, hence we invite developers, security enthusiasts, and Android app experts to actively contribute to our project through our GitHub repository. 

By participating in the project, you can contribute new Semgrep rules, suggest improvements to existing rules, report bugs, or even share insights and ideas to enhance the overall effectiveness of our Android app security framework. 

Visit our GitHub repository to explore the project, engage with fellow contributors, and make a meaningful impact in the field of mobile app security. 

Credits