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

Sunday, August 3, 2025

Getting Started with Mobile Security Framework (MobSF) for Mobile App Security Testing


Mobile application security is no longer optional—it’s essential.
 Whether you’re an Android, iOS, or Windows mobile developer, integrating automated security assessments into your CI/CD pipeline can drastically improve your app’s resilience against attacks. Enter MobSF (Mobile Security Framework)—an all-in-one toolkit for performing static and dynamic analysis of mobile apps.

In this guide, we’ll walk through setting up MobSF using Docker on macOS with Colima and demonstrate how to conduct both static and dynamic analysis.


๐Ÿš€ What is MobSF?

Mobile Security Framework (MobSF) is an open-source, automated mobile application pentesting, malware analysis, and security assessment tool. It supports:

  • Static & dynamic analysis

  • Mobile binaries: .apk.ipa.appx.xapk

  • Source code (zipped)

  • REST APIs for CI/CD or DevSecOps integration

Whether you’re running tests during development or before release, MobSF provides valuable insights into the security posture of your app.


๐Ÿ›  Prerequisites

Before starting, ensure the following tools are installed on your macOS system:

  • Colima – Docker Desktop alternative for macOS

  • Docker

Installation Commands:

brew install colima
brew install docker
colima start

๐Ÿงช Running MobSF with Docker

Once Colima and Docker are set up, launch MobSF using the following command:

docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest


๐ŸŒ Accessing the MobSF Dashboard

After launching MobSF, the terminal logs will include a line like:

Listening at: http://127.0.0.1:8000

Copy this URL into your browser to open the MobSF dashboard.

Uploading an App:

Simply drag and drop your APK/IPA file into the dashboard to begin static analysis.


๐Ÿงพ Static Analysis

Once uploaded, MobSF automatically scans the app and generates a security report. Monitor the Docker logs to verify successful completion or identify potential issues during analysis.

Sample Reports:

  • AppSec Scorecard for Prod Build (v2.9.8)

  • Full Static Analysis Report

✅ These reports help developers and security teams identify code-level vulnerabilities, permission misuses, and more.


๐Ÿ” Dynamic Analysis

MobSF’s dynamic analysis enables runtime behavior assessment, allowing you to detect malicious operations or insecure runtime behaviors.

๐Ÿ”ง Requirements:

  • Emulator without Google Play Store

  • API level ≤ 28 (Android 9)

Step 1: Start Emulator

Navigate to your SDK tools directory and run:

cd ~/Library/Android/sdk/tools

./emulator -avd Pixel_5_API_28 -writable-system -no-snapshot

To list available AVDs:

emulator -list-avds

Step 2: Launch MobSF with Emulator Identifier

Find your emulator’s ID using:

adb devices

Then start MobSF with the emulator bound:

docker run -e MOBSF_ANALYZER_IDENTIFIER="emulator-5554" -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest

Step 3: Start Dynamic Analysis

In the MobSF UI:

  • Go to Dynamic Analyzer

  • Click Start Dynamic Analysis

MobSF will initiate an interactive test session connected to your emulator.


✅ Final Thoughts

MobSF is a powerful and developer-friendly framework for mobile app security. With minimal setup, it provides:

  • Actionable security insights

  • Seamless CI/CD integration

  • Both static and dynamic testing capabilities

By integrating MobSF into your development lifecycle, you ensure your mobile applications are secure, compliant, and robust.


๐Ÿ“Ž Useful Links



Saturday, August 2, 2025

๐Ÿ” Tools and Technologies I Use for Digital Forensics Investigations


Digital forensics
 plays a critical role in modern cybersecurity — whether it’s responding to a data breach, investigating insider threats, or performing incident analysis after suspicious behavior. In my work as a security-minded engineer and DevSecOps practitioner, I’ve frequently had to identify, collect, and analyze digital evidence across endpoints, servers, and cloud environments.

In this blog post, I’ll walk you through the tools and technologies I rely on to conduct effective digital forensics investigations — categorized by use case.


