def get_installaton_path_on_windows(fc_name):
    # tested for FreeCAD 0.18
    import itertools
    from winreg import (
        ConnectRegistry,
        HKEY_LOCAL_MACHINE,
        OpenKeyEx,
        QueryValueEx,
        CloseKey,
        KEY_READ,
        EnumKey,
        WindowsError,
    )

    try:
        root = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
        reg_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
        akey = OpenKeyEx(root, reg_path, 0, KEY_READ)
        for i in itertools.count():
            try:
                subname = EnumKey(akey, i)
            except WindowsError:
                break
            if subname.lower().find(fc_name.lower()) > 0:
                subkey = OpenKeyEx(akey, subname, 0, KEY_READ)
                pathname, regtype = QueryValueEx(subkey, "InstallLocation")
                CloseKey(subkey)
                return os.path.expandvars(pathname)
        # close key and root
        CloseKey(akey)
        CloseKey(root)
        return None
    except OSError:
        return None
예제 #2
0
파일: pub2016.py 프로젝트: xme/CAPEv2
    def set_keys(self):

        baseOfficeKeyPath = r"Software\Microsoft\Office"
        installedVersions = list()
        try:
            officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0,
                                KEY_READ)
            for currentKey in range(0, QueryInfoKey(officeKey)[0]):
                isVersion = True
                officeVersion = EnumKey(officeKey, currentKey)
                if "." in officeVersion:
                    for intCheck in officeVersion.split("."):
                        if not intCheck.isdigit():
                            isVersion = False
                            break

                    if isVersion:
                        installedVersions.append(officeVersion)
            CloseKey(officeKey)
        except WindowsError:
            # Office isn't installed at all
            return

        for oVersion in installedVersions:
            key = CreateKeyEx(
                HKEY_CURRENT_USER,
                r"{0}\{1}\Publisher\Security".format(baseOfficeKeyPath,
                                                     oVersion), 0,
                KEY_SET_VALUE)

            SetValueEx(key, "VBAWarnings", 0, REG_DWORD, 1)
            SetValueEx(key, "AccessVBOM", 0, REG_DWORD, 1)
            SetValueEx(key, "ExtensionHardening", 0, REG_DWORD, 0)
            CloseKey(key)
예제 #3
0
    def set_office_params(self):
        baseOfficeKeyPath = r"Software\Microsoft\Office"
        installedVersions = []

        try:
            with OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0,
                         KEY_READ) as officeKey:
                for currentKey in range(QueryInfoKey(officeKey)[0]):
                    officeVersion = EnumKey(officeKey, currentKey)
                    if "." in officeVersion:
                        isVersion = True
                        for intCheck in officeVersion.split("."):
                            if not intCheck.isdigit():
                                isVersion = False
                                break
                        if isVersion:
                            installedVersions.append(officeVersion)
        except WindowsError:
            # Office isn't installed at all
            return

        self._office_helper("Software\\Microsoft\\Office\\Common\\Security",
                            "DisableAllActiveX", REG_DWORD, 0)
        self._office_helper("Software\\Microsoft\\Office\\Common\\Security",
                            "UFIControls", REG_DWORD, 1)
        for oVersion in installedVersions:
            for software in ("Word", "Excel", "PowerPoint", "Publisher",
                             "Outlook"):
                productPath = rf"{baseOfficeKeyPath}\{oVersion}\{software}"
                self._office_helper(f"{productPath}\\Common\\General",
                                    "ShownOptIn", REG_DWORD, 1)
                self._office_helper(f"{productPath}\\Security", "VBAWarnings",
                                    REG_DWORD, 1)
                self._office_helper(f"{productPath}\\Security", "AccessVBOM",
                                    REG_DWORD, 1)
                self._office_helper(f"{productPath}\\Security",
                                    "DisableDDEServerLaunch", REG_DWORD, 0)
                self._office_helper(f"{productPath}\\Security",
                                    "MarkInternalAsUnsafe", REG_DWORD, 0)
                self._office_helper(f"{productPath}\\Security\\ProtectedView",
                                    "DisableAttachmentsInPV", REG_DWORD, 1)
                self._office_helper(f"{productPath}\\Security\\ProtectedView",
                                    "DisableInternetFilesInPV", REG_DWORD, 1)
                self._office_helper(f"{productPath}\\Security\\ProtectedView",
                                    "DisableUnsafeLocationsInPV", REG_DWORD, 1)
                # self._office_helper(f"HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Office\\{oVersion}\\{software}\\Security", "MarkInternalAsUnsafe", REG_DWORD, 0)
                self._office_helper(f"{productPath}\\Security",
                                    "ExtensionHardening", 0)
