Ejemplo n.º 1
0
    def __init__(self, password='', proxies=None, username='', email='', cred_root='data'):
        self.email = email
        self.username = username
        self.password = password
        self.req_builder = RequestBuilder()
        self.bookmark_manager = BookmarkManager()
        self.http = requests.session()
        self.proxies = proxies

        data_path = os.path.join(cred_root, self.email) + os.sep
        if not os.path.isdir(data_path):
            os.makedirs(data_path)

        self.registry = Registry('{}registry.dat'.format(data_path))

        cookies = self.registry.get(Registry.Key.COOKIES)
        if cookies is not None:
            self.http.cookies.update(cookies)
    def ProcessPlugin(self):

        env = Environment(keep_trailing_newline=True,
                          loader=PackageLoader('regparse', 'templates'))

        lastvisited = [
            "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU",
            "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU",
            "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRULegacy"
        ]

        for hive in self.hives:
            for k in lastvisited:
                try:
                    lvmru = Registry.Registry(hive).open(k)
                    key = lvmru.name()
                    last_write = lvmru.timestamp()
                    mruorder = lvmru.value("MRUListEx").value()
                    for entry in struct.unpack("%dI" % (len(mruorder) / 4),
                                               mruorder):
                        for values in lvmru.values():
                            if str(values.name()) == str(entry):
                                value = values.name()
                                data = (values.value().split('\x00\x00')[0])
                                if self.format_file is not None:
                                    with open(self.format_file[0], "rb") as f:
                                        template = env.from_string(f.read())
                                        sys.stdout.write(template.render(last_write=last_write, \
                                                                            key=key, \
                                                                            mruorder=mruorder, \
                                                                            value=value, \
                                                                            data=data) + "\n")
                                elif self.format is not None:
                                    template = Environment().from_string(
                                        self.format[0])
                                    sys.stdout.write(template.render(last_write=last_write, \
                                                                        key=key, \
                                                                        mruorder=mruorder, \
                                                                        value=value, \
                                                                        data=data) + "\n")

                except (Registry.RegistryKeyNotFoundException,
                        Registry.RegistryValueNotFoundException):
                    continue
Ejemplo n.º 3
0
def loadHives(inputfldr):
    """
    Create Registry objects for all available hives in the input directory.
    Returns a tuple containing the status code of the hive, the Registry object,
    and the relative path to the loaded file. Status codes: 0 = not found,
    1 = ok, 2 = failed to parse. Catches un-handled exception in Registry module
    which occurs when attempting to read a file < 4 bytes long.
    """
    hivesdict = dict()
    hivenames = ['SYSTEM', 'SOFTWARE', 'SECURITY', 'SAM', 'NTUSER.DAT']

    for hive in hivenames:
        for file in os.listdir(inputfldr):
            if (file.upper() == hive):
                try:
                    hivesdict[hive] = (
                        1,
                        Registry.Registry(os.path.join(inputfldr, file)),
                        os.path.join(inputfldr, file),
                    )
                except Registry.RegistryParse.ParseException:
                    logging.error("Cannot parse registry file: " +
                                  os.path.join(inputfldr, file) +
                                  ". File may be corrupt.")
                    hivesdict[hive] = (
                        3,
                        None,
                        os.path.join(inputfldr, file),
                    )
                except:
                    logging.error(
                        "Cannot parse registry file: " +
                        os.path.join(inputfldr, file) +
                        ". File may be corrupt - check the filesize is non-zero."
                    )
                    hivesdict[hive] = (
                        3,
                        None,
                        os.path.join(inputfldr, file),
                    )
        if not hive in hivesdict:
            hivesdict[hive] = (0, None, "NULL")

    return hivesdict