๐Ÿง  What Is Digital Forensics?

At its core, digital forensics is about identifying, preserving, analyzing, and reporting on digital data in a way that’s legally sound and technically accurate. The goal is to reconstruct eventsidentify malicious activity, and support security incident response.


๐Ÿงฐ My Go-To Tools for Digital Forensics Investigations


๐Ÿ—‚️ Disk & File System Analysis

These tools help examine hard drives, deleted files, system metadata, and more:

  • Autopsy (The Sleuth Kit) – A GUI-based forensic suite for analyzing disk images, file recovery, and timelines.

  • FTK Imager – For creating and previewing forensic images without altering the original evidence.

  • dd / dc3dd – Command-line tools to create low-level forensic disk images in Linux environments.

  • EnCase (Basic familiarity) – A commercial powerhouse in forensic investigations, used primarily for legal-grade evidence analysis.


๐Ÿงฌ Memory Forensics

Memory (RAM) often holds short-lived but critical evidence, like injected malware, live sessions, or loaded processes.

  • Volatility Framework – Extracts details like running processes, DLLs, command history, network activity, and more from memory dumps.

  • Rekall – An alternative memory analysis framework focused on automation and deep system state inspection.

✅ I’ve used Volatility to trace injected PowerShell payloads and enumerate hidden processes in live incident simulations.


๐ŸŒ Network Forensics

Capturing and analyzing network traffic is essential for spotting data exfiltration, command-and-control activity, or lateral movement.

  • Wireshark – Industry standard for packet analysis and protocol dissection.

  • tcpdump – Lightweight CLI tool to capture traffic in headless environments or remote systems.

  • NetworkMiner – Parses PCAP files to extract files, sessions, and credentials automatically.


๐Ÿ“Š Log & Timeline Analysis

Understanding what happened — and when — is key to reconstructing incidents.

  • Timesketch – A timeline analysis tool for visualizing and collaborating on event data.

  • Log2Timeline (Plaso) – Converts log files, browser histories, and system events into structured timelines.

  • Sysinternals Suite – Includes gems like ProcmonPsExec, and Autoruns for Windows incident response.


๐Ÿงช Malware Analysis (Static & Dynamic)

Understanding what a file does — before or while it runs — helps detect advanced threats and APT tools.

  • Ghidra – Powerful open-source reverse engineering tool from the NSA for analyzing executables.

  • x64dbg / OllyDbg – Popular debuggers for inspecting Windows executables.

  • Hybrid Analysis / VirusTotal – Cloud-based tools to scan files and observe sandbox behavior.

  • Cuckoo Sandbox – An open-source automated sandbox for observing malware behavior in a VM.


☁️ Cloud & Endpoint Forensics

Modern investigations often span cloud platforms and remote endpoints:

  • AWS CloudTrail, GuardDuty – Audit user and API activity in cloud environments.

  • Microsoft Azure Defender – For cloud-native threat detection and log correlation.

  • CrowdStrike Falcon / SentinelOne – Endpoint Detection and Response (EDR) tools for retrieving artifacts, hunting threats, and isolating compromised machines.


๐Ÿงฐ Scripting & Automation

Scripting accelerates collection, triage, and analysis — especially in large-scale environments.

  • Python – I use it to build custom Volatility plugins, PCAP parsers, or automate alert triage.

  • Bash / PowerShell – For live memory dumps, log gathering, process inspection, and rapid automation.


๐Ÿงฉ MITRE ATT&CK & DFIR Methodology

I map artifacts and behaviors to MITRE ATT&CK techniques (e.g., T1055 – Process Injection) to align with industry standards and communicate findings effectively.

I also follow established methodologies like:

  • SANS DFIR process

  • NIST 800-61 Incident Handling Guide

  • Custom playbooks for containment, eradication, and recovery

✅ Summary: Digital Forensics Tools I Use