예제 #4
0
def parse_registry_single(registry_path):
    registry_entries = {}
    temp_subdict = {}

    try:
        location = _winreg.HKEY_LOCAL_MACHINE
        aReg = _winreg.ConnectRegistry(None, location)
        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\\' + registry_path, 0,
                               (REG_SECURITY))
        for i in range(_winreg.QueryInfoKey(aKey)[1]):
            name, value, rtype, = _winreg.EnumValue(aKey, i)
            registry_entries[name] = (value, rtype)
#         print(registry_entries)
        _winreg.CloseKey(aKey)
        _winreg.CloseKey(aReg)

        subKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                 r'SOFTWARE\\' + registry_path, 0,
                                 (REG_SECURITY))
        #look for subfolders and read them
        for k in range(_winreg.QueryInfoKey(subKey)[0]):
            subfolder = EnumKey(subKey, k)
            #             print(subfolder)
            temp_subdict = parse_registry_single(registry_path + '\\' +
                                                 subfolder)
            #             print(temp_subdict)
            registry_entries[subfolder] = temp_subdict
#         print(registry_entries)
        _winreg.CloseKey(subKey)
        return registry_entries
    except WindowsError as e:
        #         print(e)
        pass
예제 #5
0
def reg_scanner(**kwargs):

    try:
        if kwargs.get('source') == 'putty':
            parent_key = r"SOFTWARE\SimonTatham\PuTTY\Sessions"
        elif kwargs.get('source') == 'kitty':
            parent_key = r"SOFTWARE\9bis.com\KiTTY\Sessions"
    except Exception as error:
        print(
            f'Invalid source, please check configuration file or typo... -> {error}'
        )

    parent_reg = ConnectRegistry(None, HKEY_CURRENT_USER)
    parent_key = OpenKey(parent_reg, parent_key)

    for sessions in range(int(kwargs.get('sessions'))):
        try:
            subkey_name = EnumKey(parent_key, sessions)
            subkey = OpenKey(parent_key, subkey_name)
            host = QueryValueEx(subkey, "HostName")
            port = QueryValueEx(subkey, "PortNumber")
            username = QueryValueEx(subkey, "UserName")

            yield (subkey_name, host[0], port[0], username[0])
        except OSError as error:
            #print(error)
            break
