def __init__(self):
     self.mixer = Mixer()
     self.remove = Remove()
     self.utils = Utils()
def main():
    if sys.version_info[0] != 3:
        print("[-] Intensio-Obfuscator only support Python 3.x")
        sys.exit(0)

    if sys.platform != "win32" and sys.platform != "linux":
        print("[-] This tool support [windows - Linux] only !")
        sys.exit(0)

    try:
        from core.utils.intensio_design import INTENSIO_BANNER
        from core.utils.intensio_utils import Utils
        from core.utils.intensio_usage import Args
        from core.utils.intensio_error import EXIT_SUCCESS, ERROR_BAD_ENVIRONMENT, ERROR_INVALID_PARAMETER, ERROR_BAD_ARGUMENTS,\
                                                ERROR_INVALID_FUNCTION, ERROR_FILE_NOT_FOUND
        from core.obfuscation.intensio_replace import ReplaceWords
        from core.obfuscation.intensio_padding import Padding
        from core.obfuscation.intensio_analyze import Analyze
        from core.obfuscation.intensio_remove import Remove
    except ImportError as e:
        print("[-] {0}\n".format(e))
        sys.exit(0)

    args = Args()
    utils = Utils()

    if len(sys.argv) > 1 and len(sys.argv) <= 14:
        pass
    else:
        print("[-] Incorrect number of arguments\n")
        args.GetArgHelp()
        sys.exit(ERROR_BAD_ARGUMENTS)

    if args.GetArgsValue().input:
        if args.GetArgsValue().output:
            if args.GetArgsValue().code:
                if re.match(r"^python$", args.GetArgsValue().code):
                    if args.GetArgsValue().mixerlevel:
                        if re.match(r"^lower$|^medium$|^high$",
                                    args.GetArgsValue().mixerlevel):
                            if not args.GetArgsValue().padding and not args.GetArgsValue().replace \
                                and not args.GetArgsValue().rcommentaries and not args.GetArgsValue().rprint:
                                print(
                                    "\n[-] Need at least one argument [-r --replace] or [-p --padding] or [-rc --rcommentaries] or [-rp --rprint]"
                                )
                                sys.exit(ERROR_BAD_ARGUMENTS)
                        else:
                            print(
                                "[-] Incorrect level of mixerlevel, [lower - medium - high] only supported\n"
                            )
                            sys.exit(ERROR_INVALID_PARAMETER)
                    else:
                        print(
                            "[-] Mixerlevel [-m --mixerlevel] argument missing\n"
                        )
                        sys.exit(ERROR_BAD_ARGUMENTS)
                else:
                    print(
                        "[-] '{0}' Incorrect code argument, [python] only supported\n"
                        .format(args.GetArgsValue().Code))
                    sys.exit(ERROR_INVALID_PARAMETER)
            else:
                print("[-] Code [-c --code] argument missing\n")
                sys.exit(ERROR_BAD_ARGUMENTS)
        else:
            print("[-] Output [-o --output] argument missing\n")
            sys.exit(ERROR_BAD_ARGUMENTS)
    else:
        print("[-] Input [-i --input] argument missing\n")
        sys.exit(ERROR_BAD_ARGUMENTS)

    for line in INTENSIO_BANNER.split("\n"):
        time.sleep(0.05)
        print(line)

    # -- Analysis and set up of the work environment -- #
    print(
        "\n\n*********************** [ Analyze and setup environment ] ************************\n"
    )
    analyze = Analyze()

    if (analyze.InputAvailable(args.GetArgsValue().input,
                               args.GetArgsValue().code,
                               args.GetArgsValue().verbose) == EXIT_SUCCESS):
        print("\n[+] Analyze input argument '{0}' -> Successful".format(
            args.GetArgsValue().input))
    else:
        print("[-] Analyze input '{0}' failed\n".format(
            args.GetArgsValue().input))
        sys.exit(ERROR_INVALID_FUNCTION)

    if (analyze.OutputAvailable(args.GetArgsValue().input,
                                args.GetArgsValue().code,
                                args.GetArgsValue().output,
                                args.GetArgsValue().verbose) == EXIT_SUCCESS):
        print(
            "\n[+] Analyze and setup output argument environment '{0}' -> Successful"
            .format(args.GetArgsValue().output))
    else:
        print("[-] Analyze output '{0}' failed\n".format(
            args.GetArgsValue().output))
        sys.exit(ERROR_INVALID_FUNCTION)

    # -- Obfuscation process -- #
    print(
        "\n\n************************** [ Obfuscation Rcommentaries ] **************************\n"
    )
    if args.GetArgsValue().rcommentaries:
        removeData = Remove()

        if (removeData.Commentaries(
                args.GetArgsValue().code,
                args.GetArgsValue().output) == EXIT_SUCCESS):
            print("[+] Obfuscation Rcommentaries -> Successful")
        else:
            print("\n[-] Obfuscation Rcommentaries -> Failed")
    else:
        print("[!] Obfuscation Rcommentaries no asked !")

    print(
        "\n\n***************************** [ Obfuscation Replace ] *****************************\n"
    )
    if args.GetArgsValue().replace:
        replaceWords = ReplaceWords()

        if (replaceWords.VarsDefinedByUser(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel,
                args.GetArgsValue().verbose) == EXIT_SUCCESS):
            print("[+] Obfuscation Replace -> Successful")
        else:
            print("\n[-] Obfuscation Replace -> Failed")
    else:
        print("[!] Obfuscation Replace no asked !")

    print(
        "\n\n***************************** [ Obfuscation Padding ] *****************************\n"
    )
    if args.GetArgsValue().padding:
        paddingScripts = Padding()

        if (paddingScripts.AddScripts(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel) == EXIT_SUCCESS):
            print("[+] Obfuscation Padding -> Successful")
        else:
            print("\n[-] Obfuscation Padding -> Failed")
    else:
        print("[!] Obfuscation Padding no asked !")

    print(
        "\n\n****************************** [ Obfuscation Rprint ] *****************************\n"
    )
    if args.GetArgsValue().rprint:

        if (removeData.PrintFunc(args.GetArgsValue().code,
                                 args.GetArgsValue().output) == EXIT_SUCCESS):
            print("[+] Obfuscation Rprint -> Successful\n")
        else:
            print("\n[-] Obfuscation Rprint -> Failed\n")
    else:
        print("[!] Obfuscation Rprint no asked !\n")
class Padding:
    def __init__(self):
        self.mixer = Mixer()
        self.remove = Remove()
        self.utils = Utils()

    def ScriptsGenerator(self, codeArg, mixerLevelArg):
        if mixerLevelArg == "lower":
            varRandom1 = self.mixer.GetStringMixer("lower")
            varRandom2 = self.mixer.GetStringMixer("lower")
            varRandom3 = self.mixer.GetStringMixer("lower")
            varRandom4 = self.mixer.GetStringMixer("lower")
            varRandom5 = self.mixer.GetStringMixer("lower")
            varRandom6 = self.mixer.GetStringMixer("lower")
            varRandom7 = self.mixer.GetStringMixer("lower")
            varRandom8 = self.mixer.GetStringMixer("lower")
            varRandom9 = self.mixer.GetStringMixer("lower")
            varRandom10 = self.mixer.GetStringMixer("lower")
            varRandom11 = self.mixer.GetStringMixer("lower")
            varRandom12 = self.mixer.GetStringMixer("lower")
        elif mixerLevelArg == "medium":
            varRandom1 = self.mixer.GetStringMixer("medium")
            varRandom2 = self.mixer.GetStringMixer("medium")
            varRandom3 = self.mixer.GetStringMixer("medium")
            varRandom4 = self.mixer.GetStringMixer("medium")
            varRandom5 = self.mixer.GetStringMixer("medium")
            varRandom6 = self.mixer.GetStringMixer("medium")
            varRandom7 = self.mixer.GetStringMixer("medium")
            varRandom8 = self.mixer.GetStringMixer("medium")
            varRandom9 = self.mixer.GetStringMixer("medium")
            varRandom10 = self.mixer.GetStringMixer("medium")
            varRandom11 = self.mixer.GetStringMixer("medium")
            varRandom12 = self.mixer.GetStringMixer("medium")
        elif mixerLevelArg == "high":
            varRandom1 = self.mixer.GetStringMixer("high")
            varRandom2 = self.mixer.GetStringMixer("high")
            varRandom3 = self.mixer.GetStringMixer("high")
            varRandom4 = self.mixer.GetStringMixer("high")
            varRandom5 = self.mixer.GetStringMixer("high")
            varRandom6 = self.mixer.GetStringMixer("high")
            varRandom7 = self.mixer.GetStringMixer("high")
            varRandom8 = self.mixer.GetStringMixer("high")
            varRandom9 = self.mixer.GetStringMixer("high")
            varRandom10 = self.mixer.GetStringMixer("high")
            varRandom11 = self.mixer.GetStringMixer("high")
            varRandom12 = self.mixer.GetStringMixer("high")

        # ---------- Python random scripts ---------- #
        if codeArg == "python":
            rand = random.randint(1, 5)

            # -- script 1 -- #
            if rand == 1:
                scriptAssPadding1 = textwrap.dedent("""
                                                    {0} = '{5}'
                                                    {1} = '{6}'
                                                    {2} = '{7}'
                                                    {3} = '{8}'
                                                    {4} = '{9}'
                                                    if {0} in {1}:
                                                        {0} = {4}
                                                        if {1} in {2}:
                                                            {1} = {3}
                                                    elif {1} in {0}:
                                                        {2} = {1}
                                                        if {2} in {1}:
                                                            {1} = {4}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, \
                                                                varRandom6, varRandom7, varRandom8, varRandom9, varRandom10)
                return scriptAssPadding1

            # -- script 2 -- #
            elif rand == 2:
                scriptAssPadding2 = textwrap.dedent("""
                                                    {0} = '{4}'
                                                    {1} = '{5}'
                                                    if {0} != {1}:
                                                        {2} = '{6}'
                                                        {3} = '{7}'
                                                        {3} = {2}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, \
                                                                varRandom6, varRandom7, varRandom8)
                return scriptAssPadding2

            # -- script 3 -- #
            elif rand == 3:
                scriptAssPadding3 = textwrap.dedent("""
                                                    {0} = '{6}'
                                                    {1} = '{7}'
                                                    {2} = '{8}'
                                                    {3} = '{9}'
                                                    {4} = '{10}'
                                                    {5} = '{11}'
                                                    if {0} != {3}:
                                                        {1} = {2}
                                                        for {5} in {3}:
                                                            if {5} != {2}:
                                                                {1} = {1}
                                                            else:
                                                                {4} = {0}
                                                    else:
                                                        {2} = {0}
                                                        {0} = {4}
                                                        if {2} == {0}:
                                                            for {5} in {0}:
                                                                if {5} == {2}:
                                                                    {2} = {0}
                                                                else:
                                                                    {2} = {4}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, \
                                                                varRandom6, varRandom7, varRandom8, varRandom9, varRandom10, \
                                                                varRandom11, varRandom12)
                return scriptAssPadding3

            # -- script 4 -- #
            elif rand == 4:
                scriptAssPadding4 = textwrap.dedent("""
                                                    {0} = '{4}'
                                                    {1} = '{5}'
                                                    {3} = '{7}'
                                                    if {0} == {1}:
                                                        {2} = '{6}'
                                                        {2} = {0}
                                                    else:
                                                        {2} = '{6}'
                                                        {2} = {3}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, \
                                                                varRandom5, varRandom6, varRandom7, varRandom8)
                return scriptAssPadding4

            # -- script 5 -- #
            elif rand == 5:
                scriptAssPadding5 = textwrap.dedent("""
                                                    {0} = '{6}'
                                                    {1} = '{7}'
                                                    {2} = '{8}'
                                                    {3} = '{9}'
                                                    {4} = '{10}'
                                                    {5} = '{11}'
                                                    if {2} == {3}:
                                                        for {5} in {4}:
                                                            if {5} == {3}:
                                                                {4} = {0}
                                                            else:
                                                                {3} = {1}
                                                    """).format(varRandom1, varRandom2, varRandom3, \
                                                        varRandom4, varRandom5, varRandom6, \
                                                        varRandom7, varRandom8, varRandom9, \
                                                        varRandom10, varRandom11, varRandom12)
                return scriptAssPadding5

    def AddScripts(self, codeArg, outputArg, mixerLevelArg):
        listCheckLineWhitoutSpace = []
        listCheckLine = []
        countScriptsAdded = 0
        countLineAdded = 0
        countLine = 0
        checkLine = 0
        checkQuotePassing = 0
        checkCharPassing = 0
        countRecursFiles = 0
        checkParenthesesCharPassing = 0
        checkBracketsCharPassing = 0
        checkBracesCharPassing = 0

        if codeArg == "python":
            detectFile = "py"
            blockDirs = r"__pycache__"

        recursFiles = [
            f for f in glob.glob("{0}{1}**{1}*.{2}".format(
                outputArg, self.utils.Platform(), detectFile),
                                 recursive=True)
        ]

        # -- Count the number of lines that will be checked before filling -- #
        for file in recursFiles:
            if re.match(blockDirs, file):
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        if not eachLine:
                            continue
                        countLine += 1

        for number in recursFiles:
            countRecursFiles += 1

        print("\n[+] Running adding of random scripts in {0} file(s)...\n".
              format(countRecursFiles))

        # -- Padding scripts added -- #
        with tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                pbar.update(1)
                if re.match(blockDirs, file):
                    continue
                else:
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            print(eachLine)
                            if eachLine == "\n":
                                continue
                            else:
                                if codeArg == "python":
                                    spaces = len(eachLine) - len(
                                        eachLine.lstrip())  # Check line indent
                                    noAddScript = r"^\@|\s+\@|\s+return|\s*def\s+.+\s*\:{1}|^class\s+.+\s*\:{1}|.*[\[|\(|\{|\,|\\]$|\s+[\)|\]|\}]$"
                                    addIndentScript = r".*\:{1}\s"
                                    checkAddIndentScript = r".*\:{1}\s\w+"

                                    quoteIntoVariable = r".*\={1}\s*\w*\.?\w*[\(|\.]{1}[\"|\']{3}|.*\={1}\s*[\"|\']{3}"  # """ and ''' before an variables
                                    quoteOfCommentariesMultipleLines = r"^\s*[\"|\']{3}$"  # """ and ''' without before variables and if commentaries is over multiple lines
                                    quoteOfEndCommentariesMultipleLines = r"^\s*[\"|\']{3}\)?\.?"  # """ and ''' without before variables, if commentaries is over multiple lines and he finish by .format() funtion

                                    listCheckLine = []  # Initialize var

                                    for i in eachLine:
                                        listCheckLine.append(i)

                                    # -- Check if end char in line is "'" or '"' -- #
                                    if re.match(r"\"|\'", listCheckLine[-2]):
                                        try:
                                            if re.match(
                                                    r"\'|\"", listCheckLine[-3]
                                            ) and re.match(
                                                    r"\'|\"",
                                                    listCheckLine[-4]):
                                                pass
                                            else:
                                                continue
                                        except IndexError:
                                            continue

                                    # -- Check code into """ or ''' -- #
                                    if re.match(quoteIntoVariable, eachLine):
                                        checkQuotePassing += 1
                                        continue
                                    elif re.match(
                                            quoteOfCommentariesMultipleLines,
                                            eachLine
                                    ) or re.match(
                                            quoteOfEndCommentariesMultipleLines,
                                            eachLine):
                                        checkQuotePassing += 1
                                        if checkQuotePassing == 2:
                                            checkQuotePassing = 0
                                        continue

                                    if checkQuotePassing == 1:
                                        continue
                                    elif checkQuotePassing == 2:
                                        checkQuotePassing = 0
                                        continue
                                    else:
                                        checkQuotePassing = 0

                                # -- Add scripts -- #
                                if re.match(noAddScript, eachLine) is not None:
                                    continue
                                elif re.match(addIndentScript,
                                              eachLine) is not None:
                                    if re.match(checkAddIndentScript,
                                                eachLine) is not None:
                                        continue
                                    else:
                                        if spaces == 0:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "    "))
                                            countScriptsAdded += 1
                                        elif spaces == 4:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "        "))
                                            countScriptsAdded += 1
                                        elif spaces == 8:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "            "))
                                            countScriptsAdded += 1
                                        elif spaces == 12:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "                "))
                                            countScriptsAdded += 1
                                        else:
                                            continue
                                else:
                                    if spaces == 0:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg), ""))
                                        countScriptsAdded += 1
                                    elif spaces == 4:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg), "    "))
                                        countScriptsAdded += 1
                                    elif spaces == 8:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg),
                                                "        "))
                                        countScriptsAdded += 1
                                    elif spaces == 12:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg),
                                                "            "))
                                        countScriptsAdded += 1
                                    else:
                                        continue

        # -- Check padding has added in output script -- #
        for file in recursFiles:
            if re.match(blockDirs, file):
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        if not eachLine:
                            continue
                        checkLine += 1

        countLineAdded = checkLine - countLine

        if (self.remove.LineBreaks(codeArg, outputArg) == 0):
            if checkLine > countLine:
                print("\n-> {0} scripts added in {1} file(s)\n".format(
                    countScriptsAdded, countRecursFiles))
                print("-> {0} lines added in {1} file(s)\n".format(
                    countLineAdded, countRecursFiles))
                return EXIT_SUCCESS

            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE
Esempio n. 4
0
class Replace:

    def __init__(self):
        self.mixer              = Mixer()
        self.remove             = Remove()
        self.utils              = Utils()
        self.pythonExcludeWords = "exclude_python_words.txt"
        self.pythonIncludeWords = "include_python_words.txt"

    def EachLine(self, codeArg, eachLine, Dict):
        getIndexLineList    = []
        returnLine          = []
        charValue           = []
        checkCharAfterWord  = 1
        wordSetter          = 0
        checkGetKey         = ""
        checkGetWord        = ""
        getLine             = ""
        breakLine           = ""

        if codeArg == "python":
            regReplace = r"(\.)|(:)|(\))|(\()|(=)|(\[)|(\])|({)|(})|(,)|(\+)|(\s)|(\*)|(\+)|(\-)"

        # -- Get list of all letters in line -- #
        for indexLine, letterLine in enumerate(eachLine):
            getIndexLineList.append(letterLine)

        # -- Loop in each letter of line -- #
        for indexLine, letterLine in enumerate(eachLine):
            # -- Add in final line list all chars mixed -- #
            if charValue != []:
                for obfIndex, obfValue in enumerate(charValue):
                    if obfIndex == 0: # First letter in string mixed are already add in the final line
                        continue
                    returnLine.append(obfValue)
                charValue = []

                # -- If the variable is only a letter, check if the next character is specific so as not to replace it -- #
                if re.match(regReplace, letterLine):
                    returnLine.append(letterLine)

                # -- Count indexes of word to move after it --#
                countDeleteIndex = 0
                for i in getWord:
                    countDeleteIndex += 1
                wordSetter = countDeleteIndex - 2 # -2 Is to letter already append and the letter in progress
            else:
                # -- The index numbers of variable is decremented to add the mixed letters that be replaced -- #
                if wordSetter > 0:
                    wordSetter -= 1
                    continue
                else:
                    try:
                        # -- Loop in the dictionary with already mixed values-- #
                        for key, value in Dict:
                            for indexKey, letterKey in enumerate(key):
                                for letterValue in value:
                                    # -- Check if letter of word is equal to letter of key -- #
                                    if letterKey == letterLine:
                                        # -- Begin process to check  -- #
                                        if indexKey == 0:
                                            # -- Place index position after the word -- #
                                            indexExplore = indexLine + len(key)

                                            # -- If indexError return to next loop -- #
                                            try:
                                                getIndexLineList[indexExplore]
                                            except IndexError: 
                                                continue

                                            # -- Check the char after the word -- #
                                            if re.match(regReplace, getIndexLineList[indexExplore]):
                                                # -- Check word finded is not into the other word -- #
                                                indexExplore = indexLine - 1
                                                if not re.match(r"(\w)", getIndexLineList[indexExplore]):
                                                    if codeArg == "python":
                                                        # -- Check if it's 'from' and 'import' word key in line to avoid replace name of file if variable is identic name to file -- #
                                                        getLine = "".join(getIndexLineList)
                                                        if "import" in getLine:
                                                            if "from" in getLine:
                                                                # -- Cut the line from the current index and check if it is not there is the keyword "import" in the line -- #
                                                                breakLine = getIndexLineList[:indexLine]
                                                                breakLine = "".join(breakLine)
                                                                if not "import" in breakLine:
                                                                    # -- It's file because only 'from'key word -- #
                                                                    checkCharAfterWord = 1
                                                                else:
                                                                    checkCharAfterWord = 0
                                                            else:
                                                                checkCharAfterWord = 0
                                                        else:
                                                            checkCharAfterWord = 0
                                                else:
                                                    checkCharAfterWord = 1
                                            else:
                                                checkCharAfterWord = 1

                                            if checkCharAfterWord == 0:
                                                # -- Initialize vars -- #
                                                getCharAllInKey     = []
                                                getWord             = []

                                                indexExploreStart   = indexLine
                                                indexExploreEnd     = indexLine + len(key) - 1 # Remove -1, first letter is already increment

                                                # -- List contain all letters of key -- #
                                                for getLetterKey in key:
                                                    getCharAllInKey.append(getLetterKey)

                                                # -- Check if all letters of key is equal to all letters of word -- #
                                                for indexCheckLetter, checkLetter in enumerate(getIndexLineList):
                                                    if indexCheckLetter >= indexExploreStart and indexCheckLetter <= indexExploreEnd:
                                                        getWord.append(checkLetter)

                                                # -- Check if number of chars in key equal number of chars in word -- #
                                                if list(set(getCharAllInKey) - set(getWord)) == []:
                                                    checkGetWord    = "".join(getWord)
                                                    checkGetKey     = "".join(getCharAllInKey)

                                                    # -- Check if key == word -- #
                                                    if checkGetWord == checkGetKey:
                                                        for obfChar in value:
                                                            charValue.append(obfChar)

                                                        letterLine = letterValue
                                                        raise BreakLoop
                                                    else:
                                                        continue
                                                else:
                                                    continue
                                            else:
                                                continue
                                        else:
                                            continue
                                    else:
                                        continue

                        raise BreakLoop

                    except BreakLoop:
                        returnLine.append(letterLine)

        # -- Rewrite the line -- #
        returnLine = "".join(returnLine)
        return returnLine[:]
    
    def VarsDefinedByUser(self, oneFileArg, codeArg, outputArg, mixerLevelArg):
        variablesDict       = {}
        checkVarsMixed      = []
        wordsExcluded       = []
        wordsExcludedFound  = []
        wordsInclude        = []
        checkCountVarsMixed = 0
        checkCountVarsValue = 0
        checkPassing        = 0
        numberReplaced      = 0
        isCommentary        = 0
        noCommentary        = 0

        if codeArg == "python":
            variablesDefined            = r"(^\w+|\w+)([\s|^\s]*=[\s|\w|\"|\'])"    # Classic variables
            variablesErrorDefined       = r"except(\s+\w+\sas\s)(\w)"               # Error variables
            variablesLoopDefined        = r"for\s([\w\s?\,?]{1,})(\sin)"            # Loop variables
            functionsDefined            = r"def\s(\w+)"                             # Functions
            classDefined                = r"class\s(\w+)"                           # Classes

            quoteOfCommentariesOneLine  = r"[\"\']{3}.*[\"\']{3}"       # """ and ''' without before variables and if commentary is over one line, (""" commentaries """)
            noQuoteOfCommentaries       = r"\s*\w+\s*\={1}\s*[\"\']{3}" # """ and ''' with before variables

        print("######## [ Variables-Classes-Functions ] ########\n")

        ######################################### One file only #########################################

        if oneFileArg:
            # -- Find variables - classes - functions and mixed it -- #
            with open(outputArg, "r") as readFile:
                readF = readFile.readlines()
                for eachLine in readF:
                    
                    # -- Classic variables -- #     
                    search = re.search(variablesDefined, eachLine)
                    if search != None:
                        # -- Detect mixer -- #
                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                        # -- Add the mixer value of variables -- #
                        if search.group(1) not in variablesDict:
                            variablesDict[search.group(1)] = mixer
                    
                    # -- Error variables -- #
                    search = re.search(variablesErrorDefined, eachLine)
                    if search != None:
                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                        if search.group(2) not in variablesDict:
                            variablesDict[search.group(2)] = mixer
                    
                    # -- Loop variables -- #
                    search = re.search(variablesLoopDefined, eachLine)
                    if search != None:
                        if "," in search.group(1):
                            varsInFor = []
                            modifySearch = search.group(1).replace(",", " ")
                            modifySearch = modifySearch.split()
                            for i in modifySearch:
                                if i not in variablesDict:
                                    mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                    variablesDict[i] = mixer 
                        else:
                            if search.group(1) not in variablesDict:
                                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                variablesDict[search.group(1)] = mixer
                    
                    # -- Functions -- #         
                    search = re.search(functionsDefined, eachLine)
                    if search != None:
                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                        if search.group(1) not in variablesDict:
                            if codeArg == "python":
                                if not re.match(r"(^__init__$)", search.group(1)):
                                    variablesDict[search.group(1)] = mixer

                    # -- Classes -- #
                    search = re.search(classDefined, eachLine)
                    if search != None:
                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                        if search.group(1) not in variablesDict:
                            variablesDict[search.group(1)] = mixer

            # -- Delete excluded variables - classes - functions from excluded_python_varaibles.txt in dict -- #
            if os.path.exists(self.pythonExcludeWords) == True:
                with open(self.pythonExcludeWords, "r") as readFile:
                    for word in readFile:
                        if "#" in word or word == "\n":
                            continue
                        else:
                            word = word.rstrip()    
                            wordsExcluded.append(word)
            else:
                print("[-] File '{0}' not found\n".format(self.pythonExcludeWords))
            
            for word in wordsExcluded:
                if word in variablesDict.keys():
                    wordsExcludedFound.append(word)
                    del variablesDict[word]

            # -- Include variables - classes - functions defined from include_python_words.txt in dict -- #
            if os.path.exists(self.pythonIncludeWords) == True:
                with open(self.pythonIncludeWords, "r") as readFile:
                    for word in readFile:
                        if "#" in word or word == "\n":
                            continue
                        else:
                            word = word.rstrip()
                            wordsInclude.append(word)
            else:
                print("[-] File '{0}' not found\n".format(self.pythonIncludeWords))
            
            for word in wordsInclude:
                if word not in variablesDict.keys():
                    mixer = self.mixer.GetStringMixer(mixerLevelArg)
                    variablesDict[word] = mixer

            print("\n[+] Variables - Classes - Functions found :\n")
            
            for key, value in variablesDict.items():
                print("-> {0} : {1}".format(key, value))
            
            for word in wordsExcludedFound:
                print("-> {0} : excluded".format(word))
            
            print("\n[+] Running replacement of Variables - Classes - Functions...\n")

            # -- Change variables - classes - functions to mixed values -- #
            with fileinput.input(outputArg, inplace=True) as inputFile:
                for eachLine in inputFile:
                    if not eachLine:
                        continue
                    else:
                        if codeArg == "python":
                            # -- Check code in """ or ''' -- #
                            if "\"\"\"" in eachLine or "\'\'\'" in eachLine:
                                if re.match(quoteOfCommentariesOneLine, eachLine):
                                    print(eachLine)
                                    continue
                                elif re.match(noQuoteOfCommentaries, eachLine):
                                    eachLine = Replace.EachLine(self, codeArg, eachLine, variablesDict.items())
                                    print(eachLine)
                                    checkPassing += 1
                                    continue
                                else:
                                    checkPassing += 1

                            if checkPassing == 1:
                                print(eachLine)
                                continue
                            else:
                                checkPassing = 0
                                eachLine = Replace.EachLine(self, codeArg, eachLine, variablesDict.items())
                                print(eachLine)

            # -- Check if variables - classes - functions have been mixed -- #
            with open(outputArg, "r") as readFile:
                readF = readFile.readlines()
                for eachLine in readF:
                    for value in variablesDict.values():
                        if value in eachLine:
                            checkVarsMixed.append(value)
                
                # -- Remove duplicated key -- #
                checkListVarsMixed = list(dict.fromkeys(checkVarsMixed))
        
                for i in checkListVarsMixed:
                    checkCountVarsMixed += 1
                for i in variablesDict.values():
                    checkCountVarsValue += 1

            if checkCountVarsMixed == checkCountVarsValue:
                print("-> {0} variables - classes - functions replaced\n".format(checkCountVarsValue))
                if (self.remove.LineBreaks(oneFileArg, codeArg, outputArg) == 0):
                    return EXIT_SUCCESS
                else:
                    return EXIT_FAILURE
            else:
                return EXIT_FAILURE

        ######################################### Multiple files #########################################

        else:
            if codeArg == "python":
                inputExt    = "py"
                blockdirs   = r"__pycache__"

            recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, self.utils.Platform(), inputExt), recursive=True)]

            # -- Find variables - classes - functions and mixed it -- #
            for output in recursFiles:
                if re.match(blockdirs, output):
                    continue
                else:
                    with open(output, "r") as readFile:
                        readF = readFile.readlines()
                        for eachLine in readF:
                            # -- Classic variables -- #     
                            search = re.search(variablesDefined, eachLine)
                            if search != None:
                                # -- Detect mixer -- #
                                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                # -- Add the mixer value of variables -- #
                                if search.group(1) not in variablesDict:
                                    variablesDict[search.group(1)] = mixer
                            
                            # -- Error variables -- #
                            search = re.search(variablesErrorDefined, eachLine)
                            if search != None:
                                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                if search.group(2) not in variablesDict:
                                    variablesDict[search.group(2)] = mixer
                            
                            # -- Loop variables -- #
                            search = re.search(variablesLoopDefined, eachLine)
                            if search != None:
                                if "," in search.group(1):
                                    varsInFor = []
                                    modifySearch = search.group(1).replace(",", " ")
                                    modifySearch = modifySearch.split()
                                    for i in modifySearch:
                                        if i not in variablesDict:
                                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                            variablesDict[i] = mixer 
                                else:
                                    if search.group(1) not in variablesDict:
                                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                        variablesDict[search.group(1)] = mixer
                            
                            # -- Functions -- #         
                            search = re.search(functionsDefined, eachLine)
                            if search != None:
                                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                if search.group(1) not in variablesDict:
                                    if codeArg == "python":
                                        if not re.match(r"(^__init__$)", search.group(1)):
                                            variablesDict[search.group(1)] = mixer

                            # -- Classes -- #
                            search = re.search(classDefined, eachLine)
                            if search != None:
                                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                if search.group(1) not in variablesDict:
                                    variablesDict[search.group(1)] = mixer

            # -- Remove excluded variables - classes - functions defined from excluded_python_words.txt in dict -- #
            if os.path.exists(self.pythonExcludeWords) == True:
                with open(self.pythonExcludeWords, "r") as readFile:
                    for word in readFile:
                        if "#" in word or word == "\n":
                            continue
                        else:
                            word = word.rstrip()    
                            wordsExcluded.append(word)
            else:
                print("[-] File '{0}' not found\n".format(self.pythonExcludeWords))
            
            for word in wordsExcluded:
                if word in variablesDict.keys():
                    wordsExcludedFound.append(word)
                    del variablesDict[word]

            # -- Include variables - classes - functions defined from include_python_words.txt in dict -- #
            if os.path.exists(self.pythonIncludeWords) == True:
                with open(self.pythonIncludeWords, "r") as readFile:
                    for word in readFile:
                        if "#" in word or word == "\n":
                            continue
                        else:
                            word = word.rstrip()
                            wordsInclude.append(word)
            else:
                print("[-] File '{0}' not found\n".format(self.pythonIncludeWords))
            
            for word in wordsInclude:
                if word not in variablesDict.keys():
                    mixer = self.mixer.GetStringMixer(mixerLevelArg)
                    variablesDict[word] = mixer

            print("\n[+] Variables - Classes - Functions found :\n")

            for key, value in variablesDict.items():
                print("-> {0} : {1}".format(key, value))

            for word in wordsExcludedFound:
                print("-> {0} : excluded".format(word))
            
            print("\n[+] Running replacement of Variables - Classes - Functions...\n")

            # -- Change variables - classes - functions to mixed values -- #
            for output in recursFiles:
                if re.match(blockdirs, output):
                    continue
                else:
                    with fileinput.input(output, inplace=True) as inputFile:
                        for eachLine in inputFile:    
                            if not eachLine:
                                continue
                            else:
                                if codeArg == "python":
                                    # -- Check code in """ or ''' -- #
                                    if "\"\"\"" in eachLine or "\'\'\'" in eachLine:
                                        if re.match(quoteOfCommentariesOneLine, eachLine):
                                            print(eachLine)
                                            continue
                                        elif re.match(noQuoteOfCommentaries, eachLine):
                                            eachLine = Replace.EachLine(self, codeArg, eachLine, variablesDict.items())
                                            print(eachLine)
                                            checkPassing += 1
                                            continue
                                        else:
                                            checkPassing += 1

                                    if checkPassing == 1:
                                        print(eachLine)
                                        continue
                                    else:
                                        checkPassing = 0
                                        eachLine = Replace.EachLine(self, codeArg, eachLine, variablesDict.items())
                                        print(eachLine)

            # -- Check if variables - classes - functions have been mixed -- #
            for output in recursFiles:
                if re.match(blockdirs, output):
                    continue
                else:
                    with open(output, "r") as readFile:
                        readF = readFile.readlines()
                        for eachLine in readF:
                            for value in variablesDict.values():
                                if value in eachLine:
                                    checkVarsMixed.append(value)
                
            # -- Remove duplicated key -- #
            checkListVarsMixed = list(dict.fromkeys(checkVarsMixed))
            
            for i in checkListVarsMixed:
                checkCountVarsMixed += 1
            for i in variablesDict.values():
                checkCountVarsValue += 1

            if checkCountVarsMixed == checkCountVarsValue:
                print("-> {0} variables - classes - functions replaced\n".format(checkCountVarsValue))
                if (self.remove.LineBreaks(oneFileArg, codeArg, outputArg) == 0):
                    return EXIT_SUCCESS
                else:
                    return EXIT_FAILURE
            else:
                return EXIT_FAILURE