Ejemplo n.º 4
0
def parseHive(file, outputdirectory, args, count):
    r = Registry.Registry(file)
    oldstyle = False
    newstyle = False
    entries = []
    entries_app = []
    entries_file = []

    # for old hive construction
    try:
        entries = parse_execution_entries(r, "Root\\File", FIELDS)
    except NotAnAmcacheHive:
        g_logger.info("Root\\File key not found")
        pass

    if len(entries) != 0:
        with open(os.path.join(outputdirectory, "amcache_output.csv"),
                  "ab") as pf:
            standardOutput(entries, args, file, pf, count, FIELDS)
        oldstyle = True

    # for new windows10 hive construction
    try:
        entries_app = parse_execution_entries(r, "Root\\InventoryApplication",
                                              FIELDS_INVENTORY_APP)
        entries_file = parse_execution_entries(
            r, "Root\\InventoryApplicationFile", FIELDS_INVENTORY_FILE)
        entries_update1709 = mergeRegistoryInfomation(entries_app,
                                                      entries_file)
    except NotAnAmcacheHive:
        g_logger.info(
            "Root\\InventoryApplication or Root\\InventoryApplicationFile  key not found"
        )
        pass

    if len(entries_app) != 0 and len(entries_file) != 0:
        with open(
                os.path.join(outputdirectory, "amcache_inventory_output.csv"),
                "ab") as pf:
            standardOutput(entries_update1709, args, file, pf, count,
                           FIELDS_UPDATE1709)
        newstyle = True

    return {"old": oldstyle, "new": newstyle}
Ejemplo n.º 5
0
    def getUserAssist(self, hive):
        userassist = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\UserAssist"

        #Giuds for the various Operating Systems
        guids = ["{CEBFF5CD-ACE2-4F4F-9178-9926F41749EA}",
                 "{F4E57C4B-2036-45F0-A9AB-443BCFE33D9F}",
                 "{5E6AB780-7743-11CF-A12B-00AA004AE837}",
                 "{75048700-EF1F-11D0-9888-006097DEACF9}"
                 ]
        userassist_entries = []
        
        #Reference: registrydecoder.googlecode.com/svn/trunk/templates/template_files/user_assist.py
        for g in guids:
            try:
                for sks in Registry.Registry(hive).open(userassist).subkey(g).subkey("Count").values():
                    #Windows 7
                    if len(sks.value()) > 16:# 68:
                        runcount = struct.unpack("I", sks.value()[4:8])[0]
                        date = struct.unpack("Q", sks.value()[60:68])[0]
                        last_write = Registry.Registry(hive).open(userassist).subkey(g).subkey("Count").timestamp()
                        key = Registry.Registry(hive).open(userassist).subkey(g).name()
                        skey = Registry.Registry(hive).open(userassist).subkey(g).subkey("Count").name()
                        sub_key = key + skey
                        windate = self.convert_wintime(date)
                        data = codecs.decode(sks.name(), 'rot_13')
                        
                        userassist_entries.append((last_write, sub_key, runcount, windate, data))
                    
                    #Windows XP
                    elif len(sks.value()) == 16:
                        last_write = Registry.Registry(hive).open(userassist).subkey(g).subkey("Count").timestamp()
                        key = Registry.Registry(hive).open(userassist).subkey(g).name()
                        skey = Registry.Registry(hive).open(userassist).subkey(g).subkey("Count").name()
                        sub_key = key + skey                        
                        session, runcount, date = struct.unpack("IIQ", sks.value())
                        runcount -= 5
                        windate = self.convert_wintime(date)
                        data = codecs.decode(sks.name(), 'rot_13')
                        
                        #print last_write, sub_key, runcount, windate, data
                        userassist_entries.append((last_write, sub_key, runcount, windate, data))
        
            except Registry.RegistryKeyNotFoundException as e:
                continue
            
        return(userassist_entries)
Ejemplo n.º 6
0
def find_vol_guids_in_SYSTEM(SYSTEM_file):
    guid_list = list()
    registryBase_system_vol_guids = 'MountedDevices'

    try:
        Hive_SYSTEM = Registry.Registry(SYSTEM_file)
    except Registry.RegistryParse.ParseException as err:
        print('[!] find_vol_guids_in_SYSTEM() Error in parsing file: {}'.
              format(SYSTEM_file))
        print('[!] find_vol_guids_in_SYSTEM() Error given: {}'.format(err))
        return False

    SYSTEM_vol_root = Hive_SYSTEM.open(registryBase_system_vol_guids)
    for root_values in SYSTEM_vol_root.values():
        guid_system = root_values.name().strip('\\??\\Volume{').strip(
            '}').strip('#{')
        if not guid_system.startswith('DosDevices'):
            guid_list.append(guid_system)
    return guid_list