예제 #6
0
    def _users(self):
        r"""
        (Windows)
            This function checks the registry key:
            ``SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList``
            for user sids. If a new account is created, the alert will be triggered
            after the system is rebooted and is updated to reflect the creation of the account.

        (Linux)
            Open the etc/passwd file and extracts all the user's. If a new user is found within
            this file or if a service account shell has been updated to an interactive logon shell,
            an alert will be triggered
        """
        target_key = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
        allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split("|")))

        if self.system == "Windows":
            with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm:
                with OpenKey(hklm, target_key, 0, KEY_ALL_ACCESS) as profile_list:
                    subkeys = QueryInfoKey(profile_list)[0]
                    for i in range(subkeys):
                        subkey = EnumKey(profile_list, i)
                        if search(r"^S-\d-\d+-(\d+-){1,14}\d+$", subkey):
                            with OpenKey(hklm, f"{target_key}\\{subkey}", 0, KEY_ALL_ACCESS) as user_key:
                                user = QueryValueEx(user_key, r"ProfileImagePath")[0].split("\\")[-1]
                                if user not in allowed_users:
                                    message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected a interactive new user: {user}. " \
                                              f"If you have not created a new user or have not changed the shell " \
                                              f"for a service account, then your system might be compromised!"
                                    self.__send_alert(
                                        self.config["users"]["subject"],
                                        message)
                                    self.num_of_alerts += 1
        else:
            linux_shells = (
                            "bash", # GNU Bourne-Again Shell
                            "sh",   # Bourne Shell
                            "ksh",  # Korn Shell
                            "zsh",  # Z Shell
                            "csh"   # C Shell
                            ) 
            interactive_users = []
            allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split('|')))

            with open("/etc/passwd") as passwd:
                for entry in passwd:
                    entry = entry.strip().split(":")
                    user, shell = entry[0], entry[-1].split('/')[-1]
                    if shell in linux_shells:
                        interactive_users.append(user)
                    for interactive_user in interactive_users:
                        if interactive_user not in allowed_users:
                            message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected " \
                                      f"a new interactive user: {interactive_user}. " \
                                      f"If you have not created a new user or have not changed the shell " \
                                      f"for a service account, then your system might be compromised!"
                            self.__send_alert(
                                self.config["users"]["subject"],
                                message)
                            self.num_of_alerts += 1
예제 #7
0
    def test_readValues(self):
        from winreg import OpenKey, EnumValue, QueryValueEx, EnumKey
        from winreg import REG_SZ, REG_EXPAND_SZ
        key = OpenKey(self.root_key, self.test_key_name)
        sub_key = OpenKey(key, "sub_key")
        index = 0
        while 1:
            try:
                data = EnumValue(sub_key, index)
            except EnvironmentError as e:
                break
            if data[0] != 'test_name':
                # cannot wrap a memoryview in setup_class for test_data
                assert data in self.test_data
            index = index + 1
        assert index == len(self.test_data) + 1

        for name, value, type in self.test_data:
            result = QueryValueEx(sub_key, name)
            assert result == (value, type)
            if type == REG_SZ or type == REG_EXPAND_SZ:
                assert not isinstance(result[0], bytes)

        assert EnumKey(key, 0) == "sub_key"
        raises(EnvironmentError, EnumKey, key, 1)
예제 #8
0
 def __next__(self):
     try:
         next_name = EnumKey(self.__base_key, self.__idx)
         self.__idx += 1
         return next_name
     except Exception:
         raise StopIteration
예제 #9
0
def __win32_finddll():
    from winreg import OpenKey, CloseKey, EnumKey, QueryValueEx, \
        QueryInfoKey, HKEY_LOCAL_MACHINE
    from distutils.version import LooseVersion
    import os

    dlls = []
    # Look up different variants of Ghostscript and take the highest
    # version for which the DLL is to be found in the filesystem.
    for key_name in ('AFPL Ghostscript', 'Aladdin Ghostscript',
                     'GPL Ghostscript', 'GNU Ghostscript'):
        try:
            k1 = OpenKey(HKEY_LOCAL_MACHINE, "Software\\%s" % key_name)
            for num in range(0, QueryInfoKey(k1)[0]):
                version = EnumKey(k1, num)
                try:
                    k2 = OpenKey(k1, version)
                    dll_path = QueryValueEx(k2, 'GS_DLL')[0]
                    CloseKey(k2)
                    if os.path.exists(dll_path):
                        dlls.append((LooseVersion(version), dll_path))
                except WindowsError:
                    pass
            CloseKey(k1)    
        except WindowsError:
            pass
    if dlls:
        dlls.sort()
        return dlls[-1][-1]
    else:
        return None