๐Ÿ”น Disk & File System Analysis

  • Autopsy (Sleuth Kit) – GUI-based forensic suite

  • FTK Imager – Create and inspect forensic images

  • dd / dc3dd – Low-level disk imaging on Linux

  • EnCase – Commercial tool for deep disk investigations (basic familiarity)

๐Ÿ”น Memory Forensics

  • Volatility – Extract processes, DLLs, and sessions from RAM dumps

  • Rekall – Advanced volatile memory analysis

๐Ÿ”น Network Forensics

  • Wireshark – Protocol and packet analysis

  • tcpdump – Command-line traffic capture

  • NetworkMiner – Extracts files and sessions from PCAP files

๐Ÿ”น Log & Timeline Analysis

  • Timesketch – Timeline visualization and correlation

  • Plaso (log2timeline) – Converts raw logs into a forensic timeline

  • Sysinternals Suite – Live system inspection (Procmon, PsExec, Autoruns)

๐Ÿ”น Malware Analysis

  • Ghidra – Static reverse engineering

  • x64dbg / OllyDbg – Debuggers for binary inspection

  • Hybrid Analysis / VirusTotal – Behavioral analysis and threat intel

  • Cuckoo Sandbox – Automated dynamic malware analysis

๐Ÿ”น Cloud & Endpoint Forensics

  • AWS CloudTrail / GuardDuty – Monitor API and security activity

  • Microsoft Defender / Azure Logs – Cloud-native alerting and forensics

  • CrowdStrike Falcon / SentinelOne – EDR tools for endpoint activity and IOC collection

๐Ÿ”น Scripting & Automation

  • Python – For custom plugins, log parsers, automation

  • Bash / PowerShell – For system triage, memory dumps, and log collection

๐Ÿ”น Methodology

  • Align findings with MITRE ATT&CK

  • Follow structured DFIR frameworks like SANSNIST 800-61, and custom playbooks

๐ŸŽฏ Final Thoughts

Digital forensics isn’t just for breach responders — it’s a key skill for DevSecOps, SDETs, and any security-conscious engineer. Whether you’re building incident response workflows, simulating attacks, or validating your EDR, knowing how to collect and interpret evidence makes you far more effective.

Wednesday, July 30, 2025

๐Ÿš€ Turbo Intruder: Unleashing High-Speed Race Condition Testing with Burp Suite


When it comes to identifying race conditions and testing concurrency issues in APIs, Turbo Intruder is a must-have weapon in your offensive security toolkit. This powerful Burp Suite extension is built to launch blazing-fast HTTP requests—ideal for race condition exploits that require precise timing and volume.

Here’s a quick guide to getting started:


๐Ÿ› ️ Setting Up Turbo Intruder in Burp Suite

Step 1: Launch Burp Suite and go to the top menu → Extensions.

Step 2: In the Extensions tab, click BApp Store.

Step 3: Search for Turbo Intruder, then click Install.


⚙️ Running Your First Attack

Once installed, it’s time to get hands-on:

  • Select any API request in Burp’s HTTP history or Repeater.

  • Right-click the request → Navigate to Extensions > Turbo Intruder > Send to Turbo Intruder.

๐Ÿงฉ Customize the Request

  • Insert a %s token into any part of the request (e.g., a header or query parameter) where you want to inject payloads.

  • Scroll down to the scripting panel and modify the Python script to control how the payloads are fired—sequentially, concurrently, or in bursts.

 ๐Ÿ’ฅ Launch the Attack

  • Click Attack to fire off the customized payloads at high speed.

  • Analyze the results to detect anomalies that signal race conditions or concurrency flaws.

๐Ÿ” Why Turbo Intruder?

  • Speed: It outpaces traditional Burp tools with asynchronous, multi-threaded requests.

  • Control: Fine-grained scripting lets you simulate real-world race conditions.

  • Visibility: Detailed results make it easier to identify timing-related bugs.

๐Ÿง  Pro Tip