Ejemplo n.º 7
0
def test(filename):
    r = Registry.Registry(filename)
    k = r.open("Local Settings\\Software\\Microsoft\\Windows\\Shell\\BagMRU\\1\\0\\0")
    v = k.value("0")

    print hex_dump(v.value())

    l = SHITEMLIST(v.value(), 0, False)
    for index, item in enumerate(l.items()):
        print "item:", index
        print "type:", item.__class__.__name__
        print "name:", item.name()

        # its a SHITEM_FILEENTRY
        print "short name:", item.short_name()
        print "off long name:", item._off_long_name
        print "off long name size:", item._off_long_name_size
        print "long name size:", hex(item.long_name_size())
        print "mtime:", item.m_date()
Ejemplo n.º 8
0
 def parse_hive(
     self,
     registry_file_info: lib_data_structures.DataStructRegistryFileInfo
 ) -> [lib_data_structures.DataStructRegistryEntry]:
     """
     >>> fingerprint_registry = FingerPrintRegistry()
     >>> registry_file_info = lib_data_structures.DataStructRegistryFileInfo()
     >>> registry_file_info.hive_name = 'HKLM\SAM'
     >>> registry_file_info.filename = './testfiles_source/test_registry_hklm_sam.hive'
     >>> fingerprint_registry.parse_hive(registry_file_info=registry_file_info)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
     [<lib_data_structures.DataStructRegistryEntry object at ...>, ...]
     """
     reg = Registry.Registry(registry_file_info.filename)
     key_root = reg.root()
     logger.info('registry key root : {}'.format(key_root))
     logger.info('parsing registry {}'.format(registry_file_info.hive_name))
     l_reg_entries = self.get_registry_entries(
         key=key_root, registry_file_info=registry_file_info)
     return l_reg_entries
Ejemplo n.º 9
0
    def processSysinternals(self, hive):

        sysinternals_list = []

        try:
            for sks in Registry.Registry(hive).open(
                    "Software\\Sysinternals").subkeys():
                for v in sks.values():
                    if "EulaAccepted" in v.name():
                        if v.value() == 1:
                            last_write = sks.timestamp()
                            key_name = sks.name()

                            sysinternals_list.append([last_write, key_name])

        except Registry.RegistryKeyNotFoundException as e:
            pass

        return (sysinternals_list)
Ejemplo n.º 10
0
    def ProcessPlugin(self):

        env = Environment(keep_trailing_newline=True,
                          loader=PackageLoader('regparse', 'templates'))

        winlogon_list = []

        for hive in self.hives:
            key = Registry.Registry(hive).open(
                "Microsoft\\Windows NT\\CurrentVersion\\Winlogon")
            last_write = key.timestamp()

            try:
                winlogon_list.append(
                    (key.value("Shell").name(), key.value("Shell").value()))
                winlogon_list.append((key.value("Userinit").name(),
                                      key.value("Userinit").value()))
                winlogon_list.append((key.value("Taskman").name(),
                                      key.value("Taskman").value()))

            except Registry.RegistryValueNotFoundException:
                continue

        for entry in winlogon_list:
            last_write
            key_name = key.name()
            value = entry[0]
            data = entry[1]

            if self.format is not None:
                template = Environment().from_string(self.format[0])
                sys.stdout.write(template.render(last_write=last_write, \
                                                 key_name=key_name, \
                                                 value=value, \
                                                 data=data) + "\n")

            elif self.format_file is not None:
                with open(self.format_file[0], "rb") as f:
                    template = env.from_string(f.read())
                    sys.stdout.write(template.render(last_write=last_write, \
                                                 key_name=key_name, \
                                                 value=value, \
                                                 data=data) + "\n")
Ejemplo n.º 11
0
Archivo: upp.py Proyecto: azeam/upp
def _get_pp_data_from_registry(reg_file_path):
    reg_path = 'HKLM\\SYSTEM\\' + REG_KEY + ':' + REG_KEY_VAL
    tmp_pp_file = tempfile.NamedTemporaryFile(prefix='reg_pp_table_',
                                              delete=False)
    msg = ' Soft PowerPlay data from {}\n  key:value > {}\n'
    try:
        reg = Registry.Registry(reg_file_path)
        key = reg.open(REG_KEY)
        data_type = key.value(REG_KEY_VAL).value_type_str()
        registry_data = key.value(REG_KEY_VAL).raw_data()
    except Exception as e:
        print(('ERROR: Can not get' + msg).format(reg_file_path, reg_path))
        print(e)
        return None
    print(('Successfully loaded' + msg).format(reg_file_path, reg_path))
    decode._write_pp_tables_file(tmp_pp_file.name, registry_data)
    tmp_pp_file.close()

    return tmp_pp_file.name