예제 #10
0
 def read_key(
     self,
     name: str,
     key_wow64_32key: bool = False,
 ) -> RegKey:
     handle = self._get_handler(name, KEY_READ, key_wow64_32key)
     keys_num, values_num, modify = QueryInfoKey(handle)
     modify_at = datetime(1601, 1, 1) + timedelta(microseconds=modify / 10)
     keys = list()
     entries = list()
     for key_i in range(0, keys_num):
         keys.append(EnumKey(handle, key_i))
     for key_i in range(0, values_num):
         entry_name, value, raw_type = EnumValue(handle, key_i)
         entries.append(
             RegEntry(
                 reg_key=name,
                 name=entry_name,
                 value=value,
                 type=WinregType(raw_type),
                 host=self.host,
             ))
     return RegKey(
         name=name,
         reg_keys=keys,
         entries=entries,
         modify_at=modify_at,
     )
예제 #11
0
    def type(self):
        """Get resource type.

        NOTE: this winreg-based method enumerates all resources which makes it a bit slower. But, IT WORKS.

        >>> import mscluster
        >>> C = mscluster.Cluster()
        >>> while (True):
        ...     Cr = next(C.resources)
        ...     if Cr == 'AG-LABC':
        ...         R = C.openResource(Cr)
        ...         Rtype = R.type
        ...         break
        >>> Rtype
        'SQL Server Availability Group'
        """
        with OpenKey(HKEY_LOCAL_MACHINE, "Cluster\Resources") as rsKey:
            (rskeys, rsvals, rsmod) = QueryInfoKey(rsKey)
            for n in range(rskeys):
                rid = EnumKey(rsKey, n)
                with OpenKey(rsKey, rid) as rKey:
                    (rname, rname_t) = QueryValueEx(rKey, "Name")
                    if rname == self.name:
                        (rtype, rtype_t) = QueryValueEx(rKey, "Type")
                        return rtype
        raise RuntimeError("Unable to find resource type for [{}]".format(
            self.name))
예제 #12
0
 def get_info(self, reg):
     key = OpenKey(HKEY_CURRENT_USER, reg)
     conns = []
     try:
         i = 0
         while 1:
             name = EnumKey(key, i)
             conns.append(name)
             i += 1
     except:
         pass
     hosts = []
     usernames = []
     passwords = []
     for i in conns:
         key = OpenKey(HKEY_CURRENT_USER, reg + '\\' + i)
         try:
             j = 0
             while 1:
                 name, value, type = EnumValue(key, j)
                 if name == 'Host':
                     hosts.append(value)
                 if name == 'UserName':
                     usernames.append(value)
                 if name == 'Pwd':
                     passwords.append(value)
                 j += 1
         except:
             pass
     CloseKey(key)
     for i in range(len(hosts)):
         if len(hosts[i]) is not 0:
             print 'host_name:' + hosts[i] + '  ' + 'username:'******'  ' + 'password:' + passwords[i]
def get_subkeys(key):
		j = 0
		while True:
			try:
				yield EnumKey(key, j)
				j += 1
			except WindowsError: break
예제 #14
0
 def enumerate_keys(key):
     i = 0
     while True:
         try:
             yield EnumKey(key, i)
             i += 1
         except WindowsError:
             break
예제 #15
0
 def getLatestKey(hKey):
     curaList = []
     for i in range(0, QueryInfoKey(hKey)[0]):
         curaList.append(EnumKey(hKey, i))
     
     fList = [k for k in curaList if 'Ultimaker Cura' in k]
     fList.sort()
     return fList[-1]
예제 #16
0
파일: win.py 프로젝트: gwlcinphilly/base0
def reg_subkey(reg_key, name=False):
    try:
        subkey = EnumKey(reg_key, 0)
        if not name:
            subkey = reg_path(reg_key, subkey)
    except WindowsError:
        subkey = None
    return subkey