Esempio n. 5
0
 def __init__(self):
     self.mixer              = Mixer()
     self.remove             = Remove()
     self.utils              = Utils()
     self.pythonExcludeWords = "exclude_python_words.txt"
     self.pythonIncludeWords = "include_python_words.txt"
Esempio n. 6
0
    def FilesName(self, codeArg, outputArg, mixerLevelArg, verboseArg):
        filesNameDict           = {}
        filesNameDictNoExt      = {}
        filesNameFound          = []
        filesNameFoundNoExt     = []
        filesNameMixed          = []
        checkFilesFound         = []
        countRecursFiles        = 0
        checkRenameInDir        = 0
        checkRenameInCode       = 0
        unix                    = False
        win                     = False
        currentPosition         = os.getcwd()
        utils                   = Utils()
        mixer                   = Mixer()
        remove                  = Remove()

        if codeArg == "python":
            detectFiles = "py"
            blockDir    = "__pycache__"
            blockFile   = "__init__"

            detectImport = r"\s*from\s+|\s*import\s+"
    
        recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, utils.Platform(), detectFiles), recursive=True)]

        for number in recursFiles:
                countRecursFiles += 1

        for file in recursFiles:
            if blockDir in file or blockFile in file:
                continue
            else:
                if "\"" in file:
                    parseFilePath = file.split("\"")
                    win = True
                else:
                    parseFilePath = file.split("/")
                    unix = True

                checkFilesFound.append(file)

                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                filesNameDict[parseFilePath[-1]] = mixer + ".py" 
                filesNameDictNoExt[parseFilePath[-1].replace(".py", "")] = mixer
                
                filesNameFound.append(parseFilePath[-1])
                filesNameMixed.append(mixer + ".py")

                removeExt = parseFilePath[-1].replace(".py","")
                filesNameFoundNoExt.append(removeExt)
            
        # -- Diplay all files found with their mixed values if verbose arg is actived -- #
        if verboseArg:
            print("\n[+] Files name found with their mixed values :\n")
            for key, value in filesNameDict.items():
                print("-> {0} : {1}".format(key, value))
        
        print("\n[+] Running replace files name in {0} file(s)...\n".format(countRecursFiles))
        
        # -- Replace all files name to random strings with length defined -- #
        with tqdm.tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                pbar.update(1)
                if blockDir in file:
                    continue
                else:
                    # -- Rename all files in python code -- #
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            try:
                                for fileName in filesNameFound:
                                   for fileNameNoExt in filesNameFoundNoExt:
                                        if fileName in eachLine or fileNameNoExt in eachLine:
                                            if not ".py" in eachLine:
                                                if re.match(detectImport, eachLine):
                                                    eachLine = Replace.EachLine(self, codeArg, eachLine, filesNameDictNoExt.items(), True)
                                                    print(eachLine)
                                                    raise BreakLoop
                                                else:
                                                    continue
                                            else: 
                                                eachLine = Replace.EachLine(self, codeArg, eachLine, filesNameDict.items(), True)
                                                print(eachLine)
                                                raise BreakLoop
                                        else:
                                            continue
                                print(eachLine) 
                            except BreakLoop:
                                continue

                    # -- Rename all files in their directories -- #
                    if "\"" in file:
                        parseFilePath = file.split("\"")
                        win = True
                    else:
                        parseFilePath = file.split("/")
                        unix = True

                    for key, value in filesNameDict.items():        
                        if key == parseFilePath[-1]:
                            parseFilePath.remove(parseFilePath[-1])
                            if unix == True:
                                parseFilePathToMove = "/".join(parseFilePath)
                            else:
                                parseFilePathToMove = "\"".join(parseFilePath)
                            os.chdir(parseFilePathToMove) # Move in directory to rename python file
                            os.rename(key, value)
                        else:
                            continue
                    os.chdir(currentPosition) # Return to old position   

        # -- Check if all files name are been replaced to random strings with length defined -- #    
        for i in checkFilesFound:
            i.replace(".py", "")

        # -- Check for file(s) name -- #
        for file in recursFiles:
            if blockDir in file or blockFile in file:
                continue
            else:
                for i in checkFilesFound:
                    if i in file:
                        checkFilesFound.remove(i)
                        continue

        # -- Check for code if file(s) name -- #
        if checkFilesFound != []:
            for file in recursFiles:
                if blockDir in file or blockFile in file:
                    continue
                else:
                    with open(file, "r") as inputFile:
                        for line in inputFile:
                            for i in checkFilesFound:
                                if i in line:
                                    checkFilesFound.remove(i)
                                    continue

        if checkFilesFound == []:
            if (remove.Backslashes(codeArg, outputArg) == 0):    
                return EXIT_SUCCESS        
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE
Esempio n. 7
0
def main():
    if sys.version_info[0] != 3:
        print(ERROR_COLOUR + "[-] Intensio-Obfuscator only support Python 3.x")
        sys.exit(0)

    if sys.platform != "win32" and sys.platform != "linux":
        print(ERROR_COLOUR + "[-] This tool support [windows - Linux] only !")
        sys.exit(0)

    args = Args()
    utils = Utils()

    if len(sys.argv) > 1 and len(sys.argv) <= 13:
        pass
    else:
        print(ERROR_COLOUR + "[-] Incorrect number of arguments\n")
        args.GetArgHelp()
        sys.exit(ERROR_BAD_ARGUMENTS)

    if args.GetArgsValue().input:
        if args.GetArgsValue().output:
            if args.GetArgsValue().mixerlevel:
                if re.match(r"^lower$|^medium$|^high$",
                            args.GetArgsValue().mixerlevel):
                    if not args.GetArgsValue().paddingscript and not args.GetArgsValue().replacetostr \
                        and not args.GetArgsValue().replacefilename and not args.GetArgsValue().replacetohex:
                        print(
                            ERROR_COLOUR +
                            "\n[-] Need at least one argument [-rts] - [-ps] - [-rfn] - [-rth]"
                        )
                        sys.exit(ERROR_BAD_ARGUMENTS)
                else:
                    print(
                        ERROR_COLOUR +
                        "[-] Incorrect level of mixerlevel, [lower - medium - high] only supported\n"
                    )
                    sys.exit(ERROR_INVALID_PARAMETER)
            else:
                print(ERROR_COLOUR +
                      "[-] Mixerlevel [-m, --mixerlevel] argument missing\n")
                sys.exit(ERROR_BAD_ARGUMENTS)
        else:
            print(ERROR_COLOUR +
                  "[-] Output [-o, --output] argument missing\n")
            sys.exit(ERROR_BAD_ARGUMENTS)
    else:
        print(ERROR_COLOUR + "[-] Input [-i, --input] argument missing\n")
        sys.exit(ERROR_BAD_ARGUMENTS)

    for line in INTENSIO_BANNER.split("\n"):
        time.sleep(0.05)
        print(BANNER_COLOUR + line)

    # -- Analysis and set up of the work environment -- #
    print(
        SECTION_COLOUR +
        "\n\n*********************** [ Analyze and setup environment ] ************************\n"
    )
    analyzeData = Analyze()
    analyseDataInEnv = analyzeData.InputAvailable(
        inputArg=args.GetArgsValue().input,
        verboseArg=args.GetArgsValue().verbose)
    if analyseDataInEnv == EXIT_SUCCESS:
        print("\n[+] Analyze input argument '{0}' -> ".format(
            args.GetArgsValue().input) + SUCESS_COLOUR + "Successful")
    else:
        print("[-] Analyze input '{0}' -> ".format(args.GetArgsValue().input) +
              FAILED_COLOUR + "failed\n")
        sys.exit(ERROR_INVALID_FUNCTION)

    analyseDataOutEnv = analyzeData.OutputAvailable(
        inputArg=args.GetArgsValue().input,
        outputArg=args.GetArgsValue().output,
        verboseArg=args.GetArgsValue().verbose)
    if analyseDataOutEnv == EXIT_SUCCESS:
        print("\n[+] Analyze and setup output argument environment '{0}' -> " \
                .format(args.GetArgsValue().output) + SUCESS_COLOUR + "Successful")
    else:
        print(
            "[-] Analyze output '{0}' -> ".format(args.GetArgsValue().output) +
            FAILED_COLOUR + "failed\n")
        sys.exit(ERROR_INVALID_FUNCTION)

    # -- Obfuscation process -- #
    print(
        SECTION_COLOUR +
        "\n\n************************ [ Obfuscation remove comment ] *************************\n"
    )
    removeData = Remove()
    removeCommentsData = removeData.Comments(
        outputArg=args.GetArgsValue().output,
        verboseArg=args.GetArgsValue().verbose)
    if removeCommentsData == EXIT_SUCCESS:
        print("[+] Obfuscation remove comments -> " + SUCESS_COLOUR +
              "Successful")
    else:
        print("\n[-] Obfuscation remove comments -> " + FAILED_COLOUR +
              "Failed")
        if not args.GetArgsValue().verbose:
            print("\n[!] Retry with [-v, --verbose] parameter")

    print(
        SECTION_COLOUR +
        "\n\n*********************** [ Obfuscation remove line space ] ***********************\n"
    )
    if removeData:
        pass
    else:
        removeData = Remove()

    removeLinesSpacesData = removeData.LinesSpaces(
        outputArg=args.GetArgsValue().output,
        verboseArg=args.GetArgsValue().verbose)

    if removeLinesSpacesData == EXIT_SUCCESS:
        print("[+] Obfuscation remove lines spaces -> " + SUCESS_COLOUR +
              "Successful")
    else:
        print("\n[-] Obfuscation remove lines spaces -> " + FAILED_COLOUR +
              "Failed")
        if not args.GetArgsValue().verbose:
            print("\n[!] Retry with [-v, --verbose] parameter")

    # -- If empty class (avert to generate an error) -- #
    print(
        SECTION_COLOUR +
        "\n\n*********************** [ Correction padding empty class ] **********************\n"
    )
    paddingData = Padding()
    paddingDataEmptyClass = paddingData.EmptyClasses(
        outputArg=args.GetArgsValue().output,
        mixerLevelArg=args.GetArgsValue().mixerlevel,
        verboseArg=args.GetArgsValue().verbose)
    if paddingDataEmptyClass == EXIT_SUCCESS:
        pass
    else:
        print("\n[-] Padding empty class -> " + FAILED_COLOUR + "Failed")
        if not args.GetArgsValue().verbose:
            print("\n[!] Retry with [-v, --verbose] parameter")

    # -- If empty functions (avert to generate an error) -- #
    print(
        SECTION_COLOUR +
        "\n\n********************** [ Correction padding empty function ] ********************\n"
    )
    if paddingData:
        pass
    else:
        paddingData = Padding()

    paddingDataEmptyFunc = paddingData.EmptyFunctions(
        outputArg=args.GetArgsValue().output,
        mixerLevelArg=args.GetArgsValue().mixerlevel,
        verboseArg=args.GetArgsValue().verbose)
    if paddingDataEmptyFunc == EXIT_SUCCESS:
        pass
    else:
        print("\n[-] Padding empty function -> " + FAILED_COLOUR + "Failed")
        if not args.GetArgsValue().verbose:
            print("\n[!] Retry with [-v, --verbose] parameter")

    print(
        SECTION_COLOUR +
        "\n\n**************** [ Obfuscation replace string to string mixed ] *****************\n"
    )
    if args.GetArgsValue().replacetostr:
        replaceData = Replace()

        replaceDataStrStr = replaceData.StringToString(
            outputArg=args.GetArgsValue().output,
            mixerLevelArg=args.GetArgsValue().mixerlevel,
            verboseArg=args.GetArgsValue().verbose)

        if replaceDataStrStr == EXIT_SUCCESS:
            print("[+] Obfuscation replace string to string mixed -> " +
                  SUCESS_COLOUR + "Successful")
        else:
            print("\n[-] Obfuscation replace string to string mixed -> " +
                  FAILED_COLOUR + "Failed")
            if not args.GetArgsValue().verbose:
                print(
                    "\n[!] Retry with [-v, --verbose] parameter for more informations"
                )
    else:
        print("[!] Obfuscation [ replace string to string ] mixed no asked !")

    print(
        SECTION_COLOUR +
        "\n\n********************* [ Obfuscation adding padding script ] *********************\n"
    )
    if args.GetArgsValue().paddingscript:
        if paddingData:
            pass
        else:
            paddingData = Padding()

        paddingDataGarbage = paddingData.AddRandomScripts(
            outputArg=args.GetArgsValue().output,
            mixerLevelArg=args.GetArgsValue().mixerlevel,
            verboseArg=args.GetArgsValue().verbose)
        if paddingDataGarbage == EXIT_SUCCESS:
            print("[+] Obfuscation padding script -> " + SUCESS_COLOUR +
                  "Successful")
        else:
            print("\n[-] Obfuscation padding script -> " + FAILED_COLOUR +
                  "Failed")
            if not args.GetArgsValue().verbose:
                print(
                    "\n[!] Retry with [-v, --verbose] parameter for more informations"
                )
    else:
        print("[!] Obfuscation [ padding script ] no asked !")

    print(
        SECTION_COLOUR +
        "\n\n********************** [ Obfuscation replace file name ] ************************\n"
    )
    if args.GetArgsValue().replacefilename:
        if args.GetArgsValue().replacetostr:
            pass
        else:
            replaceData = Replace()

        replaceDataStrFname = replaceData.FilesName(
            outputArg=args.GetArgsValue().output,
            mixerLevelArg=args.GetArgsValue().mixerlevel,
            verboseArg=args.GetArgsValue().verbose)
        if replaceDataStrFname == EXIT_SUCCESS:
            print("\n[+] Obfuscation replace file name -> " + SUCESS_COLOUR +
                  "Successful")
        else:
            print("\n[-] Obfuscation replace file name -> " + FAILED_COLOUR +
                  "Failed")
            if not args.GetArgsValue().verbose:
                print(
                    "\n[!] Retry with [-v, --verbose] parameter for more informations"
                )
    else:
        print("[!] Obfuscation [ replace file name ] feature no asked !")

    print(
        SECTION_COLOUR +
        "\n\n******************** [ Obfuscation replace string to hex ] **********************\n"
    )
    if args.GetArgsValue().replacetohex:
        if args.GetArgsValue().replacetostr or args.GetArgsValue(
        ).replacefilename:
            pass
        else:
            replaceData = Replace()

        replaceDataStrHex = replaceData.StringsToHex(
            outputArg=args.GetArgsValue().output,
            mixerLevelArg=args.GetArgsValue().mixerlevel,
            verboseArg=args.GetArgsValue().verbose)
        if replaceDataStrHex == EXIT_SUCCESS:
            print("\n[+] Obfuscation replace string to hex -> " +
                  SUCESS_COLOUR + "Successful")
        else:
            print("\n[-] Obfuscation replace string to hex -> " +
                  FAILED_COLOUR + "Failed")
            if not args.GetArgsValue().verbose:
                print(
                    "\n[!] Retry with [-v, --verbose] parameter for more informations"
                )
    else:
        print("[!] Obfuscation [ replace string to hex ] feature no asked !")

    # -- Remove if python pyc file in output directory -- #
    print(
        SECTION_COLOUR +
        "\n\n*********************** [ Correction remove .pyc file ] *************************\n"
    )
    if removeData:
        pass
    else:
        removeData = Remove()

    removePycData = removeData.TrashFiles(
        outputArg=args.GetArgsValue().output,
        verboseArg=args.GetArgsValue().verbose,
    )
    if removePycData == EXIT_SUCCESS:
        pass
    else:
        print("\n[-] Remove .pyc file in {0} directory -> ".format(
            args.GetArgsValue().output) + FAILED_COLOUR + "Failed")
        if not args.GetArgsValue().verbose:
            print(
                "\n[!] Retry with [-v, --verbose] parameter for more informations"
            )