Ejemplo n.º 12
0
    def ProcessPlugin(self):

        env = Environment(keep_trailing_newline=True,
                          loader=PackageLoader('regparse', 'templates'))

        for hive in self.hives:
            try:
                runmru = Registry.Registry(hive).open(
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU"
                )
            except Registry.RegistryKeyNotFoundException as e:
                pass
            key = runmru.name()
            last_write = runmru.timestamp()
            try:
                mruorder = runmru.value("MRUList").value()
            except Registry.RegistryParse.RegistryStructureDoesNotExist as error:
                print "There are no MRUList values. Exiting."
                exit(0)
            for entry in list(mruorder):
                for vals in runmru.values():
                    if entry == vals.name():
                        value = vals.name()
                        data = vals.value()
                    else:
                        continue

                    if self.format_file is not None:
                        with open(self.format_file[0], "rb") as f:
                            template = env.from_string(f.read())
                            sys.stdout.write(template.render(last_write=last_write, \
                                                             key=key, \
                                                             mruorder=mruorder, \
                                                             value=value, \
                                                             data=data) + "\n")
                    elif self.format is not None:
                        template = Environment().from_string(self.format[0])
                        sys.stdout.write(template.render(last_write=last_write, \
                                                             key=key, \
                                                             mruorder=mruorder, \
                                                             value=value, \
                                                             data=data) + "\n")
Ejemplo n.º 13
0
    def get_syskey(self, system):
        """Returns the syskey value after decryption from the registry values.

        system argument is the full path to the SYSTEM registry file (usually
        located under %WINDIR%\\system32\\config\\ directory.

        """
        with open(system, 'rb') as f:
            r = Registry.Registry(f)
            cs = r.open("Select").value("Current").value()
            r2 = r.open("ControlSet%03d\\Control\\Lsa" % cs)
            syskey = "".join([
                r2.subkey(x)._nkrecord.classname()
                for x in ('JD', 'Skew1', 'GBG', 'Data')
            ])
        syskey = syskey.encode("ascii").decode("hex")
        transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]
        self.syskey = ""
        for i in xrange(len(syskey)):
            self.syskey += syskey[transforms[i]]
        return self.syskey
Ejemplo n.º 14
0
def ReadSingleReg(db, cursor, Hive, TableName, Source, Key, Category, stateStr,
                  KeyStr):
    reg = Registry.Registry(Hive)

    try:
        key = reg.open(Source)

    except Registry.RegistryKeyNotFoundException:
        print "Couldn't find %s..." % Source
        pass
    try:
        k = reg.open(Source)
        Source = "From: {} and registry path: {}".format(Hive, Source)
        v = k.value(Key)
        cursor.execute(
            '''INSERT INTO %s  (Name, Value, Category, State, KeyStr, RecString, KeyParent, KeyTimeStamp,Source) VALUES(?,?,?,?,?,?,?,?,?)'''
            % TableName, (v.name(), v.value(), Category, stateStr, KeyStr,
                          None, None, key.timestamp(), Source))

    except:
        print "Error in ReadSingleReg"
Ejemplo n.º 15
0
def env_settings(sys_reg):
    """
    Environment Settings
    """
    results = []
    sys_architecture = []
    registry = Registry.Registry(sys_reg)    
    print(("=" * 51) + "\n[+] Environment Settings\n" + ("=" * 51))
    key = registry.open("ControlSet00%s\\Control\\Session Manager\\Environment" % control_set_check(sys_reg))    
    for v in key.values():
        if v.name() == "PROCESSOR_ARCHITECTURE":
            sys_architecture = v.value()
            results.append("[-] Architecture.....: " + str(v.value()))            
        if v.name() == "NUMBER_OF_PROCESSORS":
            results.append("[-] Processors.......: " + str(v.value()))
        if v.name() == "TEMP":
            results.append("[-] Temp path........: " + str(v.value()))
        if v.name() == "TMP":
            results.append("[-] Tmp path.........: " + str(v.value()))                                                                             
    for line in results:
        print(line)
