Beispiel #1
0
def configure_modbus_logger(cfg, recycle_logs=True):
    """
    Configure the logger.

    Args:
        cfg (Namespace): The PUReST config namespace.
    """

    logger = logging.getLogger("modbus_tk")
    if isinstance(cfg, dict):
        cfg = Configuration(**cfg)

    if cfg.no_modbus_log:
        logger.setLevel(logging.ERROR)
        logger.addHandler(logging.NullHandler())
    else:
        logger.setLevel(logging.DEBUG)
        fmt = "%(asctime)s - %(levelname)s - " "%(module)s::%(funcName)s @ %(lineno)d - %(message)s"
        fmtr = logging.Formatter(fmt)

        if not cfg.no_modbus_console_log:
            sh = logging.StreamHandler()
            sh.setFormatter(fmtr)
            sh.setLevel(cfg.modbus_console_log_level.upper())
            logger.addHandler(sh)

        if not cfg.no_modbus_file_log:
            modbus_log = path(cfg.modbus_log)
            if recycle_logs:
                remove_file(modbus_log)
            make_dir(os.path.dirname(modbus_log))
            fh = logging.FileHandler(modbus_log)
            fh.setFormatter(fmtr)
            fh.setLevel(cfg.modbus_file_log_level.upper())
            logger.addHandler(fh)
 def execute_matrix_generator(self):
     print('Gen matrix...')
     self.matrix_a = self._gen_matrix()
     self.matrix_b = self._gen_matrix()
     remove_file(self.file_name)
     print('Saving to file...')
     save_matrix(self.file_name, self.matrix_a)
     save_matrix(self.file_name, self.matrix_b)
     return self.file_name
Beispiel #3
0
def main():
    for hive in ["sam", "security", "system"]:
        filename = os.path.abspath("%s.reg" % hive)
        common.log("Exporting %s hive to %s" % (hive, filename))
        common.execute(
            [REG, "save",
             "hkey_local_machine\\%s" % hive, filename])
        common.remove_file(filename)

        common.execute([REG, "save", "hklm\\%s" % hive, filename])
        common.remove_file(filename)
Beispiel #4
0
def run():
    print(" > Testing pagination using the last document's _id (find/limit)")
    common.remove_file(FILE_NAME)
    start_time = time.time()
    _run()
    seconds_elapsed = time.time() - start_time
    time_msg = ('Time elapsed %s (find limit)' %
                common.format_time(seconds_elapsed))
    print(time_msg)
    common.append_to_file('times', time_msg)
    print('Data is in %s' % FILE_NAME)
    return FILE_NAME
Beispiel #5
0
def run():
    print(' > Testing skip limit pagination')
    common.remove_file(FILE_NAME)
    start_time = time.time()
    _run()
    seconds_elapsed = time.time() - start_time
    time_msg = ('Time elapsed %s (skip limit)' % 
                common.format_time(seconds_elapsed))
    print(time_msg)
    common.append_to_file('times', time_msg)
    print('Data is in %s' % FILE_NAME)
    return FILE_NAME
Beispiel #6
0
def main():
    # http server will terminate on main thread exit
    # if daemon is True
    server, ip, port = common.serve_web()

    uri = "bin/mydll.dll"
    target_file = "mydll.dll"
    common.clear_web_cache()
    url = "http://{ip}:{port}/{uri}".format(ip=ip, port=port, uri=uri)
    common.execute(["certutil.exe", "-urlcache", "-split", "-f", url, target_file])

    server.shutdown()
    common.remove_file(target_file)
Beispiel #7
0
def main():
    masquerades = [
        "svchost.exe",
        "lsass.exe",
        "services.exe",
        "csrss.exe",

    ]

    for name in masquerades:
        path = os.path.abspath(name)
        common.copy_file(MY_APP, path)
        common.execute(path, timeout=3, kill=True)
        common.remove_file(path)
Beispiel #8
0
 def proccess_matrix_summary(self):
     print('Read matrix...')
     file_name = self.file_loader.get_file()
     res = self._read_matrix(file_name)
     if not res:
         return
     print('Sum matrix')
     matrix_a, matrix_b = res
     file_name = get_files_directory() + 'F1.txt'
     new_matrix = self._sum_matrix(matrix_a, matrix_b)
     print('Saving to file...')
     remove_file(file_name)
     save_matrix(file_name, new_matrix)
     return new_matrix
