"""
name: Dark Comet
category: config extractors
author: malcat

Decrypt config (unpacked) dark comet sample
"""
import json
import re
import malcat
malcat.setup()  # Add Malcat's data directories to sys.path when called in headless mode
from transforms.stream import RC4



############################ config extraction

def darkcomet_decrypt_config(a):
    res = {}
    for f in a.vfiles:
        if f.path.startswith("RCDATA/DCDATA/"):
            rsrcfile = f.open()
            data = bytes.fromhex(rsrcfile.read().decode("ascii"))
            dec = RC4().run(data, key=b"#KCMDDC51#-890")
            for line in dec.splitlines():
                if line.startswith(b"#"):
                    continue
                m = re.match(rb"\s*(\w+?)\s*=\s*(.*)\s*", line)
                if m:
                    key = m.group(1).decode("ascii")
                    value = m.group(2).decode("ascii", errors="replace")
                    res[key] = value
    return res 

################################ MAIN
    
if __name__ == "__main__":

    configs = []
    if "analysis" in globals():
        # called from the gui, analysis object is already instanciated with the current file
        configs.append(darkcomet_decrypt_config(analysis))
    else:
        # called in headless mode, we need to analyse a file first
        import optparse
        usage = "usage: %prog <file1> [file2] ... [fileN]"
        parser = optparse.OptionParser(usage=usage, description="""Extract config for (unpacked) Dark Comet samples""")
        options, args = parser.parse_args()
        if len(args) < 1:
            parser.error("Please give path to a file")

        for fname in args:
            a = malcat.analyse(fname)
            configs.append(darkcomet_decrypt_config(a))

    for config in configs:
        print("\nDARKCOMET_CONFIG = ", end="")
        print(json.dumps(config, indent=4))