Ejemplo n.º 16
0
def main():
    if len(sys.argv) != 2:
        print(usage())
        sys.exit(-1)
    try:
        registry = Registry.Registry(sys.argv[1])
        select = registry.open("Select")
        current = select.value("Current").value()
        key = registry.open(
            "ControlSet00%d\\Control\\ComputerName\\ComputerName" % (current))
    except:
        print("Unable to open registry hive or key")
        sys.exit(-1)
    for v in key.values():
        try:
            if v.name() == "ComputerName":
                compname = v.value()
                print('%s' % (compname))
        except:
            print("Computer Name Not Found!")
            print(usage())
Ejemplo n.º 17
0
    def get_lsa_secrets(self, security, system):
        """Retrieves and decrypts LSA secrets from the registry.
        security and system arguments are the full path to the corresponding
        registry files.
        This function automatically calls self.get_syskey() and
        self.get_lsa_key() functions prior to the secrets retrieval.

        Returns a dictionary of secrets.

        """
        self.get_syskey(system)
        currentKey = self.get_lsa_key(security)
        self.lsa_secrets = {}
        with open(security, 'rb') as f:
            r = Registry.Registry(f)
            r2 = r.open('Policy\\Secrets')
            for i in r2.subkeys():
                self.lsa_secrets[i.name()] = {}
                for j in i.subkeys():
                    self.lsa_secrets[i.name()][j.name()] = j.value(
                        '(default)').value()
        for k, v in list(self.lsa_secrets.items()):
            for s in ['CurrVal', 'OldVal']:
                if v[s] != b'':
                    if self.policy['value'] > 1.09:
                        # NT6
                        self.lsa_secrets[k][s] = crypto.decrypt_lsa_secret(
                            v[s], self.lsakeys)
                    else:
                        self.lsa_secrets[k][s] = crypto.SystemFunction005(
                            v[s][0xc:], currentKey)
            for s in ['OupdTime', 'CupdTime']:
                #print(int(self.lsa_secrets[k][s].hex(),16))
                #if self.lsa_secrets[k][s] > 0:
                if not self.lsa_secrets[k][s] == b'':
                    t = eater.Eater(self.lsa_secrets[k][s])
                    self.lsa_secrets[k][s] = int((t.eat('Q') / 10000000) -
                                                 11644473600)
        #print(self.lsa_secrets)
        return self.lsa_secrets
Ejemplo n.º 18
0
    def get_lsa_key(self, security):
        """Returns and decrypts the LSA secret key for "CurrentControlSet".
        It is stored under Policy\\PolSecretEncryptionKey.

        security is the full path the the SECURITY registry file (usually
        located under %WINDIR%\\system32\\config\\ directory.

        To decrypt the LSA key, syskey is required. Thus you must first call
        self.get_syskey() if it has not been previously done.

        """
        lsakey = ""
        if self.syskey is None:
            raise ValueError(
                "Must provide syskey or call get_syskey() method first")
        with open(security, 'rb') as f:
            r = Registry.Registry(f)
            rev = eater.Eater(
                r.open("Policy\\PolRevision").value("(default)").value())
            self.policy["minor"] = rev.eat("H")
            self.policy["major"] = rev.eat("H")
            self.policy["value"] = float(
                "%d.%02d" % (self.policy["major"], self.policy["minor"]))
            if self.policy["value"] > 1.09:
                # NT6
                r2 = r.open("Policy\\PolEKList")
                lsakey = r2.value("(default)").value()
            else:
                # NT5
                r2 = r.open("Policy\\PolSecretEncryptionKey")
                lsakey = r2.value("(default)").value()
        rv = None
        if self.policy["value"] > 1.09:
            currentKey, self.lsakeys = crypto.decrypt_lsa_key_nt6(
                lsakey, self.syskey)
            rv = self.lsakeys[currentKey]["key"]
        else:
            self.lsakeys = crypto.decrypt_lsa_key_nt5(lsakey, self.syskey)
            rv = self.lsakeys[1]
        return rv
    def ProcessPlugin(self):

        env = Environment(keep_trailing_newline=True,
                          loader=PackageLoader('regparse', 'templates'))

        for hive in self.hives:
            try:
                wordwheel = Registry.Registry(hive).open(
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\WordWheelQuery"
                )

                key = wordwheel.name()
                last_write = wordwheel.timestamp()
                mruorder = wordwheel.value("MRUListEx").value()
                for entry in struct.unpack("%dI" % (len(mruorder) / 4),
                                           mruorder):
                    for words in wordwheel.values():
                        if words.name() == str(entry):
                            value = words.name()
                            data = words.value()
                        else:
                            continue

                        if self.format_file is not None:
                            with open(self.format_file[0], "rb") as f:
                                template = env.from_string(f.read())
                                sys.stdout.write(template.render(last_write=last_write, \
                                                                 key=key, \
                                                                 value=value, \
                                                                 data=data) + "\n")
                        elif self.format is not None:
                            template = Environment().from_string(
                                self.format[0])
                            sys.stdout.write(template.render(last_write=last_write, \
                                                             key=key, \
                                                             value=value, \
                                                             data=data) + "\n")

            except Registry.RegistryKeyNotFoundException as e:
                pass