Race conditions often result in subtle, non-deterministic behavior. Run attacks multiple times and compare response patterns. Look out for HTTP 409, duplicated resources, or unauthorized access anomalies.


Try it out and take your API security testing to the next level!

Let me know your experience with Turbo Intruder or drop your favorite race condition use case in the comments ๐Ÿ‘‡


Tuesday, July 29, 2025

๐Ÿ›ก️ How to Test Security and Fraud Scenarios for Digital Payments


In a world where digital payments power everything from daily groceries to global remittances, ensuring security and fraud prevention is no longer a luxury—it’s mission-critical.

Whether you’re working on PayPal, Stripe, Razorpay, or GrabPay, your role as a QA or automation engineer is to make sure payments are secure, resilient, and abuse-proof.

In this post, we’ll walk through the strategies, techniques, and tools to test security and fraud detection in modern payment systems.


๐Ÿ” Security Testing in Digital Payments

1. Authentication & Authorization

Ensure that only the right users can initiate and complete payments.

  • Verify OTP, PIN, password, and biometric flows.

  • Test token/session expiry and renewal.

  • Simulate brute-force attacks to ensure rate-limiting and lockout work.

  • Ensure role-based permissions are enforced across all endpoints.

๐Ÿง  Tip: Use tools like Postman (with JWT plugin) or Burp Suite to test token manipulation and expiry.


2. Secure Transmission (SSL/TLS)

Payment data must be encrypted in transit.

  • Confirm HTTPS is enforced across all endpoints.

  • Reject weak cipher suites and expired/invalid SSL certificates.

  • Validate mobile apps implement certificate pinning.

Try capturing requests using Wireshark or Burp Proxy to verify encrypted transport.


3. Input Validation & Injection

Test every field involved in the transaction process.

  • Simulate SQL injection attacks in billing/payment address fields.

  • Test for XSS in saved cards or transaction summaries.

  • Use fuzzing tools to detect unhandled payloads in backend APIs.


4. Tokenization & PCI Compliance

Ensure sensitive card or bank data is never stored or displayed.

  • Check logs for PANs or CVVs—none should exist.

  • Confirm that tokens are used in place of actual card data.

  • Ensure your system complies with PCI DSS standards.


⚠️ Fraud Testing Scenarios

1. Business Logic Abuse

Fraud doesn’t always come from security holes—sometimes it’s clever users exploiting loopholes.

  • Test coupon abuse by simulating multiple users on a single device.

  • Attempt to game referral systems using parallel devices or emulators.

  • Try multiple cashback-eligible transactions under abnormal timelines.


2. Anomaly Detection & Geo Abuse

Your backend should detect and respond to abnormal behavior.

  • Simulate transactions from:

    • Blocked countries

    • VPN/tor networks

    • Inconsistent IP-device combinations

  • Trigger alerts for large amounts with unusual metadata.


3. Replay & Duplicate Payment Attacks

Ensure the system can handle re-sent or duplicate payment requests.

  • Test by refreshing the payment page and resubmitting the request.

  • Reuse expired OTPs and check if validation is still enforced.

  • Test if the system honors idempotency keys to avoid double charges.


๐Ÿงช Penetration & Automation Tools

Here are some of the tools commonly used in payment system security testing:

  • ๐Ÿ› ️ OWASP ZAP: Passive scanning and basic fuzzing

  • ๐Ÿงช Burp Suite: Full web/API pentesting and token tampering

  • ๐Ÿ”„ JMeter: Load testing and flood-simulation

  • ๐Ÿ•ต️ WireMock: Simulate gateway failure/response delays

  • ⚙️ Postman + Scripting: Token lifecycle and header replay testing


✅ Sample Test Scenarios