Beispiel #9
0
def main():
    common.log("Encoding target")
    encoded_file = os.path.abspath('encoded.txt')
    decoded_file = os.path.abspath('decoded.exe')
    common.execute(
        "c:\\Windows\\System32\\certutil.exe -encode c:\\windows\\system32\\cmd.exe %s"
        % encoded_file)

    common.log("Decoding target")
    common.execute("c:\\Windows\\System32\\certutil.exe -decode %s %s" %
                   (encoded_file, decoded_file))

    common.log("Cleaning up")
    common.remove_file(encoded_file)
    common.remove_file(decoded_file)
Beispiel #10
0
def main():
    common.log("MsBuild Beacon")
    server, ip, port = common.serve_web()
    common.clear_web_cache()

    common.log("Updating the callback http://%s:%d" % (ip, port))
    target_task = "tmp-file.csproj"
    common.copy_file(common.get_path("bin", "BadTasks.csproj"), target_task)
    new_callback = "http://%s:%d" % (ip, port)
    common.patch_regex(target_task, common.CALLBACK_REGEX, new_callback)

    common.execute([MS_BUILD, target_task])
    common.remove_file(target_task)

    server.shutdown()
Beispiel #11
0
def main():
    common.log("PowerShell Suspicious Commands")
    temp_script = os.path.abspath("tmp.ps1")

    # Create an empty script
    with open(temp_script, "wb") as f:
        f.write("whoami.exe\n")

    powershell_commands = [
        'powershell -encoded %s' % encode('ping google.com'),
        'powershell.exe -ExecutionPol Bypass %s' % temp_script,
        'powershell.exe iex Get-Process',
        'powershell.exe -ec %s' % encode('Get-Process' + ' ' * 1000),
    ]

    for command in powershell_commands:
        common.execute(command)

    common.remove_file(temp_script)
Beispiel #12
0
def main():
    server, ip, port = common.serve_web()
    common.clear_web_cache()

    target_app = "mydotnet.exe"
    common.patch_file(MY_DOT_NET,
                      common.wchar(":8000"),
                      common.wchar(":%d" % port),
                      target_file=target_app)

    install_util64 = "C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\InstallUtil.exe"
    install_util86 = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil.exe"
    fallback = False

    if os.path.exists(install_util64):
        install_util = install_util64
    elif os.path.exists(install_util86):
        install_util = install_util86
    else:
        install_util = None
        fallback = True

    if not fallback:
        common.clear_web_cache()
        common.execute([
            install_util, '/logfile=', '/LogToConsole=False', '/U', target_app
        ])

    else:
        common.log("Unable to find InstallUtil, creating temp file")
        install_util = os.path.abspath("InstallUtil.exe")
        common.copy_file(sys.executable, install_util)
        common.execute([
            install_util, "-c",
            "import urllib; urllib.urlopen('http://%s:%d')" %
            (common.LOCAL_IP, port)
        ])
        common.remove_file(install_util)

    common.remove_file(target_app)
    server.shutdown()
Beispiel #13
0
def main():
    status = common.run_system()
    if status is not None:
        return status

    common.log("System Restore Process Evasion")
    program_path = common.get_path("bin", "myapp.exe")
    common.log("Finding a writeable directory in %s" % SYSTEM_RESTORE)
    target_directory = common.find_writeable_directory(SYSTEM_RESTORE)

    if not target_directory:
        common.log("No writeable directories in System Restore. Exiting...",
                   "-")
        return common.UNSUPPORTED_RTA

    target_path = os.path.join(target_directory, "restore-process.exe")
    common.copy_file(program_path, target_path)
    common.execute(target_path)

    common.log("Cleanup", log_type="-")
    common.remove_file(target_path)
Beispiel #14
0
def main():
    common.log("MS Office unusual child process emulation")
    suspicious_apps = [
        "msiexec.exe /i blah /quiet",
        "powershell.exe exit",
        "wscript.exe //b",
    ]
    cmd_path = "c:\\windows\\system32\\cmd.exe"

    for office_app in ["winword.exe", "excel.exe"]:

        common.log("Emulating %s" % office_app)
        office_path = os.path.abspath(office_app)
        common.copy_file(cmd_path, office_path)

        for command in suspicious_apps:
            common.execute('%s /c %s' % (office_path, command),
                           timeout=5,
                           kill=True)

        common.log('Cleanup %s' % office_path)
        common.remove_file(office_path)
