Example #1
0
def import_modules():
    """Import all modules and returns them as a list"""
    result = []
    log.info("Importing modules...")
    for dirName, subdirList, fileList in os.walk(MOD_DIR, followlinks=True):
        for fname in fileList:
            if fname.endswith('.tests.ps1'):
                # This is done because PowerSploit contains tests that we
                # don't want
                continue
            _, ext = os.path.splitext(fname)
            if ext.lower() not in ['.exe', '.ps1']:
                continue
            path = os.path.join(dirName, fname)
            with open(path, "br") as f:
                buffer = f.read(2048)
                file_type = magic.from_buffer(buffer)
                mime = magic.from_buffer(buffer, mime=True)
                mod_type = get_module_type(fname, file_type, mime)
                if not mod_type:
                    continue
            log.debug("Imported module (%s): %s" % (path, mod_type))
            module = Module(
                path.replace(os.path.join(BASE_DIR, 'modules'), ''),
                path,
                mod_type,
                file_type,
            )
            result.append(module)

    for i, m in enumerate(result):
        m.n = i

    return result
Example #2
0
def decrypt_hive(loot_id):
    """Decrypt the registry hive and store result in DB"""

    loot = get_loot_entry(loot_id)

    try:
        from pypykatz.registry.offline_parser import OffineRegistry

        o = OffineRegistry()
        try:
            o = o.from_files(
                loot.system_file,
                security_path=loot.security_file,
                sam_path=loot.sam_file,
                software_path=loot.software_file,
            )
        except TypeError:  # 'system' is not here yet, no biggie
            return None
        loot.hive = o.to_json()
        _db.session.commit()
        log.debug("Hive decrypted - %s" % loot_id)

    except ImportError as e:
        log.error("You have unmet dependencies, loot could not be processed")
        log.exception(e)
Example #3
0
 def read_shell_packet(self, s):
     """Deserialize byte string and instantiate ShellPacket"""
     header = s.recv(4, socket.MSG_PEEK)
     if not header:
         return None
     if s == self.rsock:
         header = encrypt(header, self.key)
     packet_length = struct.unpack('<i', header)[0]
     body = b''
     while len(body) < packet_length:
         body += s.recv(packet_length - len(body))
     if s == self.rsock:
         body = encrypt(body, self.key)
     p = ShellPacket(body)
     if p['msg_type'] == "PONG":
         log.debug("%s - Pong" % (self.details["id"]))
     elif p['msg_type'] == "KILL" and p['data'] == "confirm":
         log.info("%s - Shell has died" % (self.details["id"]))
         self.active = False
         self.unset_lsock()
         return p
     self.append_to_log(p)
     if s == self.rsock:
         sender = "reverse shell"
         self.t_sign_of_life = dt.now()
         if self.lsock:
             self.deliver(p, self.lsock)
     else:
         sender = "local shell"
         self.deliver(p, self.rsock)
     host, port = s.getpeername()
     log.debug("%s - %s - From %s: %s" %
               (host, self.details["id"] if "id" in self.details else "?",
                sender, p))
     return p
Example #4
0
def get_secret_key():
    key = get_setting("secret_key")
    if not key:
        key = generate_random_key(128)
        set_setting("secret_key", key)
    else:
        log.debug("Loaded secret key: %s", key)
    return key
Example #5
0
 def unset_lsock(self):
     if not self.lsock:
         return None
     self.queue.pop(self.lsock)
     self.read_socks.remove(self.lsock)
     if self.lsock in self.write_socks:
         self.write_socks.remove(self.lsock)
     self.lsock.close()
     self.lsock = None
     log.debug("%s - Connection to local shell closed" %
               (self.details["id"]))
Example #6
0
 def get_shell_hello(self):
     r, _, _ = select.select([self.rsock], [], [])
     firstbytes = r[0].recv(8, socket.MSG_PEEK)
     firstbytes = encrypt(firstbytes, self.key)
     if firstbytes == self.SHELL_HELLO:
         log.debug("Shell hello received")
         r[0].recv(8)
         p = self.read_shell_packet(self.rsock)
         self.shell_type = 'smart'
         self.details.update(p["data"])
         return p
     else:
         log.debug("No shell hello found")
         return False
