Topic: Errore Veil-evasion.py - Non riesco a capire da cosa è causato  (Letto 397 volte)

0 Utenti e 1 Visitatore stanno visualizzando questo topic.

Offline neo8004

  • python unicellularis
  • *
  • Post: 2
  • Punti reputazione: 0
    • Mostra profilo
salve,

qualcuno riesce a spiegarmi questo errore che mi restituisce VEil-evasion.py?

[CODE ]
root@kali:~/Veil-Evasion# ./Veil-Evasion.py
Traceback (most recent call last):
  File "./Veil-Evasion.py", line 23, in <module>
    from modules.common import controller
  File "/root/Veil-Evasion/modules/common/controller.py", line 25, in <module>
    import settings
  File "/etc/veil/settings.py", line 38
    Arch Linux based distributions: /opt/metasploit
    ^
IndentationError: unexpected indent

allego anche i relativi file:
« Ultima modifica: Luglio 30, 2017, 14:23 da neo8004 »

Offline neo8004

  • python unicellularis
  • *
  • Post: 2
  • Punti reputazione: 0
    • Mostra profilo
Re:Errore Veil-evasion.py - Non riesco a capire da cosa è causato
« Risposta #1 il: Luglio 30, 2017, 13:45 »
controller.py


"""
Contains the main controller object for Veil-Evasion.

"""

# Import Modules
import glob
import imp
import sys
import os
import readline
import re
import socket
import commands
import time
import subprocess
import hashlib
from subprocess import Popen, PIPE


# try to find and import the settings.py config file
if os.path.exists("/etc/veil/settings.py"):
    try:
        sys.path.append("/etc/veil/")
        import settings

        # check for a few updated values to see if we have a new or old settings.py file
        try:
            settings.VEIL_EVASION_PATH
        except AttributeError:
            #os.system('clear')
            print 'n========================================================================='
            print ' New major Veil-Evasion version installed'
            print '========================================================================='
            print 'n [*] Manually run: bash %s -s' % os.path.abspath("setup/setup.sh")
            sys.exit()

    except ImportError:
        print "n [!] ERROR #1: run %s manuallyn" % (os.path.abspath("./config/update.py"))
        sys.exit()
elif os.path.exists("./config/settings.py"):
    try:
        sys.path.append("./config")
        import settings
    except ImportError:
        print "n [!] ERROR #2: run %s manuallyn" % (os.path.abspath("./config/update.py"))
        sys.exit()
else:
    # if the file isn't found, try to run the update script
    #os.system('clear')
    print 'n========================================================================='
    print ' Veil First Run Detected...'
    print '========================================================================='
    print 'n [*] Manually run: bash %s -s' % os.path.abspath("setup/setup.sh")
    sys.exit()


from os.path import join, basename, splitext
from modules.common import messages
from modules.common import helpers
from modules.common import supportfiles
from modules.common import completers