Here are critical test scenarios every QA or SDET should include when testing digital payment security and fraud systems:

  • ๐Ÿ” Carding Attack Simulation

    Try performing hundreds of small transactions rapidly using random or stolen card numbers.

    ➤ Expected: System blocks the IP, triggers rate limiting, or requires CAPTCHA.

  • ๐Ÿ”ข Brute Force OTP Attempts

    Continuously try random OTPs during checkout or login.

    ➤ Expected: User account gets locked or temporary timeout is enforced after a threshold.

  • ๐Ÿงพ Duplicate Payment Requests

    Submit the same payment request multiple times by refreshing or resending it.

    ➤ Expected: Only one transaction should succeed (idempotency should be enforced).

  • ๐ŸŒ Payments from Blocked Locations

    Try initiating payments using VPNs or from geographies that are disallowed.

    ➤ Expected: Gateway or system blocks the request based on geo or IP reputation.

  • ๐Ÿ”„ Session Replay by Refreshing Payment Page

    Refresh the payment page or use the back button and attempt a resubmission.

    ➤ Expected: Token/session should be invalidated, and user should be redirected to start fresh.

  • ๐Ÿท️ Coupon or Promo Abuse

    Apply the same promo or referral code across multiple user accounts/devices.

    ➤ Expected: Backend should detect abuse and flag or restrict suspicious users.

  • ๐Ÿ” Expired OTP or Token Reuse

    Reuse expired authorization codes or payment tokens.

    ➤ Expected: Server rejects the request with an appropriate error message.



๐Ÿ“Š Monitoring & Alerting (Post-release)

Don’t stop after testing. Monitor live systems for:

  • Unusual transaction spikes by IP or card BIN

  • High failure rates on certain gateways or banks

  • Repeated coupon or referral attempts

Use tools like ELK StackGrafanaPrometheus, and Splunk for visibility.


๐ŸŽฏ Final Thoughts

Security and fraud testing is not just about using tools—it’s about thinking like an attacker while keeping the business context in mind.

You need to:

  • Blend white-box + black-box testing.

  • Automate what’s repetitive.

  • Update your threat models regularly.

  • Work closely with product, dev, and security teams.

As testers, we’re not just validating features — we’re guarding the gates of trust in the digital economy.

Thursday, September 2, 2021

NFR Template/Checklist for JIRA


To make NFR as predefined template/checklist, we came up with few critical points to start with and it would be auto-populated as and when someone creates any story to the project.

Idea is to pushing NFR in initial phase discussion like designing and developing and as a cross check goes to QA. Apart from predefined template/checklist, anyone can work on other points too for which checklist already been published in Confluence under Guidelines and having predefined checklist in each story would ensure we are having NFR discussions too along with functional towards any deliverables to production.


NFR ListChecklist_PointsComments if any
Logging
Have we ensured we are not logging access logs?Access logs represent the request logs containing the API Path, status code, latencies & and any information about the request. We can avoid logging this since we already have this information in the istio-proxy logs
Have we ensured we didn't add any sort of secrets in logs (DB passwords, keys, etc) ?
Have we ensured that payload gets logged in the event of an error ?
Have we ensured that logging level can be dyanamic configured ?
Have we ensured that entire sequence of events in particular flow can be identified using an identifier like orderId or anything- The logs added should be meaningful enough such that anyone looking at the logs, regardless of whether they have context on the code should be able to understand the flow.
- For new features, it maybe important that the logs are logged as info to help ensure the feature is working is expected in production. Once we have confidence that the feature is working as expected, we could change these logs to debug unless required. Devs could take a call based on the requirement.
Have we ensured that we are using logging levels diligently ?
Timeouts
Have we ensured that we have set a timeout for database calls ?
Have we ensured that we have set a timeout for API call ?
Have we ensured that timeouts are derived from dependent component timeouts ?An API might have dependencies on few other components (APIs, DB queries, etc) internally. It is important the overall API timeout is considered after careful consideration of the dependent component timeouts.
Have we ensured that we have set a HTTP timeout ?Today, in most of our services we set timeouts at the client (caller). But we should also start looking at setting timeouts for requests on the server (callee). This way we ensure we kill the request in the server if it exceeds a timeout regardless of whether the client closes the connection or not.
Response Codes
Have we ensured that we are sending 2xx only for successfull scenarios ?
Have we ensured that we are sending 500 only for unexpected errors (excluding timeouts) ?
Have we ensured that we are sending 504 for a timeout error ?
Perf
Have we ensured that we did perf testing of any new API we build to get benchmark of the same we can go as per the expectations and can track accordingly going forward ?
We should identify below parameters as part of the perf test & any other additional info as per need:
- Max number of requests a pod can handle with the allocated resources
- CPU usage
- Memory usage
- Response times