Ejemplo n.º 20
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser(
        description="Parse Shellbag entries from a Windows Registry.")
    parser.add_argument("-v",
                        action="store_true",
                        dest="vverbose",
                        help="Print debugging information while parsing")
    parser.add_argument("file",
                        nargs="+",
                        help="Windows Registry hive file(s)")
    parser.add_argument(
        "-o",
        choices=["csv", "bodyfile"],
        dest="fmt",
        default="bodyfile",
        help="Output format: csv or bodyfile; default is bodyfile")
    args = parser.parse_args(argv[1:])

    for f in args.file:
        registry = Registry.Registry(f)

        parsed_shellbags = get_all_shellbags(registry)

        if args.fmt == "csv":
            print_shellbag_csv(parsed_shellbags, f)
        elif args.fmt == "bodyfile":
            for shellbag in parsed_shellbags:
                print_shellbag_bodyfile(
                    shellbag["mtime"],
                    shellbag["atime"],
                    shellbag["crtime"],
                    shellbag["path"],
                    fail_note="Failed to parse entry name from: " +
                    shellbag["source"])
        else:
            print "Error: Unsupported output format"
Ejemplo n.º 21
0
def main():
    import sys
    hive = sys.argv[1]

    import hashlib
    m = hashlib.md5()
    with open(hive, 'rb') as f:
        m.update(f.read())
    if m.hexdigest() != "26cb15876ceb4fd64476223c2bf1c8e3":
        print "Please use the SYSTEM hive with MD5 26cb15876ceb4fd64476223c2bf1c8e3"
        sys.exit(-1)

    r = Registry.Registry(hive)
    k = r.open("ControlSet001\\Control\\TimeZoneInformation")
    v = k.value("TimeZoneKeyName")
    if v.value() == "Pacific Standard Time":
        print "Passed."
    else:
        print "Failed."
        print "Expected: Pacific Standard Time"
        print "Got: %s (length: %d)" % (v.value(), len(v.value()))
    sys.exit(0)
Ejemplo n.º 22
0
def registry2json(file_name):
    reg_json = dict()
    def _value(key):
        res = {"data": "", "timestamp": key.timestamp().strftime("%Y-%m-%d %H:%M:%S")}
        vals = dict()
        for value in [v for v in key.values() if v.value_type() == Registry.RegSZ or v.value_type() == Registry.RegExpandSZ]:
            vals[value.name()] = value.value()
        res["data"] = vals
        return res

    def _key(key, depth=0):
        vals = _value(key)
        if len(vals["data"]) != 0:
            reg_json[key.path()] = vals
        for subkey in key.subkeys():
            _key(subkey, depth + 1)

    reg = Registry.Registry(file_name)
    _key(reg.root())

    with open("{}.json".format(file_name), "w") as f:
        json.dump(reg_json, f, indent=4)
Ejemplo n.º 23
0
def main():
    parser = argparse.ArgumentParser(
        description='Parse Registry hive looking for malicious Binary data.')
    parser.add_argument('--hive', help='Path to Hive.')
    parser.add_argument('--size', help='Size in bytes.')
    parser.add_argument('--write',
                        help='Write the binary values out to a directory.')
    parser.add_argument('--virustotal', help='Query VT with data hashes.')
    args = parser.parse_args()

    if args.virustotal:
        api_key = args.virustotal
    else:
        #You can specify a default API key here vs. None.
        api_key = None

    if args.write:
        try:
            reg = Registry.Registry(args.hive).root()
            getBinaryEntries(reg, int(args.size), args.write, api_key, depth=0)
        except TypeError:
            pass