예제 #17
0
파일: regaux.py 프로젝트: luzhlon/script
def keys(pkey):
    i = 0
    while 1:
        try:
            key = EnumKey(pkey, i)
            i += 1
            yield key
        except OSError:
            break
예제 #18
0
def readSubKeys(hkey, regPath):
    if not pathExists(hkey, regPath):
        return -1
    reg = OpenKey(hkey, regPath)
    subKeys = []
    noOfSubkeys = QueryInfoKey(reg)[0]
    for i in range(0, noOfSubkeys):
        subKeys.append(EnumKey(reg, i))
    CloseKey(reg)
    return subKeys
예제 #19
0
def subkeys(hkey=HKEY_CURRENT_USER, path='', accum=''):
    with suppress(WindowsError), OpenKey(hkey, path) as k:
        nsubkeys, nvalues, _ = QueryInfoKey(k)
        # for i in range(nvalues):
        #     yield winreg.EnumValue(k, i)
        for i in range(nsubkeys):
            sub_key = EnumKey(k, i)
            fullpath = accum + '\\' + sub_key
            yield fullpath
            yield from subkeys(k, sub_key, fullpath)
예제 #20
0
 def _e(key, at):
     result = None
     key_id = id(key)
     try:
         result = EnumKey(key, at)
         return result
     except Exception as exception:
         result = exception
         raise result
     finally:
         enum_collect[key_id].append(result)
예제 #21
0
def test_winreg():
    from winreg import OpenKey, EnumKey, CloseKey, HKEY_LOCAL_MACHINE

    def hook(event, args):
        if not event.startswith("winreg."):
            return
        print(event, *args)

    sys.addaudithook(hook)

    k = OpenKey(HKEY_LOCAL_MACHINE, "Software")
    EnumKey(k, 0)
    try:
        EnumKey(k, 10000)
    except OSError:
        pass
    else:
        raise RuntimeError("Expected EnumKey(HKLM, 10000) to fail")

    kv = k.Detach()
    CloseKey(kv)
예제 #22
0
 def delete_key_tree(
     self,
     name: str,
     key_wow64_32key: bool = False,
 ) -> None:
     handle = self._get_handler(name, KEY_READ, key_wow64_32key)
     keys_num, values_num, modify = QueryInfoKey(handle)  # pylint: disable=unused-variable
     for key_i in range(0, keys_num):
         key = EnumKey(handle, key_i)
         self.delete_key_tree(f"{name}\\{key}", key_wow64_32key)
     handle.Close()
     self.delete_key(name, key_wow64_32key)
예제 #23
0
def delete_registry_tree(root, subkey):
    try:
        hkey = OpenKey(root, subkey, access=KEY_ALL_ACCESS)
    except OSError:
        return
    while True:
        try:
            subsubkey = EnumKey(hkey, 0)
        except OSError:
            break
        delete_registry_tree(hkey, subsubkey)
    CloseKey(hkey)
    DeleteKey(root, subkey)
예제 #24
0
 def get_subattribs(self, attrib_name, ob):
     count = 0
     attrib = []
     while True:
         try:
             subattribs = EnumKey(
                 ob, count) if attrib_name is 'key' else EnumValue(
                     ob, count)
             attrib.append(subattribs)
             count += 1
         except WindowsError as e:
             break
     return attrib
예제 #25
0
        def __get_sub_keys(self, key):
            partial_key, root_hive = self.__parse_key(key)

            with ConnectRegistry(None, root_hive) as reg:
                with OpenKey(reg, partial_key) as key_object:
                    sub_keys_count, values_count, last_modified = QueryInfoKey(
                        key_object)
                    try:
                        for i in range(sub_keys_count):
                            sub_key_name = EnumKey(key_object, i)
                            yield sub_key_name
                    except WindowsError:
                        pass