Have we ensured we did perf testing of existing APIs if there are changes around it to make sure we didn’t impact existing benchmark results ?
Feature ToggleHave we ensured that we have feature toggle for new features to be able to go back to the old state at any given point until we are confident of the new changes. We may need to have toggles like feature will be enabled for specific users or city ?
ResiliencyHave we ensured that we are resilient to failures of dependent components (database, services ) ?
MetricsHave we ensured that we are capturing the right metrics in prometheous ?Below are some of the metrics that could be captured based on need or criticality:
- Business metrics (example: number of payment gateway failures)
- Business logic failures (example: number of rider prioritization requests that failed)
- Or any other errors which would be important to help assess the impact in a critical flow could be captured as metrics.
Security
Have we ensured that right authentication scheme is active at the gateway level ?This is applicable when we are adding any end point on Kong(Gateway). 
- any of the authentication plugins (jwt,key-auth/basic-auth) must be defined either at the route level or on the service level
- for gateway kong end points, acl plugin must be added and same group must be present on the consumer definition.
Have we ensured that proper rate limiting applied at the gateway level ?This is applicable when we are adding any end point on Kong(Gateway).Team leads are the code owners, so one of them have to check this when approving the PR. 
- rate limiting plugin needs to be enabled on the route / service level on the PR raised against kong-config. 
Have we ensured that we are retreiving the userId from JWT ?if requests is coming from kong, userid in requestbody should be matched with headers. Or for fetching any user related information, we have to read the userId only from the header populated by kong (x-consumer-username).

 


It would be populated in all Jira stories across projects as a predefined NFR checklist as given below screenshot.




Security Test Checklist - Cheatsheet

As part of engineering team, when specially we are dealing with scale and playing a role towards quality of end product we ship to outside world, it becomes quite important to make sure we looked into from security perspective for all the deliverables.