Ejemplo n.º 24
0
def startShellbags(Hive, db, cursor):
    registry = Registry.Registry(Hive)

    parsed_shellbags = get_all_shellbags(registry)

    cursor.execute(
        '''CREATE TABLE ShellbagsTable(Id INTEGER PRIMARY KEY, Path TEXT, Modified TEXT, Accessed TEXT, Created TEXT, Source TEXT)'''
    )
    db.commit()

    # print_shellbag_csv(parsed_shellbags,Hive)
    # elif args.fmt == "bodyfile":
    for shellbag in parsed_shellbags:
        # print_shellbag_bodyfile(shellbag["mtime"],
        #                            shellbag["atime"],
        #                           shellbag["crtime"],
        #                          shellbag["path"],
        #                         fail_note="Failed to parse entry name from: " + shellbag["source"])
        if str(shellbag["atime"]) != "0001-01-01 00:00:00":
            atime = shellbag["atime"]
        else:
            atime = ''
        if str(shellbag["mtime"]) != "0001-01-01 00:00:00":
            mtime = shellbag["mtime"]
        else:
            mtime = ''
        if str(shellbag["crtime"]) != "0001-01-01 00:00:00":
            crtime = shellbag["crtime"]
        else:
            crtime = ''
        path = shellbag["path"] + ""
        source = shellbag["source"]
        cursor.execute(
            '''INSERT INTO ShellbagsTable(Path, Modified, Accessed, Created, Source) VALUES(?,?,?,?,?)''',
            [path, str(mtime),
             str(atime),
             str(crtime),
             str(source)])
        db.commit()
Ejemplo n.º 25
0
def main():
    parser = argparse.ArgumentParser(
        description="Timeline Windows Registry key timestamps")
    parser.add_argument("--bodyfile",
                        action="store_true",
                        help="Output in the Bodyfile 3 format")
    parser.add_argument("registry_hives",
                        type=str,
                        nargs="+",
                        help="Path to the Windows Registry hive to process")
    args = parser.parse_args()

    def rec(key, visitor):
        try:
            visitor(key.timestamp(), key.path())
        except ValueError:
            pass
        for subkey in key.subkeys():
            rec(subkey, visitor)

    for path in args.registry_hives:
        reg = Registry.Registry(path)

        if args.bodyfile:
            hive = guess_hive_name(path)

            def visitor(timestamp, path):
                try:
                    print("0|[Registry %s] %s|0|0|0|0|0|%s|0|0|0" % \
                      (hive, path, int(calendar.timegm(timestamp.timetuple()))))
                except UnicodeDecodeError:
                    pass

            rec(reg.root(), visitor)
        else:
            items = []
            rec(reg.root(), lambda a, b: items.append((a, b)))
            for i in sorted(items, key=lambda x: x[0]):
                print("%s\t%s" % i)