class Controller:
    """
    Principal controller object that's instantiated.

    Loads all payload modules dynamically from ./modules/payloads/* and
    builds store the instantiated payload objects in self.payloads.
    has options to list languages/payloads, manually set payloads,
    generate code, and provides the main interactive
    menu that lists payloads and allows for user ineraction.
    """

    def __init__(self, langs = None, oneRun=True):
        self.payloads = list()
        # a specific payload, so we can set it manually
        self.payload = None
        self.payloadname = None
        # restrict loaded modules to specific languages
        self.langs = langs

        # oneRune signifies whether to only generate one payload, as we would
        # if being invoked from external code.
        # defaults to True, so Veil.py needs to manually specific "False" to
        # ensure an infinite loop
        self.oneRun = oneRun

        self.outputFileName = ""

        self.commands = [   ("use","Use a specific payload"),
                            ("info","Information on a specific payload"),
                            ("list","List available payloads"),
                            ("update","Update Veil-Evasion to the latest version"),
                            ("clean","Clean out payload folders"),
                            ("checkvt","Check payload hashes vs. VirusTotal"),
                            ("exit","Exit Veil-Evasion")]

        self.payloadCommands = [    ("set","Set a specific option value"),
                                    ("info","Show information about the payload"),
                                    ("options","Show payload's options"),
                                    ("generate","Generate payload"),
                                    ("back","Go to the main menu"),
                                    ("exit","exit Veil-Evasion")]

        self.LoadPayloads()


    def LoadPayloads(self):
        """
        Crawl the module path and load up everything found into self.payloads.
        """

        # crawl up to 5 levels down the module path
        for x in xrange(1,5):
            # make the folder structure the key for the module

            d = dict( (path[path.find("payloads")+9:-3], imp.load_source( "/".join(path.split("/")[3:])[:-3],path )  ) for path in glob.glob(join(settings.VEIL_EVASION_PATH+"/modules/payloads/" + "*/" * x,'[!_]*.py')) )

            # instantiate the payload stager
            for name in d.keys():
                module = d[name].Payload()
                self.payloads.append( (name, module) )

        # sort payloads by their key/path name
        self.payloads = sorted(self.payloads, key=lambda x: (x[0]))


    def ListPayloads(self):
        """
        Prints out available payloads in a nicely formatted way.
        """

        print helpers.color("n [*] Available Payloads:n")
        lastBase = None
        x = 1
        for (name, payload) in self.payloads:
            parts = name.split("/")
            if lastBase and parts[0] != lastBase:
                print ""
            lastBase = parts[0]
            print "t%s)t%s" % (x, '{0: <24}'.format(name))
            x += 1
        print ""


    def UpdateVeil(self, interactive=True):
        """
        Updates Veil by invoking git pull on the OS

        """
        print "n Updating Veil via git...n"
        updatecommand = ['git', 'pull']
        updater = subprocess.Popen(updatecommand, cwd=settings.VEIL_EVASION_PATH, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        updoutput, upderr = updater.communicate()

        if interactive:
            raw_input(" [>] Veil updated, press any key to continue.")


    def CheckVT(self, interactive=True):
        """
        Checks payload hashes in veil-output/hashes.txt vs VirusTotal
        """

        # Command for in-menu vt-notify check against hashes within hash file
        # It's only triggered if selected in menu and file isn't empty
        try:
            if os.stat(settings.HASH_LIST)[6] != 0:
                checkVTcommand = "./vt-notify.rb -f " + settings.HASH_LIST + " -i 0"
                print helpers.color("n [*] Checking Virus Total for payload hashes...n")
                checkVTout = Popen(checkVTcommand.split(), stdout=PIPE, cwd=settings.VEIL_EVASION_PATH + "tools/vt-notify/")

                found = False
                for line in checkVTout.stdout:
                    if "was found" in line:
                        filehash, filename = line.split()[0].split(":")
                        print helpers.color(" [!] File %s with hash %s found!" %(filename, filehash), warning=True)
                        found = True
                if found == False:
                    print " [*] No payloads found on VirusTotal!"

                raw_input("n [>] Press any key to continue...")

            else:
                print helpers.color("n [!] Hash file is empty, generate a payload first!", warning=True)
                raw_input("n [>] Press any key to continue...")

        except OSError as e:
            print helpers.color("n [!] Error: hash list %s not found" %(settings.HASH_LIST), warning=True)
            raw_input("n [>] Press any key to continue...")


    def CleanPayloads(self, interactive=True):
        """
        Cleans out the payload source/compiled/handler folders.
        """

        # prompt for confirmation if we're in the interactive menu
        if interactive:
            choice = raw_input("n [>] Are you sure you want to clean payload folders? [y/N] ")

            if choice.lower() == "y":
                print "n [*] Cleaning %s" %(settings.PAYLOAD_SOURCE_PATH)
                os.system('rm -f %s/*.*' %(settings.PAYLOAD_SOURCE_PATH))

                print " [*] Cleaning %s" %(settings.PAYLOAD_COMPILED_PATH)
                os.system('rm -f %s/*.exe' %(settings.PAYLOAD_COMPILED_PATH))

                print " [*] Cleaning %s" %(settings.HANDLER_PATH)
                os.system('rm -f %s/*.rc' %(settings.HANDLER_PATH))

                print " [*] cleaning %s" %(settings.HASH_LIST)
                os.system('rm -f %s' %(settings.HASH_LIST))
                os.system('touch ' + settings.HASH_LIST)

                print " [*] cleaning ./tools/vt-notify/results.log"
                os.system('rm -f ./tools/vt-notify/results.log')

                choice = raw_input("n [>] Folders cleaned, press any key to return to the main menu.")

        else:
            print "n [*] Cleaning %s" %(settings.PAYLOAD_SOURCE_PATH)
            os.system('rm -f %s/*.*' %(settings.PAYLOAD_SOURCE_PATH))

            print " [*] Cleaning %s" %(settings.PAYLOAD_COMPILED_PATH)
            os.system('rm -f %s/*.exe' %(settings.PAYLOAD_COMPILED_PATH))

            print " [*] Cleaning %s" %(settings.HANDLER_PATH)
            os.system('rm -f %s/*.rc' %(settings.HANDLER_PATH))

            print " [*] cleaning %s" %(settings.HASH_LIST)
            os.system('rm -f %s' %(settings.HASH_LIST))
            os.system('touch ' + settings.HASH_LIST)

            print "n [*] Folders cleanedn"

    def PayloadOptions(self, payload):
        print helpers.color("n Required Options:n")

        print " NametttCurrent ValuetDescription"
        print " ----ttt-------------t-----------"

        # sort the dictionary by key before we output, so it looks nice
        for key in sorted(self.payload.required_options.iterkeys()):
            print " %st%st%s" % ('{0: <16}'.format(key), '{0: <8}'.format(payload.required_options[key][0]), payload.required_options[key][1])

        print ""

    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on
        showTitle = whether to show the Veil title
        showInfo = whether to show the payload information bit

        """
        if showTitle:
            if settings.TERMINAL_CLEAR != "false": messages.title()

        if showInfo:
            # extract the payload class name from the instantiated object, then chop off the load folder prefix
            payloadname = "/".join(str(str(payload.__class__)[str(payload.__class__).find("payloads"):]).split(".")[0].split("/")[1:])

            print helpers.color(" Payload information:n")
            print "tName:tt" + payloadname
            print "tLanguage:t" + payload.language
            print "tRating:tt" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "tShellcode:ttused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            self.PayloadOptions(self.payload)

    def SetPayload(self, payloadname, options):
        """
        Manually set the payload for this object with specified options.

        name = the payload to set, ex: c/meter/rev_tcp
        options = dictionary of required options for the payload, ex:
                options['customShellcode'] = "x00..."
                options['required_options'] = {"compile_to_exe" : ["Y", "Compile to an executable"], ...}
                options['msfvenom'] = ["windows/meterpreter/reverse_tcp", ["LHOST=192.168.1.1","LPORT=443"]
        """

        # iterate through the set of loaded payloads, trying to find the specified payload name
        for (name, payload) in self.payloads:

            if payloadname.lower() == name.lower():

                # set the internal payload variable
                self.payload = payload
                self.payloadname = name

            # did they enter a number rather than the full payload?
            elif payloadname.isdigit() and 0 < int(payloadname) <= len(self.payloads):
                x = 1
                for (name, pay) in self.payloads:
                    # if the entered number matches the payload #, use that payload
                    if int(payloadname) == x:
                        self.payload = pay
                        self.payloadname = name
                    x += 1

        print " Payload: %sn" % helpers.color(self.payloadname)

        # if payload is found, then go ahead
        if self.payload:

            # options['customShellcode'] = "x00..."
            if 'customShellcode' in options:
                self.payload.shellcode.setCustomShellcode(options['customShellcode'])
            # options['required_options'] = {"compile_to_exe" : ["Y", "Compile to an executable"], ...}
            if 'required_options' in options:
                try:
                    for k,v in options['required_options'].items():
                        self.payload.required_options[k] = v
                except:
                    print helpers.color("n [!] Internal error #4.", warning=True)
            # options['msfvenom'] = ["windows/meterpreter/reverse_tcp", ["LHOST=192.168.1.1","LPORT=443"]
            if 'msfvenom' in options:
                if hasattr(self.payload, 'shellcode'):
                    self.payload.shellcode.SetPayload(options['msfvenom'])
                else:
                    print helpers.color("n [!] Internal error #3: This module does not use msfvenom!", warning=True)
                    sys.exit()

            if not self.ValidatePayload(self.payload):

                print helpers.color("n [!] WARNING: Not all required options filledn", warning=True)
                self.PayloadOptions(self.payload)
                print ''
                sys.exit()

        # if a payload isn't found, then list available payloads and exit
        else:

            print helpers.color(" [!] Invalid payload selectednn", warning=True)
            self.ListPayloads()
            sys.exit()


    def ValidatePayload(self, payload):
        """
        Check if all required options are filled in.

        Returns True if valid, False otherwise.
        """

        # don't worry about shellcode - it validates itself


        # validate required options if present
        if hasattr(payload, 'required_options'):
            for key in sorted(self.payload.required_options.iterkeys()):
                if payload.required_options[key][0] == "":
                    return False

        return True


    def GeneratePayload(self):
        """
        Calls self.payload.generate() to generate payload code.

        Returns string of generated payload code.
        """
        return self.payload.generate()


    def OutputMenu(self, payload, code, showTitle=True, interactive=True, args=None):
        """
        Write a chunk of payload code to a specified ouput file base.
        Also outputs a handler script if required from the options.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        OutputBaseChoice = ""
        overwrite = False

        # if we have arguments passed, extract out the values we want
        if args:
            OutputBaseChoice = args.o
            overwrite = args.overwrite

        # if we get .exe or ELF (with no base) code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe" or payload.extension == "war":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        # Check for ELF binary
        elif hasattr(payload, 'type') and payload.type == "ELF":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                if settings.TERMINAL_CLEAR != "false": messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            OutputBaseChoice = raw_input("n [>] Please enter the base name for output files (default is 'payload'): ")

            # ensure we get a base name and not a full path
            while OutputBaseChoice != "" and "/" in OutputBaseChoice:
                print helpers.color(" [!] Please provide a base name, not a path, for the output base", warning=True)
                OutputBaseChoice = raw_input("n [>] Please enter the base name for output files (default is 'payload'): ")

        # for invalid output base choices that are passed by arguments
        else:
            if "/" in OutputBaseChoice:
                print helpers.color(" [!] Please provide a base name, not a path, for the output base", warning=True)
                print helpers.color(" [!] Defaulting to 'payload' for output base...", warning=True)
                OutputBaseChoice = "payload"

        if OutputBaseChoice == "": OutputBaseChoice = "payload"

        # if we are overwriting, this is the base choice used
        FinalBaseChoice = OutputBaseChoice

        # if we're not overwriting output files, walk the existing and increment
        if not overwrite:
            # walk the output path and grab all the file bases, disregarding extensions
            fileBases = []
            for (dirpath, dirnames, filenames) in os.walk(outputFolder):
                fileBases.extend(list(set([x.split(".")[0] for x in filenames if x.split(".")[0] != ''])))
                break

            # as long as the file exists, increment a counter to add to the filename
            # i.e. "payload3.py", to make sure we don't overwrite anything
            FinalBaseChoice = OutputBaseChoice
            x = 1
            while FinalBaseChoice in fileBases:
                FinalBaseChoice = OutputBaseChoice + str(x)
                x += 1

Offline Python

  • python sapiens sapiens
  • ******
  • Post: 2.045
  • Punti reputazione: 2
  • Radon - Cyclomatic Complexity of your Python code
    • Mostra profilo
    • Radon - Cyclomatic Complexity of your Python code
Re:Errore Veil-evasion.py - Non riesco a capire da cosa è causato
« Risposta #2 il: Luglio 31, 2017, 08:18 »
È inutile che metti 400 linee di codice sul forum, danno solo fastidio alla lettura. Meglio una cosa come Gist di Github o Pastebin o quello che ti pare.

E comunque, come puoi leggere dal traceback, l'errore è nel file settings.py alla linea 38. Quindi tutte queste 400 linee non servono a nulla.