Beispiel #15
0
def main():
    common.log("NetSH Advanced Firewall Configuration", log_type="~")
    netsh = "netsh.exe"

    rules_file = os.path.abspath("fw.rules")

    # Check to be sure that fw.rules does not already exist from previously running this script
    common.remove_file(rules_file)

    common.log("Backing up rules")
    common.execute([netsh, "advfirewall", "export", rules_file])

    common.log("Disabling the firewall")
    common.execute(
        [netsh, "advfirewall", "set", "allprofiles", "state", "off"])

    common.log("Enabling the firewall")
    common.execute([netsh, "advfirewall", "set", "allprofiles", "state", "on"])

    common.log("Undoing the firewall change", log_type="-")
    common.execute([netsh, "advfirewall", "import", rules_file])

    common.remove_file(rules_file)
Beispiel #16
0
def main():
    common.log("Persistent Scripts")

    if common.check_system():
        common.log("Must be run as a non-SYSTEM user", log_type="!")
        return 1

    # Remove any existing profiles
    user_profile = os.environ['USERPROFILE']
    log_file = os.path.join(user_profile, NAME + ".log")

    # Remove log file if exists
    common.remove_file(log_file)

    common.log("Running VBS")
    common.execute(["cscript.exe", VBS])

    # Let the script establish persistence, then read the log file back
    time.sleep(5)
    common.print_file(log_file)
    common.remove_file(log_file)

    # Now trigger a 'logon' event which causes persistence to run
    common.log("Simulating user logon and loading of profile")
    common.execute(["taskkill.exe", "/f", "/im", "explorer.exe"])
    time.sleep(2)

    common.execute(["C:\\Windows\\System32\\userinit.exe"], wait=True)
    common.execute(["schtasks.exe", "/run", "/tn", NAME])

    # Wait for the "logon" to finish
    time.sleep(30)
    common.print_file(log_file)

    # Now delete the user profile
    common.log("Cleanup", log_type="-")
    common.remove_file(log_file)
Beispiel #17
0
 def __init__(self, workdspace):
     self.runfile = path.join(workdspace, "drun.sh")
     remove_file(self.runfile)
     self.fopen = open(self.runfile, 'w')
     self.fopen.write(BASE_CONTENT)
Beispiel #18
0
 def remove_cache(self):
     if self.qvc:
         self.qvc = None
         self.qvc_is_ready = False
         remove_file(self.qvc_path)
Beispiel #19
0
    def co_init_cache(self):
        if self.qvc is not None:
            raise MultipleQVCInitialization(self.src_path)

        qvc_file_name = u"qvc_" + self.commit_sha + u".py"
        qvc_path = self.qvc_path = join(self.build_path, qvc_file_name)

        qemu_heuristic_hash = calculate_qh_hash()

        yield True

        if not isfile(qvc_path):
            yield self.co_check_untracked_files()

            self.qvc = QemuVersionCache()

            # make new QVC active and begin construction
            prev_qvc = self.qvc.use()
            for path in self.include_paths:
                yield Header.co_build_inclusions(path)

            self.qvc.list_headers = self.qvc.stc.create_header_db()

            yield self.co_check_modified_files()

            yield self.co_gen_device_tree()

            # gen version description
            yield self.qvc.co_computing_parameters(self.repo)
            self.qvc.version_desc[QVD_QH_HASH] = qemu_heuristic_hash

            # Search for PCI Ids
            PCIClassification.build()

            yield True

            PyGenerator().serialize(open(qvc_path, "wb"), self.qvc)
        else:
            self.load_cache()
            # make just loaded QVC active
            prev_qvc = self.qvc.use()

            if self.qvc.list_headers is not None:
                yield True

                self.qvc.stc.load_header_db(self.qvc.list_headers)

            yield True

            # verify that the version_desc is not outdated
            is_outdated = False
            try:
                checksum = self.qvc.version_desc[QVD_QH_HASH]
            except KeyError:
                is_outdated = True
            else:
                if not checksum == qemu_heuristic_hash:
                    is_outdated = True
            if is_outdated:
                remove_file(qvc_path)
                yield self.qvc.co_computing_parameters(self.repo)
                self.qvc.version_desc[QVD_QH_HASH] = qemu_heuristic_hash
                PyGenerator().serialize(open(qvc_path, "wb"), self.qvc)

        yield True

        # set Qemu version heuristics according to current version
        initialize_version(self.qvc.version_desc)

        yield True

        # initialize Qemu types in QVC
        get_vp()["qemu types definer"]()
        get_vp()["msi_init type definer"]()

        if prev_qvc is not None:
            prev_qvc.use()

        self.qvc_is_ready = True