Esempio n. 8
0
class Replace:

    def __init__(self):
        self.mixer              = Mixer()
        self.remove             = Remove()
        self.utils              = Utils()
        self.pythonExcludeWords = "exclude/python/exclude_python_words.txt"
        self.pythonIncludeWords = "include/python/include_python_words.txt"


    def EachLine(self, codeArg, eachLine, Dict, forFilesName):
        getIndexLineList    = []
        returnLine          = []
        charValue           = []
        checkCharAfterWord  = 1
        wordSetter          = 0
        checkGetKey         = ""
        checkGetWord        = ""
        getLine             = ""
        breakLine           = ""

        if codeArg == "python":
            regReplace = r"\.|\:|\)|\(|\=|\[|\]|\{|\}|\,|\+|\s|\*|\-"

        # -- Get list of all letters in line -- #
        for indexLine, letterLine in enumerate(eachLine):
            getIndexLineList.append(letterLine)

        # -- Loop in each letter of line -- #
        for indexLine, letterLine in enumerate(eachLine):
            # -- Add in final line list all chars mixed -- #
            if charValue != []:
                for obfIndex, obfValue in enumerate(charValue):
                    if obfIndex == 0: # First letter in string mixed are already add in the final line
                        continue
                    returnLine.append(obfValue)
                charValue = []

                # -- If the variable is only a letter, check if the next character is specific so as not to replace it -- #
                if re.match(regReplace, letterLine):
                    returnLine.append(letterLine)

                # -- Count indexes of word to move after it --#
                countDeleteIndex = 0
                for i in getWord:
                    countDeleteIndex += 1
                wordSetter = countDeleteIndex - 2 # -2 Is to letter already append and the letter in progress
            else:
                # -- The index numbers of variable is decremented to add the mixed letters that be replaced -- #
                if wordSetter > 0:
                    wordSetter -= 1
                    continue
                else:
                    try:
                        # -- Loop in the dictionary with already mixed values-- #
                        for key, value in Dict:
                            for indexKey, letterKey in enumerate(key):
                                for letterValue in value:
                                    # -- Check if letter of word is equal to letter of key -- #
                                    if letterKey == letterLine:
                                        # -- Begin process to check -- #s
                                        if indexKey == 0:
                                            indexExplore = indexLine + len(key) # Place index position after the word

                                            # -- If indexError return to next loop -- #
                                            try:
                                                getIndexLineList[indexExplore]
                                            except IndexError: 
                                                continue
                                                
                                            # -- Check the char after and before the word -- #
                                            if re.match(regReplace, getIndexLineList[indexExplore]):
                                                indexExploreBefore  = indexLine - 1 # Index check if word finded is not into the other word
                                                indexExploreAfter   = indexLine + 2 # Index check char after the the char finded with regReplace regex
                                                
                                                if codeArg == "python":
                                                    try:
                                                        if not re.match(r"\w|\\", getIndexLineList[indexExploreBefore]):
                                                            # -- Check if it's 'from' and 'import' word key in line to avoid replace name of file if variable is identic name to file -- #
                                                            getLine = "".join(getIndexLineList)
                                                            if forFilesName == False:
                                                                if "import" in getLine:
                                                                    if "from" in getLine:
                                                                        # -- Cut the line from the current index and check if it is not there is the keyword "import" in the line -- #
                                                                        breakLine = getIndexLineList[:indexLine]
                                                                        breakLine = "".join(breakLine)
                                                                        if not "import" in breakLine:
                                                                            # -- It's file because only 'from'key word -- #
                                                                            checkCharAfterWord = 1
                                                                        else:
                                                                            checkCharAfterWord = 0
                                                                    else:
                                                                        checkCharAfterWord = 0
                                                                # -- Check if after char find by 'regReplace' variable there no is ' or " -- #
                                                                elif re.match(r"\"|\'", getIndexLineList[indexExploreAfter]):
                                                                    checkCharAfterWord = 1
                                                                else:
                                                                    checkCharAfterWord = 0
                                                            # -- Only for -rfn, --replacefilesname feature -- #
                                                            else:
                                                                checkCharAfterWord = 0
                                                        else:
                                                            checkCharAfterWord = 1
                                                    except IndexError:
                                                        checkCharAfterWord = 0
                                                        pass
                                            else:
                                                checkCharAfterWord = 1

                                            if checkCharAfterWord == 0:
                                                # -- Initialize vars -- #
                                                getCharAllInKey     = []
                                                getWord             = []

                                                indexExploreStart   = indexLine
                                                indexExploreEnd     = indexLine + len(key) - 1 # Remove -1, first letter is already increment

                                                # -- List contain all letters of key -- #
                                                for getLetterKey in key:
                                                    getCharAllInKey.append(getLetterKey)

                                                # -- Check if all letters of key is equal to all letters of word -- #
                                                for indexCheckLetter, checkLetter in enumerate(getIndexLineList):
                                                    if indexCheckLetter >= indexExploreStart and indexCheckLetter <= indexExploreEnd:
                                                        getWord.append(checkLetter)

                                                # -- Check if number of chars in key equal number of chars in word -- #
                                                if list(set(getCharAllInKey) - set(getWord)) == []:
                                                    checkGetWord    = "".join(getWord)
                                                    checkGetKey     = "".join(getCharAllInKey)

                                                    # -- Check if key == word -- #
                                                    if checkGetWord == checkGetKey:
                                                        for obfChar in value:
                                                            charValue.append(obfChar)

                                                        letterLine = letterValue
                                                        raise BreakLoop
                                                    else:
                                                        continue
                                                else:
                                                    continue
                                            else:
                                                continue
                                        else:
                                            continue
                                    else:
                                        continue

                        raise BreakLoop

                    except BreakLoop:
                        returnLine.append(letterLine)

        # -- Rewrite the line -- #
        returnLine = "".join(returnLine)
        return returnLine[:]
    
     
    def StringsToStrings(self, codeArg, outputArg, mixerLevelArg, verboseArg):
        variablesDict           = {}
        classesDict             = {}
        functionsDict           = {}
        includeDict             = {}
        allDict                 = {}
        checkWordsMixed         = []
        wordsExcluded           = []
        wordsExcludedFound      = []
        wordsIncludedFound      = []
        wordsIncludedNotFound   = []
        checkCountWordsMixed    = 0
        checkCountWordsValue    = 0
        checkQuotePassing       = 0
        numberReplaced          = 0
        countRecursFiles        = 0

        if codeArg == "python":
            detectFiles = "py"
            blockDir    = "__pycache__"
            blockFile   = "__init__"

            functionsDefined        = r"def\s(\w+)"                             # Functions
            classDefined            = r"class\s(\w+)"                           # Classes
            variablesErrorDefined   = r"except(\s+\w+\sas\s)(\w)"               # Error variables
            variablesLoopDefined    = r"for\s+([\w\s\,]+)(\s+in\s+)"            # Loop variables
            variablesDefined        = r"(^\w+|\w+)([\s|^\s]*=[\s|\w|\"|\'])"    # Variables
            
            quoteOfCommentariesMultipleLines    = r"^\s*[\"|\']{3}$"        # """ and ''' without before variables and if commentaries is over multiple lines
            quoteInRegex                        = r"\={1}\s*r[\"|\']{1}"    # If quote in regex
            quoteOfEndCommentariesMultipleLines = r"^\s*[\"|\']{3}\)?\.?"   # """ and ''' without before variables, if commentaries is over multiple lines and he finish by .format() funtion
            quoteIntoVariable                   = r".*\={1}\s*\w*\.?\w*[\(|\.]{1}[\"|\']{3}|.*\={1}\s*[\"|\']{3}" # """ and ''' with before variables

        recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, self.utils.Platform(), detectFiles), recursive=True)]

        # -- Replace variables/classes/functions to random strings with length defined -- #
        for file in recursFiles:
            if blockDir in file:
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        # -- Variables -- #     
                        search = re.search(variablesDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(1) not in variablesDict:
                                variablesDict[search.group(1)] = mixer
                        
                        # -- Error variables -- #
                        search = re.search(variablesErrorDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(2) not in variablesDict:
                                variablesDict[search.group(2)] = mixer
                        
                        # -- Loop variables -- #
                        search = re.search(variablesLoopDefined, eachLine)
                        if search != None:
                            if "," in search.group(1):
                                modifySearch = search.group(1).replace(",", " ")
                                modifySearch = modifySearch.split()
                                for i in modifySearch:
                                    if i not in variablesDict:
                                        mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                        variablesDict[i] = mixer 
                            else:
                                if search.group(1) not in variablesDict:
                                    mixer = self.mixer.GetStringMixer(mixerLevelArg)
                                    variablesDict[search.group(1)] = mixer
                        
                        # -- Functions -- #         
                        search = re.search(functionsDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(1) not in functionsDict:
                                if codeArg == "python":
                                    if not blockFile in search.group(1):
                                        functionsDict[search.group(1)] = mixer

                        # -- Classes -- #
                        search = re.search(classDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(1) not in classesDict:
                                classesDict[search.group(1)] = mixer

        # -- Remove excluded variables/classes/functions defined from 'exclude/python/exclude_python_words.txt' in dict -- #
        if os.path.exists(self.pythonExcludeWords) == True:
            with open(self.pythonExcludeWords, "r") as readFile:
                for word in readFile:
                    if "#" in word or word == "\n":
                        continue
                    else:
                        word = word.rstrip()    
                        wordsExcluded.append(word)
        else:
            print(ERROR_COLOUR + "[-] '{0}' file not found\n".format(self.pythonExcludeWords))
        
        for word in wordsExcluded:
            if word in variablesDict.keys():
                wordsExcludedFound.append(word)
                del variablesDict[word]
            if word in classesDict.keys():
                wordsExcludedFound.append(word)
                del classesDict[word]
            if word in functionsDict.keys():
                wordsExcludedFound.append(word)
                del functionsDict[word]

        # -- Include variables/classes/functions defined from 'include/python/include_python_words.txt' in dict -- #
        if os.path.exists(self.pythonIncludeWords) == True:
            with open(self.pythonIncludeWords, "r") as readFile:
                for word in readFile:
                    if "#" in word or word == "\n":
                        continue
                    else:
                        word = word.rstrip()
                        wordsIncludedFound.append(word)
        else:
            print(ERROR_COLOUR + "[-] '{0}' file not found\n".format(self.pythonIncludeWords))
        
        for word in wordsIncludedFound:
            if word not in variablesDict.keys() and word not in classesDict.keys() and word not in functionsDict.keys():
                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                includeDict[word] = mixer
                wordsIncludedNotFound.append(word)

        for file in recursFiles:
            if blockDir in file:
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:        
                        for word in wordsIncludedNotFound:
                            if word in eachLine:
                                wordsIncludedNotFound.remove(word)

        for word in wordsIncludedNotFound:
            if word in includeDict.keys():
                del includeDict[word]
        
        # -- Display variables/classes/functions found -- #
        if verboseArg:
            print("\n[+] Variables found :\n")

            if variablesDict == {}:
                print("-> No result")
            else:
                for key, value in variablesDict.items():
                    print("-> {0} : {1}".format(key, value))
            
            print("\n[+] Classes found :\n")
            
            if classesDict == {}:
                print("-> No result")
            else:
                for key, value in classesDict.items():
                    print("-> {0} : {1}".format(key, value))
            
            print("\n[+] Functions found :\n")

            if functionsDict == {}:
                print("-> No result")
            else:
                for key, value in functionsDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Include found :\n")

            if includeDict == {}:
                print("-> No result")
            else:
                for key, value in includeDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Exclude found :\n")

            if wordsExcludedFound == []:
                print("-> No result")
            else:
                for word in wordsExcludedFound:
                    print("-> {0} : excluded".format(word))

        # -- Merge all dicts -- #
        allDict = self.utils.DictMerge(allDict, variablesDict)
        allDict = self.utils.DictMerge(allDict, classesDict)
        allDict = self.utils.DictMerge(allDict, functionsDict)
        allDict = self.utils.DictMerge(allDict, includeDict)
        
        for number in recursFiles:
            countRecursFiles += 1

        # -- Change variables/classes/functions to mixed values -- #
        print("\n[+] Running replacement of variables/classes/functions in {0} file(s)...\n".format(countRecursFiles))

        with tqdm.tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                pbar.update(1)
                if blockDir in file:
                    continue
                else:
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            if not eachLine:
                                continue
                            else:
                                if codeArg == "python":
                                    # -- Check code into """ or ''' -- #
                                    if re.match(quoteIntoVariable, eachLine):
                                        checkQuotePassing += 1
                                        eachLine = Replace.EachLine(self, codeArg, eachLine, allDict.items(), False)
                                        print(eachLine)
                                        continue
                                    elif re.match(quoteOfCommentariesMultipleLines, eachLine) or re.match(quoteOfEndCommentariesMultipleLines, eachLine):
                                        checkQuotePassing += 1
                                        eachLine = Replace.EachLine(self, codeArg, eachLine, allDict.items(), False)
                                        print(eachLine)
                                        if checkQuotePassing == 2:
                                            checkQuotePassing = 0
                                        continue

                                    if checkQuotePassing == 1:
                                        print(eachLine)
                                        continue
                                    elif checkQuotePassing == 2:
                                        checkQuotePassing = 0
                                        continue
                                    else:
                                        eachLine = Replace.EachLine(self, codeArg, eachLine, allDict.items(), False)
                                        print(eachLine)
                                        continue
                            
        # -- Check if variables/classes/functions have been mixed -- #
        for file in recursFiles:
            if blockDir in file:
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        for value in allDict.values():
                            if value in eachLine:
                                checkWordsMixed.append(value)
            
        # -- Remove duplicated key -- #
        checkListWordsMixed = list(dict.fromkeys(checkWordsMixed))
        
        for i in checkListWordsMixed:
            checkCountWordsMixed += 1
        for i in allDict.values():
            checkCountWordsValue += 1

        if (self.remove.Backslashes(codeArg, outputArg) == 0):
            if checkCountWordsMixed == checkCountWordsValue:
                print("\n-> {0} variables/classes/functions replaced in {1} file(s)\n".format(checkCountWordsValue, countRecursFiles))
                return EXIT_SUCCESS
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE


    def StringsToHex(self, codeArg, outputArg, mixerLevelArg):
        getLetterLineList   = []
        countRecursFiles    = 0
        checkPrint          = 0
        checkHexError       = False
        checkPrintError     = False
        hexLine             = ""
        utils               = Utils()
        mixer               = Mixer()
        remove              = Remove()

        if codeArg == "python":
            detectFiles = "py"
            blockDir    = "__pycache__"

            detectExecFunc  = r"exec\(\w+\)"
            detectQuotes    = r"[\'|\"]{3}"

        recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, utils.Platform(), detectFiles), recursive=True)]

        for number in recursFiles:
                countRecursFiles += 1

        print("\n[+] Running replace all strings to their hexadecimal value in {0} file(s)...\n".format(countRecursFiles))

        # -- Replace all strings to their hexadecimal value -- #
        with tqdm.tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                checkPrint = 0 # initialize check print() func at the begining of each file
                pbar.update(1)
                if blockDir in file:
                    continue
                else:
                    # -- Add a new first random line and move the old first line to the second line to avoid replacing it -- #
                    with open(file, "r") as inputFile:
                        stringRandomMixer   = mixer.GetStringMixer(mixerLevelArg)
                        firstLine           = "{0}\n".format(stringRandomMixer)
                        line                = inputFile.readlines()

                        line.insert(0, firstLine)

                    with open(file, "w") as inputFile:
                        inputFile.writelines(line)

                    # -- Replace all lines-- #
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            if checkPrint == 0:
                                varMixer = mixer.GetStringMixer(mixerLevelArg)
                                print(varMixer + "=\"\"\"")
                                checkPrint = 1   
                            else:
                                getLetterLineList = [] # initialize list     
                                for letterLine in eachLine:
                                    letterToHex = "\\x" + str(letterLine.encode().hex())
                                    getLetterLineList.append(letterToHex) # Get list of all letters in line          
                                hexLine = "".join(getLetterLineList)
                                print(hexLine)

                    # -- Add exec funtions to interpret hex code in strings -- #
                    with open(file, "a") as inputFile:
                        inputFile.write("\"\"\"")
                        inputFile.write("\nexec({0})".format(varMixer))

        # -- Check if all lines are replaced of hexadecimal value -- #
        for file in recursFiles: 
            if blockDir in file:
                continue
            else:
                with open(file, "r") as inputFile:
                    for eachLine in inputFile:
                        if not eachLine:
                            continue
                        else:
                            if not "\\x" in eachLine:
                                if re.match(detectQuotes, eachLine):
                                    continue
                                elif re.match(detectExecFunc, eachLine):
                                    continue
                                else:
                                    checkError = True
                            else:
                                continue
            
        if (remove.Backslashes(codeArg, outputArg) == 0):
            if checkHexError == False:
                return EXIT_SUCCESS        
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE


    def FilesName(self, codeArg, outputArg, mixerLevelArg, verboseArg):
        filesNameDict           = {}
        filesNameDictNoExt      = {}
        filesNameFound          = []
        filesNameFoundNoExt     = []
        filesNameMixed          = []
        checkFilesFound         = []
        countRecursFiles        = 0
        checkRenameInDir        = 0
        checkRenameInCode       = 0
        unix                    = False
        win                     = False
        currentPosition         = os.getcwd()
        utils                   = Utils()
        mixer                   = Mixer()
        remove                  = Remove()

        if codeArg == "python":
            detectFiles = "py"
            blockDir    = "__pycache__"
            blockFile   = "__init__"

            detectImport = r"\s*from\s+|\s*import\s+"
    
        recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, utils.Platform(), detectFiles), recursive=True)]

        for number in recursFiles:
                countRecursFiles += 1

        for file in recursFiles:
            if blockDir in file or blockFile in file:
                continue
            else:
                if "\"" in file:
                    parseFilePath = file.split("\"")
                    win = True
                else:
                    parseFilePath = file.split("/")
                    unix = True

                checkFilesFound.append(file)

                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                filesNameDict[parseFilePath[-1]] = mixer + ".py" 
                filesNameDictNoExt[parseFilePath[-1].replace(".py", "")] = mixer
                
                filesNameFound.append(parseFilePath[-1])
                filesNameMixed.append(mixer + ".py")

                removeExt = parseFilePath[-1].replace(".py","")
                filesNameFoundNoExt.append(removeExt)
            
        # -- Diplay all files found with their mixed values if verbose arg is actived -- #
        if verboseArg:
            print("\n[+] Files name found with their mixed values :\n")
            for key, value in filesNameDict.items():
                print("-> {0} : {1}".format(key, value))
        
        print("\n[+] Running replace files name in {0} file(s)...\n".format(countRecursFiles))
        
        # -- Replace all files name to random strings with length defined -- #
        with tqdm.tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                pbar.update(1)
                if blockDir in file:
                    continue
                else:
                    # -- Rename all files in python code -- #
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            try:
                                for fileName in filesNameFound:
                                   for fileNameNoExt in filesNameFoundNoExt:
                                        if fileName in eachLine or fileNameNoExt in eachLine:
                                            if not ".py" in eachLine:
                                                if re.match(detectImport, eachLine):
                                                    eachLine = Replace.EachLine(self, codeArg, eachLine, filesNameDictNoExt.items(), True)
                                                    print(eachLine)
                                                    raise BreakLoop
                                                else:
                                                    continue
                                            else: 
                                                eachLine = Replace.EachLine(self, codeArg, eachLine, filesNameDict.items(), True)
                                                print(eachLine)
                                                raise BreakLoop
                                        else:
                                            continue
                                print(eachLine) 
                            except BreakLoop:
                                continue

                    # -- Rename all files in their directories -- #
                    if "\"" in file:
                        parseFilePath = file.split("\"")
                        win = True
                    else:
                        parseFilePath = file.split("/")
                        unix = True

                    for key, value in filesNameDict.items():        
                        if key == parseFilePath[-1]:
                            parseFilePath.remove(parseFilePath[-1])
                            if unix == True:
                                parseFilePathToMove = "/".join(parseFilePath)
                            else:
                                parseFilePathToMove = "\"".join(parseFilePath)
                            os.chdir(parseFilePathToMove) # Move in directory to rename python file
                            os.rename(key, value)
                        else:
                            continue
                    os.chdir(currentPosition) # Return to old position   

        # -- Check if all files name are been replaced to random strings with length defined -- #    
        for i in checkFilesFound:
            i.replace(".py", "")

        # -- Check for file(s) name -- #
        for file in recursFiles:
            if blockDir in file or blockFile in file:
                continue
            else:
                for i in checkFilesFound:
                    if i in file:
                        checkFilesFound.remove(i)
                        continue

        # -- Check for code if file(s) name -- #
        if checkFilesFound != []:
            for file in recursFiles:
                if blockDir in file or blockFile in file:
                    continue
                else:
                    with open(file, "r") as inputFile:
                        for line in inputFile:
                            for i in checkFilesFound:
                                if i in line:
                                    checkFilesFound.remove(i)
                                    continue

        if checkFilesFound == []:
            if (remove.Backslashes(codeArg, outputArg) == 0):    
                return EXIT_SUCCESS        
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE
Esempio n. 9
0
    def StringsToHex(self, codeArg, outputArg, mixerLevelArg):
        getLetterLineList   = []
        countRecursFiles    = 0
        checkPrint          = 0
        checkHexError       = False
        checkPrintError     = False
        hexLine             = ""
        utils               = Utils()
        mixer               = Mixer()
        remove              = Remove()

        if codeArg == "python":
            detectFiles = "py"
            blockDir    = "__pycache__"

            detectExecFunc  = r"exec\(\w+\)"
            detectQuotes    = r"[\'|\"]{3}"

        recursFiles = [f for f in glob.glob("{0}{1}**{1}*.{2}".format(outputArg, utils.Platform(), detectFiles), recursive=True)]

        for number in recursFiles:
                countRecursFiles += 1

        print("\n[+] Running replace all strings to their hexadecimal value in {0} file(s)...\n".format(countRecursFiles))

        # -- Replace all strings to their hexadecimal value -- #
        with tqdm.tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                checkPrint = 0 # initialize check print() func at the begining of each file
                pbar.update(1)
                if blockDir in file:
                    continue
                else:
                    # -- Add a new first random line and move the old first line to the second line to avoid replacing it -- #
                    with open(file, "r") as inputFile:
                        stringRandomMixer   = mixer.GetStringMixer(mixerLevelArg)
                        firstLine           = "{0}\n".format(stringRandomMixer)
                        line                = inputFile.readlines()

                        line.insert(0, firstLine)

                    with open(file, "w") as inputFile:
                        inputFile.writelines(line)

                    # -- Replace all lines-- #
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            if checkPrint == 0:
                                varMixer = mixer.GetStringMixer(mixerLevelArg)
                                print(varMixer + "=\"\"\"")
                                checkPrint = 1   
                            else:
                                getLetterLineList = [] # initialize list     
                                for letterLine in eachLine:
                                    letterToHex = "\\x" + str(letterLine.encode().hex())
                                    getLetterLineList.append(letterToHex) # Get list of all letters in line          
                                hexLine = "".join(getLetterLineList)
                                print(hexLine)

                    # -- Add exec funtions to interpret hex code in strings -- #
                    with open(file, "a") as inputFile:
                        inputFile.write("\"\"\"")
                        inputFile.write("\nexec({0})".format(varMixer))

        # -- Check if all lines are replaced of hexadecimal value -- #
        for file in recursFiles: 
            if blockDir in file:
                continue
            else:
                with open(file, "r") as inputFile:
                    for eachLine in inputFile:
                        if not eachLine:
                            continue
                        else:
                            if not "\\x" in eachLine:
                                if re.match(detectQuotes, eachLine):
                                    continue
                                elif re.match(detectExecFunc, eachLine):
                                    continue
                                else:
                                    checkError = True
                            else:
                                continue
            
        if (remove.Backslashes(codeArg, outputArg) == 0):
            if checkHexError == False:
                return EXIT_SUCCESS        
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE
Esempio n. 10
0
class Padding:
    def __init__(self):
        self.mixer = Mixer()
        self.remove = Remove()
        self.utils = Utils()

    def ScriptsGenerator(self, codeArg, mixerLevelArg):
        if mixerLevelArg == "lower":
            varRandom1 = self.mixer.GetStringMixer("lower")
            varRandom2 = self.mixer.GetStringMixer("lower")
            varRandom3 = self.mixer.GetStringMixer("lower")
            varRandom4 = self.mixer.GetStringMixer("lower")
            varRandom5 = self.mixer.GetStringMixer("lower")
            varRandom6 = self.mixer.GetStringMixer("lower")
            varRandom7 = self.mixer.GetStringMixer("lower")
            varRandom8 = self.mixer.GetStringMixer("lower")
            varRandom9 = self.mixer.GetStringMixer("lower")
            varRandom10 = self.mixer.GetStringMixer("lower")
            varRandom11 = self.mixer.GetStringMixer("lower")
            varRandom12 = self.mixer.GetStringMixer("lower")
        elif mixerLevelArg == "medium":
            varRandom1 = self.mixer.GetStringMixer("medium")
            varRandom2 = self.mixer.GetStringMixer("medium")
            varRandom3 = self.mixer.GetStringMixer("medium")
            varRandom4 = self.mixer.GetStringMixer("medium")
            varRandom5 = self.mixer.GetStringMixer("medium")
            varRandom6 = self.mixer.GetStringMixer("medium")
            varRandom7 = self.mixer.GetStringMixer("medium")
            varRandom8 = self.mixer.GetStringMixer("medium")
            varRandom9 = self.mixer.GetStringMixer("medium")
            varRandom10 = self.mixer.GetStringMixer("medium")
            varRandom11 = self.mixer.GetStringMixer("medium")
            varRandom12 = self.mixer.GetStringMixer("medium")
        elif mixerLevelArg == "high":
            varRandom1 = self.mixer.GetStringMixer("high")
            varRandom2 = self.mixer.GetStringMixer("high")
            varRandom3 = self.mixer.GetStringMixer("high")
            varRandom4 = self.mixer.GetStringMixer("high")
            varRandom5 = self.mixer.GetStringMixer("high")
            varRandom6 = self.mixer.GetStringMixer("high")
            varRandom7 = self.mixer.GetStringMixer("high")
            varRandom8 = self.mixer.GetStringMixer("high")
            varRandom9 = self.mixer.GetStringMixer("high")
            varRandom10 = self.mixer.GetStringMixer("high")
            varRandom11 = self.mixer.GetStringMixer("high")
            varRandom12 = self.mixer.GetStringMixer("high")

        # ---------- Python random scripts ---------- #
        if codeArg == "python":
            rand = random.randint(1, 5)

            # -- script 1 -- #
            if rand == 1:
                scriptAssPadding1 = textwrap.dedent("""
                                                    {0} = '{5}'
                                                    {1} = '{6}'
                                                    {2} = '{7}'
                                                    {3} = '{8}'
                                                    {4} = '{9}'
                                                    if {0} in {1}:
                                                        {0} = {4}
                                                        if {1} in {2}:
                                                            {1} = {3}
                                                    elif {1} in {0}:
                                                        {2} = {1}
                                                        if {2} in {1}:
                                                            {1} = {4}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, \
                                                                varRandom6, varRandom7, varRandom8, varRandom9, varRandom10)
                return scriptAssPadding1

            # -- script 2 -- #
            elif rand == 2:
                scriptAssPadding2 = textwrap.dedent("""
                                                    {0} = '{4}'
                                                    {1} = '{5}'
                                                    if {0} != {1}:
                                                        {2} = '{6}'
                                                        {3} = '{7}'
                                                        {3} = {2}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, \
                                                                varRandom6, varRandom7, varRandom8)
                return scriptAssPadding2

            # -- script 3 -- #
            elif rand == 3:
                scriptAssPadding3 = textwrap.dedent("""
                                                    {0} = '{6}'
                                                    {1} = '{7}'
                                                    {2} = '{8}'
                                                    {3} = '{9}'
                                                    {4} = '{10}'
                                                    {5} = '{11}'
                                                    if {0} != {3}:
                                                        {1} = {2}
                                                        for {5} in {3}:
                                                            if {5} != {2}:
                                                                {1} = {1}
                                                            else:
                                                                {4} = {0}
                                                    else:
                                                        {2} = {0}
                                                        {0} = {4}
                                                        if {2} == {0}:
                                                            for {5} in {0}:
                                                                if {5} == {2}:
                                                                    {2} = {0}
                                                                else:
                                                                    {2} = {4}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, varRandom5, varRandom6, \
                                                                varRandom7, varRandom8, varRandom9, varRandom10, varRandom11, varRandom12)
                return scriptAssPadding3

            # -- script 4 -- #
            elif rand == 4:
                scriptAssPadding4 = textwrap.dedent("""
                                                    {0} = '{4}'
                                                    {1} = '{5}'
                                                    {3} = '{7}'
                                                    if {0} == {1}:
                                                        {2} = '{6}'
                                                        {2} = {0}
                                                    else:
                                                        {2} = '{6}'
                                                        {2} = {3}
                                                    """).format(varRandom1, varRandom2, varRandom3, varRandom4, \
                                                                varRandom5, varRandom6, varRandom7, varRandom8)
                return scriptAssPadding4

            # -- script 5 -- #
            elif rand == 5:
                scriptAssPadding5 = textwrap.dedent("""
                                                    {0} = '{6}'
                                                    {1} = '{7}'
                                                    {2} = '{8}'
                                                    {3} = '{9}'
                                                    {4} = '{10}'
                                                    {5} = '{11}'
                                                    if {2} == {3}:
                                                        for {5} in {4}:
                                                            if {5} == {3}:
                                                                {4} = {0}
                                                            else:
                                                                {3} = {1}
                                                    """).format(varRandom1, varRandom2, varRandom3, \
                                                        varRandom4, varRandom5, varRandom6, \
                                                        varRandom7, varRandom8, varRandom9, \
                                                        varRandom10, varRandom11, varRandom12)
                return scriptAssPadding5

    def AddScripts(self, codeArg, outputArg, mixerLevelArg):
        countScriptsAdded = 0
        countLineAdded = 0
        countLine = 0
        checkLine = 0
        checkPassing = 0
        countRecursFiles = 0

        if codeArg == "python":
            inputExt = "py"
            blockDirs = r"__pycache__"

        recursFiles = [
            f for f in glob.glob("{0}{1}**{1}*.{2}".format(
                outputArg, self.utils.Platform(), inputExt),
                                 recursive=True)
        ]

        # -- Count the number of lines that will be checked before filling -- #
        for output in recursFiles:
            if re.match(blockDirs, output):
                continue
            else:
                with open(output, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        if not eachLine:
                            continue
                        countLine += 1

        for number in recursFiles:
            countRecursFiles += 1

        print("\n[+] Running adding of random scripts in {0} file(s)...\n".
              format(countRecursFiles))

        # -- Padding scripts added -- #
        with tqdm(total=countRecursFiles) as pbar:
            for output in recursFiles:
                pbar.update(1)
                if re.match(blockDirs, output):
                    continue
                else:
                    with fileinput.input(output, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            print(eachLine)
                            if eachLine == "\n":
                                continue
                            else:
                                if codeArg == "python":
                                    spaces = len(eachLine) - len(
                                        eachLine.lstrip())  # Check line indent
                                    noAddScript = r"(^[\#]+.*)|(\@|\s+\@)|(\s+return)|(\s+#\s{1,10}\w+)"
                                    addIndentScript = r".*\:{1}\s"
                                    checkAddIndentScript = r".*\:{1}\s\w+"

                                    # -- Check if ',' char or '\' char,in end line -- #
                                    listCheckEndLine = []

                                    for i in eachLine:
                                        listCheckEndLine.append(i)

                                    if "," in listCheckEndLine[
                                            -2] or "\\" in listCheckEndLine[-2]:
                                        continue

                                    # -- Check code between """ or ''' -- #
                                    if '\"\"\"' in eachLine or "\'\'\'" in eachLine:
                                        checkPassing += 1

                                    if checkPassing == 1:  # Loop until the next """ or '''
                                        continue
                                    else:
                                        checkPassing = 0

                                if re.match(noAddScript, eachLine) is not None:
                                    continue
                                elif re.match(addIndentScript,
                                              eachLine) is not None:
                                    if re.match(checkAddIndentScript,
                                                eachLine) is not None:
                                        continue
                                    else:
                                        if spaces == 0:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "    "))
                                            countScriptsAdded += 1
                                        elif spaces == 4:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "        "))
                                            countScriptsAdded += 1
                                        elif spaces == 8:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "            "))
                                            countScriptsAdded += 1
                                        elif spaces == 12:
                                            print(
                                                textwrap.indent(
                                                    Padding.ScriptsGenerator(
                                                        self, codeArg,
                                                        mixerLevelArg),
                                                    "                "))
                                            countScriptsAdded += 1
                                        else:
                                            continue
                                else:
                                    if spaces == 0:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg), ""))
                                        countScriptsAdded += 1
                                    elif spaces == 4:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg), "    "))
                                        countScriptsAdded += 1
                                    elif spaces == 8:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg),
                                                "        "))
                                        countScriptsAdded += 1
                                    elif spaces == 12:
                                        print(
                                            textwrap.indent(
                                                Padding.ScriptsGenerator(
                                                    self, codeArg,
                                                    mixerLevelArg),
                                                "            "))
                                        countScriptsAdded += 1
                                    else:
                                        continue

        # -- Check padding has added in output script -- #
        for output in recursFiles:
            if re.match(blockDirs, output):
                continue
            else:
                with open(output, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        if not eachLine:
                            continue
                        checkLine += 1

        countLineAdded = checkLine - countLine

        if (self.remove.LineBreaks(codeArg, outputArg) == 0):
            if checkLine > countLine:
                print("\n-> {0} scripts added in {1} file(s)\n".format(
                    countScriptsAdded, countRecursFiles))
                print("-> {0} lines added in {1} file(s)\n".format(
                    countLineAdded, countRecursFiles))
                return EXIT_SUCCESS

            else:
                return EXIT_FAILURE
        else:
            EXIT_FAILURE
def main():
    if sys.version_info[0] != 3:
        print(ERROR_COLOUR + "[-] Intensio-Obfuscator only support Python 3.x")
        sys.exit(0)

    if sys.platform != "win32" and sys.platform != "linux":
        print(ERROR_COLOUR + "[-] This tool support [windows - Linux] only !")
        sys.exit(0)

    try:
        from core.utils.intensio_design import INTENSIO_BANNER
        from core.utils.intensio_utils import Utils
        from core.utils.intensio_usage import Args
        from core.utils.intensio_error  import EXIT_SUCCESS, ERROR_BAD_ENVIRONMENT, ERROR_INVALID_PARAMETER, \
                                                ERROR_BAD_ARGUMENTS, ERROR_INVALID_FUNCTION, ERROR_FILE_NOT_FOUND
        from core.obfuscation.intensio_replace import Replace
        from core.obfuscation.intensio_padding import Padding
        from core.obfuscation.intensio_analyze import Analyze
        from core.obfuscation.intensio_remove import Remove
    except ImportError as e:
        print(ERROR_COLOUR + "[-] {0}\n".format(e))
        sys.exit(0)

    args = Args()
    utils = Utils()

    if len(sys.argv) > 1 and len(sys.argv) <= 16:
        pass
    else:
        print(ERROR_COLOUR + "[-] Incorrect number of arguments\n")
        args.GetArgHelp()
        sys.exit(ERROR_BAD_ARGUMENTS)

    if args.GetArgsValue().input:
        if args.GetArgsValue().output:
            if args.GetArgsValue().code:
                if args.GetArgsValue().code == "python":
                    if args.GetArgsValue().mixerlevel:
                        if re.match(r"^lower$|^medium$|^high$",
                                    args.GetArgsValue().mixerlevel):
                            if not args.GetArgsValue().paddingscripts and not args.GetArgsValue().replacetostr \
                                and not args.GetArgsValue().removecommentaries and not args.GetArgsValue().removeprint \
                                and not args.GetArgsValue().replacetohex and not args.GetArgsValue().replacefilesname:
                                print(
                                    ERROR_COLOUR +
                                    "\n[-] Need at least one argument [-rts --replacetostr] or [-ps --paddingscripts] \
                                    or [-rc --removecommentaries] or [-rp --removeprint] or [-rth --replacetohex] or [-rfn, --replacefilesname]"
                                )
                                sys.exit(ERROR_BAD_ARGUMENTS)
                        else:
                            print(
                                ERROR_COLOUR +
                                "[-] Incorrect level of mixerlevel, [lower - medium - high] only supported\n"
                            )
                            sys.exit(ERROR_INVALID_PARAMETER)
                    else:
                        print(
                            ERROR_COLOUR +
                            "[-] Mixerlevel [-m --mixerlevel] argument missing\n"
                        )
                        sys.exit(ERROR_BAD_ARGUMENTS)
                else:
                    print(
                        ERROR_COLOUR +
                        "[-] '{0}' Incorrect code argument, [python] only supported\n"
                        .format(args.GetArgsValue().Code))
                    sys.exit(ERROR_INVALID_PARAMETER)
            else:
                print(ERROR_COLOUR + "[-] Code [-c --code] argument missing\n")
                sys.exit(ERROR_BAD_ARGUMENTS)
        else:
            print(ERROR_COLOUR + "[-] Output [-o --output] argument missing\n")
            sys.exit(ERROR_BAD_ARGUMENTS)
    else:
        print(ERROR_COLOUR + "[-] Input [-i --input] argument missing\n")
        sys.exit(ERROR_BAD_ARGUMENTS)

    for line in INTENSIO_BANNER.split("\n"):
        time.sleep(0.05)
        print(BANNER_COLOUR + line)

    # -- Analysis and set up of the work environment -- #
    print(
        SECTION_COLOUR +
        "\n\n*********************** [ Analyze and setup environment ] ************************\n"
    )
    analyzeData = Analyze()

    if (analyzeData.InputAvailable(
            args.GetArgsValue().input,
            args.GetArgsValue().code,
            args.GetArgsValue().verbose) == EXIT_SUCCESS):
        print("\n[+] Analyze input argument '{0}' -> ".format(
            args.GetArgsValue().input) + SUCESS_COLOUR + "Successful")
    else:
        print("[-] Analyze input '{0}' -> ".format(args.GetArgsValue().input) +
              FAILED_COLOUR + "failed\n")
        sys.exit(ERROR_INVALID_FUNCTION)

    if (analyzeData.OutputAvailable(
            args.GetArgsValue().input,
            args.GetArgsValue().code,
            args.GetArgsValue().output,
            args.GetArgsValue().verbose) == EXIT_SUCCESS):
        print("\n[+] Analyze and setup output argument environment '{0}' -> ".
              format(args.GetArgsValue().output) + SUCESS_COLOUR +
              "Successful")
    else:
        print(
            "[-] Analyze output '{0}' -> ".format(args.GetArgsValue().output) +
            FAILED_COLOUR + "failed\n")
        sys.exit(ERROR_INVALID_FUNCTION)

    # -- Obfuscation process -- #
    print(
        SECTION_COLOUR +
        "\n\n********************** [ Obfuscation remove commentaries ] **********************\n"
    )
    if args.GetArgsValue().removecommentaries:
        removeData = Remove()

        if (removeData.Commentaries(
                args.GetArgsValue().code,
                args.GetArgsValue().output) == EXIT_SUCCESS):
            print("[+] Obfuscation remove commentaries -> " + SUCESS_COLOUR +
                  "Successful")
        else:
            print("\n[-] Obfuscation remove commentaries -> " + FAILED_COLOUR +
                  "Failed")
    else:
        print("[!] Obfuscation remove commentaries no asked !")

    print(
        SECTION_COLOUR +
        "\n\n*************** [ Obfuscation replace strings to strings mixed ] ****************\n"
    )
    if args.GetArgsValue().replacetostr:
        replaceData = Replace()

        if (replaceData.StringsToStrings(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel,
                args.GetArgsValue().verbose) == EXIT_SUCCESS):
            print("[+] Obfuscation replace strings to strings mixed -> " +
                  SUCESS_COLOUR + "Successful")
        else:
            print("\n[-] Obfuscation replace strings to strings mixed -> " +
                  FAILED_COLOUR + "Failed")
    else:
        print("[!] Obfuscation replace strings to strings mixed no asked !")

    print(
        SECTION_COLOUR +
        "\n\n************************ [ Obfuscation padding scripts ] ************************\n"
    )
    if args.GetArgsValue().paddingscripts:
        paddingData = Padding()

        if (paddingData.AddRandomScripts(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel) == EXIT_SUCCESS):
            print("[+] Obfuscation padding random scripts -> " +
                  SUCESS_COLOUR + "Successful")
        else:
            print("\n[-] Obfuscation padding random scripts -> " +
                  FAILED_COLOUR + "Failed")
    else:
        print("[!] Obfuscation add random scripts no asked !")

    print(
        SECTION_COLOUR +
        "\n\n************************* [ Obfuscation remove print ] **************************\n"
    )
    if args.GetArgsValue().removeprint:

        if (removeData.PrintFunctions(
                args.GetArgsValue().code,
                args.GetArgsValue().output) == EXIT_SUCCESS):
            print("[+] Obfuscation remove print functions -> " +
                  SUCESS_COLOUR + "Successful")
        else:
            print("\n[-] Obfuscation remove print functions -> " +
                  FAILED_COLOUR + "Failed")
    else:
        print("[!] Obfuscation remove print functions no asked !")

    print(
        SECTION_COLOUR +
        "\n\n********************** [ Obfuscation replace files name ] ***********************\n"
    )
    if args.GetArgsValue().replacefilesname:
        if args.GetArgsValue().replacetostr:
            pass
        else:
            replaceData = Replace()

        if (replaceData.FilesName(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel,
                args.GetArgsValue().verbose) == EXIT_SUCCESS):
            print("\n[+] Obfuscation replace files name -> " + SUCESS_COLOUR +
                  "Successful")
        else:
            print("\n[-] Obfuscation replace files name -> " + FAILED_COLOUR +
                  "Failed")
    else:
        print("[!] Obfuscation replace files name no asked !")

    print(
        SECTION_COLOUR +
        "\n\n******************** [ Obfuscation replace strings to hex ] *********************\n"
    )
    if args.GetArgsValue().replacetohex:
        if args.GetArgsValue().replacetostr or args.GetArgsValue(
        ).replacefilesname:
            pass
        else:
            replaceData = Replace()

        if (replaceData.StringsToHex(
                args.GetArgsValue().code,
                args.GetArgsValue().output,
                args.GetArgsValue().mixerlevel) == EXIT_SUCCESS):
            print("\n[+] Obfuscation replace strings to hex -> " +
                  SUCESS_COLOUR + "Successful\n")
        else:
            print("\n[-] Obfuscation replace strings to hex -> " +
                  FAILED_COLOUR + "Failed\n")
    else:
        print("[!] Obfuscation replace strings to hex no asked !\n")

    # -- Remove if python pyc file(s) in output directory -- #
    if (removeData.TrashFiles(args.GetArgsValue().code,
                              args.GetArgsValue().output) >= 0):
        pass
    else:
        print(
            SECTION_COLOUR +
            "\n**************************** [ Remove pyc files ] *****************************\n"
        )
        print("\n[-] Remove .pyc files in {0} directory -> " + FAILED_COLOUR +
              "Failed\n".format(args.GetArgsValue().output))
Esempio n. 12
0
class ReplaceWords:
    def __init__(self):
        self.mixer = Mixer()
        self.remove = Remove()
        self.utils = Utils()
        self.pythonExcludeWords = "exclude/python/exclude_python_words.txt"
        self.pythonIncludeWords = "include/python/include_python_words.txt"

    def EachLine(self, codeArg, eachLine, Dict):
        getIndexLineList = []
        returnLine = []
        charValue = []
        checkCharAfterWord = 1
        wordSetter = 0
        checkGetKey = ""
        checkGetWord = ""
        getLine = ""
        breakLine = ""

        if codeArg == "python":
            regReplace = r"(\.)|(:)|(\))|(\()|(=)|(\[)|(\])|({)|(})|(,)|(\+)|(\s)|(\*)|(\+)|(\-)"

        # -- Get list of all letters in line -- #
        for indexLine, letterLine in enumerate(eachLine):
            getIndexLineList.append(letterLine)

        # -- Loop in each letter of line -- #
        for indexLine, letterLine in enumerate(eachLine):
            # -- Add in final line list all chars mixed -- #
            if charValue != []:
                for obfIndex, obfValue in enumerate(charValue):
                    if obfIndex == 0:  # First letter in string mixed are already add in the final line
                        continue
                    returnLine.append(obfValue)
                charValue = []

                # -- If the variable is only a letter, check if the next character is specific so as not to replace it -- #
                if re.match(regReplace, letterLine):
                    returnLine.append(letterLine)

                # -- Count indexes of word to move after it --#
                countDeleteIndex = 0
                for i in getWord:
                    countDeleteIndex += 1
                wordSetter = countDeleteIndex - 2  # -2 Is to letter already append and the letter in progress
            else:
                # -- The index numbers of variable is decremented to add the mixed letters that be replaced -- #
                if wordSetter > 0:
                    wordSetter -= 1
                    continue
                else:
                    try:
                        # -- Loop in the dictionary with already mixed values-- #
                        for key, value in Dict:
                            for indexKey, letterKey in enumerate(key):
                                for letterValue in value:
                                    # -- Check if letter of word is equal to letter of key -- #
                                    if letterKey == letterLine:
                                        # -- Begin process to check  -- #
                                        if indexKey == 0:
                                            # -- Place index position after the word -- #
                                            indexExplore = indexLine + len(key)

                                            # -- If indexError return to next loop -- #
                                            try:
                                                getIndexLineList[indexExplore]
                                            except IndexError:
                                                continue

                                            # -- Check the char after the word -- #
                                            if re.match(
                                                    regReplace,
                                                    getIndexLineList[
                                                        indexExplore]):
                                                # -- Check word finded is not into the other word -- #
                                                indexExploreBefore = indexLine - 1
                                                if not re.match(
                                                        r"\w|\\",
                                                        getIndexLineList[
                                                            indexExploreBefore]
                                                ):
                                                    if codeArg == "python":
                                                        # -- Check if it's 'from' and 'import' word key in line to avoid replace name of file if variable is identic name to file -- #
                                                        getLine = "".join(
                                                            getIndexLineList)
                                                        if "import" in getLine:
                                                            if "from" in getLine:
                                                                # -- Cut the line from the current index and check if it is not there is the keyword "import" in the line -- #
                                                                breakLine = getIndexLineList[:
                                                                                             indexLine]
                                                                breakLine = "".join(
                                                                    breakLine)
                                                                if not "import" in breakLine:
                                                                    # -- It's file because only 'from'key word -- #
                                                                    checkCharAfterWord = 1
                                                                else:
                                                                    checkCharAfterWord = 0
                                                            else:
                                                                checkCharAfterWord = 0
                                                        else:
                                                            checkCharAfterWord = 0
                                                else:
                                                    checkCharAfterWord = 1
                                            else:
                                                checkCharAfterWord = 1

                                            if checkCharAfterWord == 0:
                                                # -- Initialize vars -- #
                                                getCharAllInKey = []
                                                getWord = []

                                                indexExploreStart = indexLine
                                                indexExploreEnd = indexLine + len(
                                                    key
                                                ) - 1  # Remove -1, first letter is already increment

                                                # -- List contain all letters of key -- #
                                                for getLetterKey in key:
                                                    getCharAllInKey.append(
                                                        getLetterKey)

                                                # -- Check if all letters of key is equal to all letters of word -- #
                                                for indexCheckLetter, checkLetter in enumerate(
                                                        getIndexLineList):
                                                    if indexCheckLetter >= indexExploreStart and indexCheckLetter <= indexExploreEnd:
                                                        getWord.append(
                                                            checkLetter)

                                                # -- Check if number of chars in key equal number of chars in word -- #
                                                if list(
                                                        set(getCharAllInKey) -
                                                        set(getWord)) == []:
                                                    checkGetWord = "".join(
                                                        getWord)
                                                    checkGetKey = "".join(
                                                        getCharAllInKey)

                                                    # -- Check if key == word -- #
                                                    if checkGetWord == checkGetKey:
                                                        for obfChar in value:
                                                            charValue.append(
                                                                obfChar)

                                                        letterLine = letterValue
                                                        raise BreakLoop
                                                    else:
                                                        continue
                                                else:
                                                    continue
                                            else:
                                                continue
                                        else:
                                            continue
                                    else:
                                        continue

                        raise BreakLoop

                    except BreakLoop:
                        returnLine.append(letterLine)

        # -- Rewrite the line -- #
        returnLine = "".join(returnLine)
        return returnLine[:]

    def VarsDefinedByUser(self, codeArg, outputArg, mixerLevelArg, verboseArg):
        variablesDict = {}
        classesDict = {}
        functionsDict = {}
        includeDict = {}
        allDict = {}
        checkWordsMixed = []
        wordsExcluded = []
        wordsExcludedFound = []
        wordsIncludedFound = []
        wordsIncludedNotFound = []
        checkCountWordsMixed = 0
        checkCountWordsValue = 0
        checkQuotePassing = 0
        numberReplaced = 0
        countRecursFiles = 0

        if codeArg == "python":
            variablesDefined = r"(^\w+|\w+)([\s|^\s]*=[\s|\w|\"|\'])"  # Variables
            variablesErrorDefined = r"except(\s+\w+\sas\s)(\w)"  # Error variables
            variablesLoopDefined = r"for\s+([\w\s\,]+)(\s+in\s+)"  # Loop variables
            functionsDefined = r"def\s(\w+)"  # Functions
            classDefined = r"class\s(\w+)"  # Classes

            quoteOfEndCommentariesMultipleLines = r"^\s*[\"|\']{3}\)?\.?"  # """ and ''' without before variables, if commentaries is over multiple lines and he finish by .format() funtion
            quoteOfCommentariesMultipleLines = r"^\s*[\"|\']{3}$"  # """ and ''' without before variables and if commentaries is over multiple lines
            quoteInRegex = r"\={1}\s*r[\"|\']{1}"  # If quote in regex
            quoteIntoVariable = r".*\={1}\s*\w*\.?\w*[\(|\.]{1}[\"|\']{3}|.*\={1}\s*[\"|\']{3}"  # """ and ''' with before variables

            detectFile = "py"
            blockDirs = r"__pycache__"

        recursFiles = [
            f for f in glob.glob("{0}{1}**{1}*.{2}".format(
                outputArg, self.utils.Platform(), detectFile),
                                 recursive=True)
        ]

        # -- Find variables/classes/functions and mixed it -- #
        for file in recursFiles:
            if re.match(blockDirs, file):
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        # -- Variables -- #
                        search = re.search(variablesDefined, eachLine)
                        if search != None:
                            # -- Detect mixer -- #
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            # -- Add the mixer value of variables -- #
                            if search.group(1) not in variablesDict:
                                variablesDict[search.group(1)] = mixer

                        # -- Error variables -- #
                        search = re.search(variablesErrorDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(2) not in variablesDict:
                                variablesDict[search.group(2)] = mixer

                        # -- Loop variables -- #
                        search = re.search(variablesLoopDefined, eachLine)
                        if search != None:
                            if "," in search.group(1):
                                modifySearch = search.group(1).replace(
                                    ",", " ")
                                modifySearch = modifySearch.split()
                                for i in modifySearch:
                                    if i not in variablesDict:
                                        mixer = self.mixer.GetStringMixer(
                                            mixerLevelArg)
                                        variablesDict[i] = mixer
                            else:
                                if search.group(1) not in variablesDict:
                                    mixer = self.mixer.GetStringMixer(
                                        mixerLevelArg)
                                    variablesDict[search.group(1)] = mixer

                        # -- Functions -- #
                        search = re.search(functionsDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(1) not in functionsDict:
                                if codeArg == "python":
                                    if not re.match(r"__init__",
                                                    search.group(1)):
                                        functionsDict[search.group(1)] = mixer

                        # -- Classes -- #
                        search = re.search(classDefined, eachLine)
                        if search != None:
                            mixer = self.mixer.GetStringMixer(mixerLevelArg)
                            if search.group(1) not in classesDict:
                                classesDict[search.group(1)] = mixer

        # -- Remove excluded variables/classes/functions defined from 'exclude/python/exclude_python_words.txt' in dict -- #
        if os.path.exists(self.pythonExcludeWords) == True:
            with open(self.pythonExcludeWords, "r") as readFile:
                for word in readFile:
                    if "#" in word or word == "\n":
                        continue
                    else:
                        word = word.rstrip()
                        wordsExcluded.append(word)
        else:
            print("[-] '{0}' file not found\n".format(self.pythonExcludeWords))

        for word in wordsExcluded:
            if word in variablesDict.keys():
                wordsExcludedFound.append(word)
                del variablesDict[word]
            if word in classesDict.keys():
                wordsExcludedFound.append(word)
                del classesDict[word]
            if word in functionsDict.keys():
                wordsExcludedFound.append(word)
                del functionsDict[word]

        # -- Include variables/classes/functions defined from 'include/python/include_python_words.txt' in dict -- #
        if os.path.exists(self.pythonIncludeWords) == True:
            with open(self.pythonIncludeWords, "r") as readFile:
                for word in readFile:
                    if "#" in word or word == "\n":
                        continue
                    else:
                        word = word.rstrip()
                        wordsIncludedFound.append(word)
        else:
            print("[-] '{0}' file not found\n".format(self.pythonIncludeWords))

        for word in wordsIncludedFound:
            if word not in variablesDict.keys(
            ) and word not in classesDict.keys(
            ) and word not in functionsDict.keys():
                mixer = self.mixer.GetStringMixer(mixerLevelArg)
                includeDict[word] = mixer
                wordsIncludedNotFound.append(word)

        for file in recursFiles:
            if re.match(blockDirs, file):
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        for word in wordsIncludedNotFound:
                            if word in eachLine:
                                wordsIncludedNotFound.remove(word)

        for word in wordsIncludedNotFound:
            if word in includeDict.keys():
                del includeDict[word]

        # -- Display variables/classes/functions found -- #
        if verboseArg:
            print("\n[+] Variables found :\n")

            if variablesDict == {}:
                print("-> No result")
            else:
                for key, value in variablesDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Classes found :\n")

            if classesDict == {}:
                print("-> No result")
            else:
                for key, value in classesDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Functions found :\n")

            if functionsDict == {}:
                print("-> No result")
            else:
                for key, value in functionsDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Include found :\n")

            if includeDict == {}:
                print("-> No result")
            else:
                for key, value in includeDict.items():
                    print("-> {0} : {1}".format(key, value))

            print("\n[+] Exclude found :\n")

            if wordsExcludedFound == []:
                print("-> No result")
            else:
                for word in wordsExcludedFound:
                    print("-> {0} : excluded".format(word))

        # -- Merge all dicts -- #
        allDict = self.utils.DictMerge(allDict, variablesDict)
        allDict = self.utils.DictMerge(allDict, classesDict)
        allDict = self.utils.DictMerge(allDict, functionsDict)
        allDict = self.utils.DictMerge(allDict, includeDict)

        for number in recursFiles:
            countRecursFiles += 1

        # -- Change variables/classes/functions to mixed values -- #
        print(
            "\n[+] Running replacement of variables/classes/functions in {0} file(s)...\n"
            .format(countRecursFiles))

        with tqdm(total=countRecursFiles) as pbar:
            for file in recursFiles:
                pbar.update(1)
                if re.match(blockDirs, file):
                    continue
                else:
                    with fileinput.input(file, inplace=True) as inputFile:
                        for eachLine in inputFile:
                            if not eachLine:
                                continue
                            else:
                                if codeArg == "python":
                                    # -- Check code into """ or ''' -- #
                                    if re.match(quoteIntoVariable, eachLine):
                                        checkQuotePassing += 1
                                        eachLine = ReplaceWords.EachLine(
                                            self, codeArg, eachLine,
                                            allDict.items())
                                        print(eachLine)
                                        continue
                                    elif re.match(
                                            quoteOfCommentariesMultipleLines,
                                            eachLine
                                    ) or re.match(
                                            quoteOfEndCommentariesMultipleLines,
                                            eachLine):
                                        checkQuotePassing += 1
                                        eachLine = ReplaceWords.EachLine(
                                            self, codeArg, eachLine,
                                            allDict.items())
                                        print(eachLine)
                                        if checkQuotePassing == 2:
                                            checkQuotePassing = 0
                                        continue

                                    if checkQuotePassing == 1:
                                        print(eachLine)
                                        continue
                                    elif checkQuotePassing == 2:
                                        checkQuotePassing = 0
                                        continue
                                    else:
                                        eachLine = ReplaceWords.EachLine(
                                            self, codeArg, eachLine,
                                            allDict.items())
                                        print(eachLine)
                                        continue

        # -- Check if variables/classes/functions have been mixed -- #
        for file in recursFiles:
            if re.match(blockDirs, file):
                continue
            else:
                with open(file, "r") as readFile:
                    readF = readFile.readlines()
                    for eachLine in readF:
                        for value in allDict.values():
                            if value in eachLine:
                                checkWordsMixed.append(value)

        # -- Remove duplicated key -- #
        checkListWordsMixed = list(dict.fromkeys(checkWordsMixed))

        for i in checkListWordsMixed:
            checkCountWordsMixed += 1
        for i in allDict.values():
            checkCountWordsValue += 1

        if (self.remove.LineBreaks(codeArg, outputArg) == 0):
            if checkCountWordsMixed == checkCountWordsValue:
                print(
                    "\n-> {0} variables/classes/functions replaced in {1} file(s)\n"
                    .format(checkCountWordsValue, countRecursFiles))
                return EXIT_SUCCESS
            else:
                return EXIT_FAILURE
        else:
            return EXIT_FAILURE
 def __init__(self):
     self.mixer  = Mixer()
     self.remove = Remove()
     self.utils  = Utils()
     self.pythonExcludeDefaultString = "exclude/string_to_string_mixed/exclude_word_do_not_modify.txt"
     self.pythonExcludeUserString    = "exclude/string_to_string_mixed/exclude_word_by_user.txt"
def main():
    if sys.version_info[0] != 3:
        print("[-] Intensio-Obfuscator only support Python 3.x")
        sys.exit(0)

    if sys.platform != "win32" and sys.platform != "linux":
        print("[-] This tool support [windows - Linux] only !")
        sys.exit(0)

    try:
        from core.lolz.intensio_bullshit import BestFunctionOfTheWorld
        from core.lolz.intensio_design_skill import INTENSIO_BANNER
        from core.utils.intensio_utils import Utils
        from core.utils.intensio_usage import Args
        from core.utils.intensio_error import EXIT_SUCCESS, ERROR_BAD_ENVIRONMENT, ERROR_INVALID_PARAMETER, ERROR_BAD_ARGUMENTS,\
                                                ERROR_INVALID_FUNCTION, ERROR_FILE_NOT_FOUND
        from core.obfuscation.intensio_replace import Replace
        from core.obfuscation.intensio_padding import Padding
        from core.obfuscation.intensio_analyze import Analyze
        from core.obfuscation.intensio_remove import Remove
    except ImportError as e:
        print("[-] {0}\n".format(e))
        sys.exit(0)

    args    = Args()
    utils   = Utils()

    if len(sys.argv) > 1 and len(sys.argv) <= 14:
        if args.GetArgsValue().onefile == False and args.GetArgsValue().multiplefiles == False:
            print("[-] [-f --onefile] or [-d --multiple] argument unspecifed")
            sys.exit(ERROR_BAD_ARGUMENTS)

        if args.GetArgsValue().input:
            if args.GetArgsValue().output:
                for line in INTENSIO_BANNER.split("\n"):
                    time.sleep(0.05)
                    print(line)

                if args.GetArgsValue().secret:
                    if (BestFunctionOfTheWorld("YES-YES-YES!!") == EXIT_SUCCESS):
                        pass
                    else:
                        sys.exit(ERROR_INVALID_FUNCTION)

                print("\n\n*********************** [ Analyze and setup environment ] ***********************\n")
                # -- Analysis and set up of the work environment -- #
                if args.GetArgsValue().code:
                    if re.match(r"^python$", args.GetArgsValue().code):
                        analyze = Analyze()

                        if (analyze.InputAvailable(args.GetArgsValue().onefile, args.GetArgsValue().input, args.GetArgsValue().code) == EXIT_SUCCESS):
                            print("[+] Analyze input argument '{0}' -> Successful".format(args.GetArgsValue().input))

                            if (analyze.OutputAvailable(args.GetArgsValue().onefile, args.GetArgsValue().input, args.GetArgsValue().code, args.GetArgsValue().output) == EXIT_SUCCESS):
                                print("[+] Analyze and setup output argument environment '{0}' -> Successful".format(args.GetArgsValue().output))

                                if args.GetArgsValue().mixer:
                                    if re.match(r"(^lower$)|(^medium$)|(^high$)", args.GetArgsValue().mixer):
                                        if not args.GetArgsValue().padding and not args.GetArgsValue().replace and not args.GetArgsValue().remove:
                                            print("\n[-] Need at least one argument [-r --replace] or [-p --padding] or [-rm -remove]")
                                            sys.exit(ERROR_BAD_ARGUMENTS)
                                        else:
                                            print("\n\n***************************** [ Obfuscation Replace ] ****************************\n")
                                            if args.GetArgsValue().replace:
                                                replace = Replace()

                                                if (replace.VarsDefinedByUser(args.GetArgsValue().onefile, args.GetArgsValue().code, args.GetArgsValue().output, args.GetArgsValue().mixer) == EXIT_SUCCESS):
                                                    print("[+] Obfuscation Replace -> Successful")
                                                else:
                                                    print("[-] Obfuscation Replace -> Failed")
                                            else:
                                                print("[!] Obfuscation Replace no asked !")

                                            print("\n\n***************************** [ Obfuscation Padding ] ****************************\n")
                                            if args.GetArgsValue().padding:
                                                paddingScripts = Padding()

                                                if (paddingScripts.AddScripts(args.GetArgsValue().onefile, args.GetArgsValue().code, args.GetArgsValue().output, args.GetArgsValue().mixer) == EXIT_SUCCESS):
                                                    print("[+] Obfuscation Padding -> Successful")
                                                else:
                                                    print("[-] Obfuscation Padding -> Failed")
                                            else:
                                                print("[!] Obfuscation Padding no asked !")

                                            print("\n\n***************************** [ Obfuscation Remove ] *****************************\n")
                                            if args.GetArgsValue().remove:
                                                removeData = Remove()

                                                if (removeData.Commentaries(args.GetArgsValue().onefile, args.GetArgsValue().code, args.GetArgsValue().output) == EXIT_SUCCESS):
                                                    print("[+] Obfuscation Remove -> Successful\n")
                                                else:
                                                    print("[-] Obfuscation Remove -> Failed\n")
                                            else:
                                                print("[!] Obfuscation Remove no asked !\n")
                                    else:
                                        print("[-] Incorrect level of mixer, [lower - medium - high] only supported\n")
                                        sys.exit(ERROR_INVALID_PARAMETER)
                                else:
                                    print("[-] Mixer [-m --mixer] argument missing\n")
                                    sys.exit(ERROR_BAD_ARGUMENTS)
                            else:
                                print("[-] Analyze output '{0}' failed\n".format(args.GetArgsValue().output))
                                sys.exit(ERROR_INVALID_FUNCTION)
                        else:
                            print("[-] Analyze input '{0}' failed\n".format(args.GetArgsValue().input))
                            sys.exit(ERROR_INVALID_FUNCTION)
                    else:
                        print("[-] '{0}' Incorrect code argument, [python] only currently supported\n".format(args.GetArgsValue().Code))
                        sys.exit(ERROR_INVALID_PARAMETER)
                else:
                    print("[-] Code [-c --code] argument missing\n")
                    sys.exit(ERROR_BAD_ARGUMENTS)
            else:
                print("[-] Output [-o --output] argument missing\n")
                sys.exit(ERROR_BAD_ARGUMENTS)
        else:
            print("[-] Input [-i --input] argument missing\n")
            sys.exit(ERROR_BAD_ARGUMENTS)
    else:
        print("[-] Incorrect number of arguments\n")
        args.GetArgHelp()
        sys.exit(ERROR_BAD_ARGUMENTS)