예제 #26
0
def test_winreg():  # type: () -> None
    from winreg import OpenKey, EnumKey, CloseKey, HKEY_LOCAL_MACHINE  # type: ignore

    def hook(event,
             args):  # type: (str, typing.Tuple[typing.Any, ...]) -> None
        if not event.startswith("winreg."):
            return
        print(event, args)

    sysaudit.addaudithook(hook)

    k = OpenKey(HKEY_LOCAL_MACHINE, "Software")
    EnumKey(k, 0)
    try:
        EnumKey(k, 10000)
    except OSError:
        pass
    else:
        raise RuntimeError("Expected EnumKey(HKLM, 10000) to fail")

    kv = k.Detach()
    CloseKey(kv)
예제 #27
0
def parseRegistry(software_name, special_folder=''):
    registry_entries = {}
    rex = re.compile(software_name + '*', re.IGNORECASE)

    try:
        registry_path = r'SOFTWARE\\' + special_folder
        aKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, registry_path, 0,
                               (REG_SECURITY))

        #search whole registry for desired folder
        for i in range(_winreg.QueryInfoKey(aKey)[0]):
            folder = EnumKey(aKey, i)
            target = rex.search(folder)
            #if found, read info of folder
            if target:
                _winreg.CloseKey(aKey)
                #                 print(folder)
                temp_dict = parse_registry_single(folder)
                #                 print(temp_dict)
                subKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                         registry_path + '\\' + folder, 0,
                                         (REG_SECURITY))
                #look for subfolders and read them
                for k in range(_winreg.QueryInfoKey(subKey)[0]):
                    subfolder = EnumKey(subKey, k)
                    #                     print(subfolder)
                    temp_subdict = parse_registry_single(special_folder +
                                                         '\\' + folder + '\\' +
                                                         subfolder)
                    #                     print(temp_subdict)
                    registry_entries = {subfolder: temp_subdict}
                    print(registry_entries)
                _winreg.CloseKey(subKey)
    except WindowsError as e:
        #         print(e)
        pass
예제 #28
0
파일: test_winreg.py 프로젝트: Qointum/pypy
 def test_long_key(self):
     from winreg import (HKEY_CURRENT_USER, KEY_ALL_ACCESS, CreateKey,
                         SetValue, EnumKey, REG_SZ, QueryInfoKey, OpenKey,
                         DeleteKey)
     name = 'x' * 256
     try:
         with CreateKey(HKEY_CURRENT_USER, self.test_key_name) as key:
             SetValue(key, name, REG_SZ, 'x')
             num_subkeys, num_values, t = QueryInfoKey(key)
             EnumKey(key, 0)
     finally:
         with OpenKey(HKEY_CURRENT_USER, self.test_key_name, 0,
                      KEY_ALL_ACCESS) as key:
             DeleteKey(key, name)
         DeleteKey(HKEY_CURRENT_USER, self.test_key_name)
예제 #29
0
파일: sage.py 프로젝트: m1gnus/RSArmageddon
def get_sage_nt_locations_registry():
    assert os.name == "nt"
    sage_key_re = re.compile(r"SageMath-(\d+)\.(\d+)", re.IGNORECASE)
    with OpenKey(HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") as root_key:
        try:
            for i in count():
                subkey_name = EnumKey(root_key, i)
                m = sage_key_re.search(subkey_name)
                if m:
                    vmaj, vmin = m.group(1, 2)
                    with OpenKey(root_key, subkey_name) as subkey:
                        location, _ = QueryValueEx(subkey, "InstallLocation")
                    yield Path(location).resolve(), vmaj, vmin
        except OSError:
            pass
예제 #30
0
파일: win.py 프로젝트: gwlcinphilly/base0
def reg_subkeys(reg_key, subkey=None):
    subkeys = []
    try:
        index = 0
        while True:
            subkey_ = EnumKey(reg_key, index)
            subkeys.append(subkey_)
            index += 1
            if subkey is not None:
                if subkey == subkey_:
                    subkeys = reg_path(reg_key, subkey)
                    break
    except WindowsError:
        pass
    return subkeys