Ejemplo n.º 26
0
def tz_settings(sys_reg):
    """
    Time Zone Settings
    """
    results = []
    current_control_set = "ControlSet00%s" % control_set_check(sys_reg)
    k = "%s\\Control\\TimeZoneInformation" % current_control_set
    registry = Registry.Registry(sys_reg)
    key = registry.open(k)
    results.append(("=" * 51) + "\nTime Zone Settings\n" + ("=" * 51))
    print("[-] Checking %s based on 'Select' settings" % current_control_set)
    results.append("[+] %s" % k)
    results.append("---------------------------------------")
    for v in key.values():
        if v.name() == "ActiveTimeBias":
            results.append("[-] ActiveTimeBias: %s" % v.value())
        if v.name() == "Bias":
            results.append("[-] Bias...: %s" % v.value())
        if v.name() == "TimeZoneKeyName":
            results.append("[-] Time Zone Name...: %s" % str(v.value()))

    return results
    def get_lsa_secrets(self, security, system):
        """
		Retrieves and decrypts LSA secrets from the registry.
		security and system arguments are the full path to the corresponding registry files.
		This function automatically calls self.get_syskey() and self.get_lsa_key() functions prior to the secrets retrieval.

		Returns a dictionary of secrets.
		"""
        self.syskey = self.get_syskey(system)
        currentKey = self.get_lsa_key(security)
        lsa_secrets = {}

        with open(security, 'rb') as f:
            r = Registry.Registry(f)

        r2 = r.open('Policy\\Secrets')
        for i in r2.subkeys():
            lsa_secrets[i.name()] = {}
            for j in i.subkeys():
                lsa_secrets[i.name()][j.name()] = j.value('(default)').value()

        for k, v in lsa_secrets.iteritems():
            for s in ['CurrVal', 'OldVal']:
                if v[s] != '':
                    if self.policy > 1.09:
                        # NT6
                        lsa_secrets[k][s] = crypto.decrypt_lsa_secret(
                            v[s], self.lsakeys)
                    else:
                        lsa_secrets[k][s] = crypto.SystemFunction005(
                            v[s][0xc:], currentKey)

            for s in ['OupdTime', 'CupdTime']:
                if lsa_secrets[k][s] > 0:
                    lsa_secrets[k][s] = SYSTEM_TIME.parse(
                        lsa_secrets[k][s]).time

        return lsa_secrets
Ejemplo n.º 28
0
    def get_lsa_secrets(self, security, system):
        """Retrieves and decrypts LSA secrets from the registry.
        security and system arguments are the full path to the corresponding
        registry files.
        This function automatically calls self.get_syskey() and
        self.get_lsa_key() functions prior to the secrets retrieval.

        Returns a dictionary of secrets.

        """
        self.get_syskey(system)
        currentKey = self.get_lsa_key(security)
        self.lsa_secrets = {}
        with open(security, 'rb') as f:
            r = Registry.Registry(f)
            r2 = r.open("Policy\\Secrets")
            for i in r2.subkeys():
                self.lsa_secrets[i.name()] = {}
                for j in i.subkeys():
                    self.lsa_secrets[i.name()][j.name()] = j.value(
                        '(default)').value()
        for k, v in self.lsa_secrets.iteritems():
            for s in ["CurrVal", "OldVal"]:
                if v[s] != "":
                    if self.policy["value"] > 1.09:
                        # NT6
                        self.lsa_secrets[k][s] = crypto.decrypt_lsa_secret(
                            v[s], self.lsakeys)
                    else:
                        self.lsa_secrets[k][s] = crypto.SystemFunction005(
                            v[s][0xc:], currentKey)
            for s in ["OupdTime", "CupdTime"]:
                if self.lsa_secrets[k][s] > 0:
                    t = eater.Eater(self.lsa_secrets[k][s])
                    self.lsa_secrets[k][s] = (t.eat("Q") /
                                              10000000) - 11644473600

        return self.lsa_secrets
Ejemplo n.º 29
0
  def __init__(self, host, port):
    self.commands = []
    self.executions = []
    self.transmit = []
    self.data = []
    self.registry = Registry(IMU = None, ping = None, mode = None, jointAngles = None, position = None, velocity = None)
    self.timer = 0
    self.HOST = host
    self.PORT = port

    #connecting using scokets
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Socket created')
    #managing error exception
    try:
      s.bind((self.HOST, self.PORT))
    except socket.error:
        print ('Bind failed ')

    s.listen(5)
    print('Socket awaiting messages')
    (self.conn, addr) = s.accept()
    print('Connected')
Ejemplo n.º 30
0
    def ProcessPlugin(self):

        env = Environment(keep_trailing_newline=True, loader=PackageLoader('regparse', 'templates'))
        
        for hive in self.hives:
            reg = Registry.Registry(hive).root()
            
            #https://github.com/williballenthin/python-registry/blob/master/samples/printall.py
            def rec(reg, depth=None):
                key_path = "\t" * depth + reg.path()
                if self.format is not None:
                    template = Environment().from_string(self.format[0])
                    sys.stdout.write(template.render(key_path=key_path) + "\n")
            
                elif self.format_file is not None:
                    with open(self.format_file[0], "rb") as f:
                        template = env.from_string(f.read())            
                        sys.stdout.write(template.render(key_path=key_path) + "\n")

                for subkey in reg.subkeys():
                    rec(subkey, depth + 1)

            rec(reg, depth=0)