Please follow below checklist as part of your regular deliverables

  • Broken Object Level Authorization

    • Let’s say a user generates a document with ID=322. They should only be allowed access to that document. If you specify ID=109 or some other ID, the service should return the 403 (Forbidden) error. To test this issue, what parameters can you experiment with? You could pass any ID in the URL or as part of Query parameters or Body (in XML or JSON). Try changing them to see what the service returns to you.

  • Broken User Authentication

    • Here, you can test whether session token gets reassigned after each successful login procedure or after the access level gets escalated in the application. In case your application removes or somehow changes the session token, check to see whether it returns a 401 error. We must not allow the possibility of predicting the session token for each next session. It should be as random as possible.

  • Excessive Data Exposure

    • For example, you have an interface that displays three fields: First Name, Position, Email Address, and Photo. However, if you look at the API response, you may find more data, including some sensitive data like Birth Date or Home Address. The second type of Excessive Data Exposure occurs when UI data and API data are both returned correctly, but parameters are filtered on the front end and are not verified in any way on the back end. You may be able to specify in the request what data you need, but the back-end does not check whether you really have permission to access that data.

  • Lack of Resources & Rate Limiting

    • API should not send more than N requests per second. However, this strategy is not quite correct. If your client generates more traffic than another client, your API should be stable for all clients.

      This can be resolved using special status codes, for example, 429 (Too Many Requests). Using this status code, you can implement some form of Rate Limiting. There are also special proprietary headers. For example, GitHub uses its X-RateLimit-*. These headers help regulate how many requests the client can send during a specific unit of time.

    • The second scenario is related to the fact that you may not have enough parameter checks in the request. Suppose you have an application that returns a list of user types like size=10. What happens if an attacker changes this to 200000? Can the application cope with such a large request?

  • Broken Function Level Authorization

    • This is concerned with vertical levels of authorization —the user attempting to gain more access rights than allowed. For example, a regular user trying to become an admin. To find this vulnerability, you must first understand how various roles and objects in the application are connected. Secondly, you must clearly understand the access matrix implemented in the application.

  • Mass Assignment

    • Avoid providing convenient mass assignment functions (when assigning parameters in bulk).

  • Security Misconfiguration

    • What can you test here? First of all, unnecessary HTTP methods must be disabled on the server. Do not show any unnecessary user errors at all. Do not pass technical details of the error to the client. If your application uses Cross-Origin Resource Sharing (CORS), that is, if it allows another application from a different domain to access your application’s cookies, then these headers must be appropriately configured to avoid additional vulnerabilities. Any access to internal files must also be disabled.

  • Injections

    • In my opinion, modern frameworks, modern development methods, and architectural patterns block us from the most primitive SQL or XSS injections. For example, you can use the object-relational mapping model to avoid SQL injection. This does not mean that you need to forget about injections at all. Such problems are still possible throughout a huge number of old sites and systems. Besides XSS and SQL, you should look for XML injections, JSON injections, and so on.

  • Improper Assets Management

    • CI/CD pipelines have access to various secrets and confidential data, such as accounts used to sign the code. Ensure you do not leave hard-coded secrets in the code and don’t “commit” them to the repository, no matter whether it is public or private.

  • Insufficient Logging & Monitoring

    • The main idea here is that whatever happens to your application, you must be sure that you can track it. You should always have logs that show precisely what the attacker was trying to do. Also, have systems in place to identify suspicious traffic, and so on.Also we must check for secrets/credentials/confidential info in log. Have seen this in some cases where we log username/password of databases.

Thursday, July 22, 2021

API Security Testing - How we can do/stop hacking to the APIs : Part-3

 

The first two parts in this series have set us well on our path to API security/intrusion nirvana; we first got to grips with current API technology basics, moved on to API Attack surface detection and then looked at a series of common and potent vulnerability attacks – all sharing the fact that they are pretty simple to perform using a little wit and available tools. Let’s dig a little more in our arsenal before concluding with some hands on tips on how to work with API Security Testing.

Cross Site Request Forgery (CSRF)

The last vulnerabilities we looked at in the previous installment were related to cross-site scripting attacks (XSS). Now, let’s have a look at another vulnerability / attack that plays with similar cards; cross-site request forgery. Just like XSS, this is an attack that originates from a web-browser – but since it often follows through with an API call it is definitely something you should be aware of:

HackYourAPI10

Let’s walk through this so to provide an understanding of how this type of attack works:

  • A user logs in to his/her bank account – which sets a session cookie on the client
  • The bank shows a (malicious) ad for the latest vitamin pills, which the user clicks on without first logging out of the bank
  • The page selling vitamin pills also contains a hidden form performing a bank-transfer, which is submitted automatically without the user noticing
  • Since the user is still logged in to the bank the “forged request” succeeds and makes the transfer without the user noticing.

While this example may seem somewhat contrived (what bank shows vitamin ads?), I’m sure you get the idea, and I’m also sure I’m not the only one that has navigated away from an authenticated site without logging out first.

A common way to attempt to prevent these attacks is to look for specific http headers related to request referral, but headers can easily be spoofed using various techniques described online. The much better way to guard for these attacks from a development point-of-view is therefore to require a unique request token to be added to each incoming request to an API – either as an HTTP header or as a query parameter. The value is generated by the server when preparing the underlying webpage using a secret algorithm - which the attacker presumably won’t know – and thus won’t be able to.