Example #7
0
 def __init__(self, body, packet_type=T_BSON):
     if packet_type == T_BSON:
         try:
             self._dict = bson.loads(body)
         except Exception:
             log.error("Could not decipher shell packet")
             log.debug(body)
             self._dict = {}
     elif packet_type == T_DICT:
         self._dict = body
     else:
         raise Exception
     if "data" not in self._dict:
         self._dict["data"] = ""
     self.delivered = False
Example #8
0
def save_loot(file, loot_id, encrypted=False):
    """Process the loot file"""

    filename = save_file(file, dir=LOOT_DIR, encrypted=encrypted)
    loot_type = get_loot_type(filename)
    log.debug("Saving %s [%s]" % (filename, loot_type))
    if loot_type == "DMP":
        from pypykatz.pypykatz import pypykatz
        mimi = pypykatz.parse_minidump_file(filename)
        creds = [json.loads(v.to_json())
                 for _, v in mimi.logon_sessions.items()]
        store_minidump(loot_id, json.dumps(creds), filename)
    elif loot_type == "SYSINFO":
        add_sysinfo(loot_id, filename)
    else:  # registry hive
        add_hive(loot_id, loot_type, filename)
Example #9
0
def decrypt_hive(loot_id):
    """Decrypt the registry hive and store result in DB"""

    loot = get_loot_entry(loot_id)

    from pypykatz.registry.offline_parser import OffineRegistry

    o = OffineRegistry()
    try:
        o = o.from_files(
            loot.system_file,
            security_path=loot.security_file,
            sam_path=loot.sam_file,
            software_path=loot.software_file,
        )
    except TypeError:  # 'system' is not here yet, no biggie
        return None
    loot.hive = o.to_json()
    _db.session.commit()
    log.debug("Hive decrypted - %s" % loot_id)
Example #10
0
 def getChild(self, path, request):
     path = path.decode()
     log.debug("%s - %s" % (request.client.host, path))
     resource = path.split('/')[0].encode()
     path = '/'.join(path.split('/')[1:])
     host = '127.0.0.1'
     x_forwarded_for = request.client.host
     x_for_host = request.requestHeaders.getRawHeaders('host')
     x_for_host = x_for_host[0].split(':')[0]
     x_for_port = request.host.port
     if x_for_port == args.SSL_PORT:
         x_for_proto = "https"
     else:
         x_for_proto = "http"
     for header in [
         ('X-Forwarded-For', x_forwarded_for),
         ('X-Forwarded-Host', x_for_host),
         ('X-Forwarded-Port', str(x_for_port)),
         ('X-Forwarded-Proto', x_for_proto),
     ]:
         request.requestHeaders.addRawHeader(*header)
     path = path.encode()
     if resource.startswith(b"webdav"):
         new_path = b'/%s' % (resource, )
         if path:
             new_path += b'/%s' % path
         log.debug("Forwarding request to WebDAV server: %s" %
                   path.decode())
         return ReverseProxyResource(host, args.WEBDAV_PORT, new_path)
     else:
         log.debug("Forwarding request to Flask server")
         new_path = b'/%s' % (resource, )
         if path:
             new_path += b'/%s' % path
         return ReverseProxyResource(host, args.FLASK_PORT, new_path)
Example #11
0
def generate_random_key(n):
    key = ''.join(random.choice(string.ascii_letters) for _ in range(n))
    log.debug("Generated a secret key: %s", key)
    return key
Example #12
0
def test_connect():
    log.debug("Websockt client connected")
Example #13
0
 def ping(self, s):
     now = dt.now()
     if (now-self.t_sign_of_life).total_seconds() > 10:
         log.debug("%s - Ping" % (self.details["id"]))
         p = ShellPacket({"msg_type": "PING", "data": ""}, T_DICT)
         self.write_shell_packet(p, s)