Testing this becomes straightforward; are tokens enforced and validated correctly? What if you use one of the previously discussed techniques for the token itself; fuzzing, injection, etc.? Is this all handled gracefully or does an error message give away a little too much about how things are being done on the server side?

Insufficient SSL Configuration

Let’s shift our focus a little and have a look at some common vulnerabilities and attack opportunities that relate to the security stack of your API itself.

Using a self-signed SSL certificate is an easy mistake to make – the convenience of generating your own certificate is high – but the dangers are lurking, especially when it comes to APIs; if your app is the only one consuming your API your developers might even have hard-coded the client to accept the certificate – and then forgot all about it. Unfortunately, using a self-signed certificate leaves your API wide open for man-in-the-middle attacks – where an attacker inserts him/herself between the API and its client by replacing the client-facing certificate – allowing them to listen in on (and modify) traffic that was meant to be encrypted.

Testing for insufficient SSL configurations is straightforward – make sure your tests accept only valid certificates. Taking an extra precaution for MITM attacks is also advisable – for example by adding signatures to a message, which makes it impossible (well, almost) for a eavesdropper to modify messages on the wire, even if they manage to insert themselves in the communication pipeline. Testing with signatures, that they are enforced, correctly validated, etc. – is equally possible.

Insecure Direct Object References (IDOR)

Including object references as arguments to an API call is common practice – and consequently a very common API vulnerability is that access rights are not enforced for objects a user does not have access to. Identifying id parameters and sequentially looping through possible values can be an easy way to access data that isn’t meant for a user – once again API metadata can be a natural source for more information in this regard, making it easy for both hackers and tester to find possible attack surfaces within an API topology.

As a tester you need to validate that security is correctly enforced for objects one should not have access to – which is easily done by automating requests to resource not accessible and validating that the correct error messages are shown. At a higher level – you should perhaps also question the usage of identifier values that can easily be guessed – especially if the data is sensitive. Perhaps using GUID identifiers could be a better solution as identifiers in applicable cases.

Bad Session / Authentication Handling

The previous vulnerability is a specific example of whole slew of vulnerabilities related to bad session, security and authentication handling. Consider some more examples:

  • Are session tokens re-used or sequential?
  • Do session tokens timeout correctly?
  • Are tokens exposed in unencrypted traffic?
  • Are tokens added to URLs when sending links?
  • Are login endpoints restricted?

All of these will be obvious attack points for a hacker – and should be as such for you as a Security Tester. Make sure that the described situations are correctly handled, do not give “bad” error messages if charged with invalid / unexpected input (using the arsenal of tests we have been looking at) – and do not provide an entry point for a hacker to start prying away at the walls of your APIs defense mechanisms!

Recap – and some tips to go!

Some hands-on tips to ensure that your APIs are fully security tested before we say our goodbyes:

  • Automate: Most of the testing approaches for security vulnerabilities that we have covered can be automated and should definitely be done so – preferably against your production environment in some way. A system upgrade or server reconfiguration could be just as much a cause for a security vulnerability as bad development in the code of your APIs – and you definitely want to find out if such changes open up for unexpected vulnerabilities before anyone else.
  • Stay on top: OWASP provides invaluable services and information on Internet related security vulnerabilities – and how to work against them. Make it a habit to check out their website and match their recommendations and findings against your APIs and infrastructure. Follow their guidelines – specifically those geared at APIs - and make sure you are doing what you can base on their resources.
  • Finally - It’s your problem: Security is probably not going to be fixed or worried by anyone else than you, – make sure you give it the same attention and focus as you do to functional, performance, usability, A/B testing, etc. The price to pay for leaked passwords or erased user data is too high to pay for you not to care (which I know you do).

And there you have it - that’s it for the last part of the series. Hopefully you have learned plenty; basic underpinnings of API security vulnerabilities, how easy it is too perform common API attacks and how equally easy it is in most cases to test for corresponding vulnerabilities. Now get out there and hack an API!

My Profile

My photo
can be reached at 09916017317