CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/auxiliary/admin/aws/aws_launch_instances.rb
Views: 11655
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'metasploit/framework/aws/client'
7
8
class MetasploitModule < Msf::Auxiliary
9
include Metasploit::Framework::Aws::Client
10
11
def initialize(info = {})
12
super(
13
update_info(
14
info,
15
'Name' => "Launches Hosts in AWS",
16
'Description' => %q{
17
This module will attempt to launch an AWS instances (hosts) in EC2.
18
},
19
'License' => MSF_LICENSE,
20
'Author' => [
21
'Javier Godinez <godinezj[at]gmail.com>',
22
],
23
'References' => [
24
[ 'URL', 'https://drive.google.com/open?id=0B2Ka7F_6TetSNFdfbkI1cnJHUTQ'],
25
[ 'URL', 'https://published-prd.lanyonevents.com/published/rsaus17/sessionsFiles/4721/IDY-W10-DevSecOps-on-the-Offense-Automating-Amazon-Web-Services-Account-Takeover.pdf' ]
26
]
27
)
28
)
29
register_options(
30
[
31
OptString.new('AccessKeyId', [true, 'AWS access key', '']),
32
OptString.new('SecretAccessKey', [true, 'AWS secret key', '']),
33
OptString.new('Token', [false, 'AWS session token', '']),
34
OptString.new('RHOST', [true, 'AWS region specific EC2 endpoint', 'ec2.us-west-2.amazonaws.com']),
35
OptString.new('Region', [true, 'The default region', 'us-west-2' ]),
36
OptString.new("AMI_ID", [true, 'The Amazon Machine Image (AMI) ID', 'ami-1e299d7e']),
37
OptString.new("KEY_NAME", [true, 'The SSH key to be used for ec2-user', 'admin']),
38
OptString.new("SSH_PUB_KEY", [false, 'The public SSH key to be used for ec2-user, e.g., "ssh-rsa ABCDE..."', '']),
39
OptString.new("USERDATA_FILE", [false, 'The script that will be executed on start', 'tools/modules/aws-aggregator-userdata.sh'])
40
]
41
)
42
register_advanced_options(
43
[
44
OptPort.new('RPORT', [true, 'AWS EC2 Endpoint TCP Port', 443]),
45
OptBool.new('SSL', [true, 'AWS EC2 Endpoint SSL', true]),
46
OptString.new('INSTANCE_TYPE', [true, 'The instance type', 'm3.medium']),
47
OptString.new('ROLE_NAME', [false, 'The instance profile/role name', '']),
48
OptString.new('VPC_ID', [false, 'The EC2 VPC ID', '']),
49
OptString.new('SUBNET_ID', [false, 'The public subnet to use', '']),
50
OptString.new('SEC_GROUP_ID', [false, 'The EC2 security group to use', '']),
51
OptString.new('SEC_GROUP_CIDR', [true, 'EC2 security group network access CIDR', '0.0.0.0/0']),
52
OptString.new('SEC_GROUP_PORT', [true, 'EC2 security group network access PORT', 'tcp:22']),
53
OptString.new('SEC_GROUP_NAME', [false, 'Optional EC2 security group name', '']),
54
OptInt.new('MaxCount', [true, 'Maximum number of instances to launch', 1]),
55
OptInt.new('MinCount', [true, 'Minumum number of instances to launch', 1])
56
]
57
)
58
deregister_options('VHOST')
59
end
60
61
def run
62
if datastore['AccessKeyId'].blank? || datastore['SecretAccessKey'].blank?
63
print_error("Both AccessKeyId and SecretAccessKey are required")
64
return
65
end
66
# setup creds for making IAM API calls
67
creds = {
68
'AccessKeyId' => datastore['AccessKeyId'],
69
'SecretAccessKey' => datastore['SecretAccessKey']
70
}
71
creds['Token'] = datastore['Token'] unless datastore['Token'].blank?
72
73
create_keypair(creds) unless datastore['SSH_PUB_KEY'].blank?
74
vpc = datastore['VPC_ID'].blank? ? vpc(creds) : datastore['VPC_ID']
75
sg = datastore['SEC_GROUP_ID'].blank? ? create_sg(creds, vpc) : datastore['SEC_GROUP_ID']
76
subnet = datastore['SUBNET_ID'].blank? ? pub_subnet(creds, vpc) : datastore['SUBNET_ID']
77
unless subnet
78
print_error("Could not find a public subnet, please provide one")
79
return
80
end
81
instance_id = launch_instance(creds, subnet, sg)
82
action = 'DescribeInstances'
83
doc = call_ec2(creds, 'Action' => action, 'InstanceId.1' => instance_id)
84
doc = print_results(doc, action)
85
begin
86
# need a better parser so we can avoid shit like this
87
ip = doc['reservationSet']['item']['instancesSet']['item']['networkInterfaceSet']['item']['privateIpAddressesSet']['item']['association']['publicIp']
88
print_status("Instance #{instance_id} has IP address #{ip}")
89
rescue NoMethodError
90
print_error("Could not retrieve instance IP address")
91
end
92
end
93
94
def opts(action, subnet, sg)
95
opts = {
96
'Action' => action,
97
'ImageId' => datastore['AMI_ID'],
98
'KeyName' => datastore['KEY_NAME'],
99
'InstanceType' => datastore['INSTANCE_TYPE'],
100
'NetworkInterface.1.SubnetId' => subnet,
101
'NetworkInterface.1.SecurityGroupId.1' => sg,
102
'MinCount' => datastore['MinCount'].to_s,
103
'MaxCount' => datastore['MaxCount'].to_s,
104
'NetworkInterface.1.AssociatePublicIpAddress' => 'true',
105
'NetworkInterface.1.DeviceIndex' => '0'
106
}
107
opts['IamInstanceProfile.Name'] = datastore['ROLE_NAME'] unless datastore['ROLE_NAME'].blank?
108
unless datastore['USERDATA_FILE'].blank?
109
if File.exist?(datastore['USERDATA_FILE'])
110
opts['UserData'] = URI::DEFAULT_PARSER.escape(Base64.encode64(open(datastore['USERDATA_FILE'], 'r').read).strip)
111
else
112
print_error("Could not open userdata file: #{datastore['USERDATA_FILE']}")
113
end
114
end
115
opts
116
end
117
118
def launch_instance(creds, subnet, sg)
119
action = 'RunInstances'
120
print_status("Launching instance(s) in #{datastore['Region']}, AMI: #{datastore['AMI_ID']}, key pair name: #{datastore['KEY_NAME']}, security group: #{sg}, subnet ID: #{subnet}")
121
doc = call_ec2(creds, opts(action, subnet, sg))
122
doc = print_results(doc, action)
123
return if doc.nil?
124
# TODO: account for multiple instances
125
if doc['instancesSet']['item'].instance_of?(Array)
126
instance_id = doc['instancesSet']['item'].first['instanceId']
127
else
128
instance_id = doc['instancesSet']['item']['instanceId']
129
end
130
print_status("Launched instance #{instance_id} in #{datastore['Region']} account #{doc['ownerId']}")
131
action = 'DescribeInstanceStatus'
132
loop do
133
sleep(15)
134
doc = call_ec2(creds, 'Action' => action, 'InstanceId' => instance_id)
135
doc = print_results(doc, action)
136
if doc['instanceStatusSet'].nil?
137
print_error("Error, could not get instance status, instance possibly terminated")
138
break
139
end
140
status = doc['instanceStatusSet']['item']['systemStatus']['status']
141
print_status("instance #{instance_id} status: #{status}")
142
break if status == 'ok' || status != 'initializing'
143
end
144
instance_id
145
end
146
147
def create_keypair(creds)
148
action = 'ImportKeyPair'
149
doc = call_ec2(creds, 'Action' => action, 'KeyName' => datastore['KEY_NAME'], 'PublicKeyMaterial' => Rex::Text.encode_base64(datastore['SSH_PUB_KEY']))
150
if doc['Response'].nil?
151
doc = print_results(doc, action)
152
if doc['keyName'].nil? || doc['keyFingerprint'].nil?
153
print_error("Error creating key using provided key material (SSH_PUB_KEY)")
154
else
155
print_status("Created #{doc['keyName']} (#{doc['keyFingerprint']})")
156
end
157
else
158
if doc['Response']['Errors'] && doc['Response']['Errors']['Error']
159
print_error(doc['Response']['Errors']['Error']['Message'])
160
else
161
print_error("Error creating key using provided key material (SSH_PUB_KEY)")
162
end
163
end
164
end
165
166
def pub_subnet(creds, vpc_id)
167
# First look for subnets that are configured to provision a public IP when instances are launched
168
action = 'DescribeSubnets'
169
doc = call_ec2(creds, 'Action' => action)
170
doc = print_results(doc, action)
171
vpc_subnets = doc['subnetSet']['item'].select { |x| x['vpcId'] == vpc_id }
172
pub_subnets = vpc_subnets.select { |x| x['mapPublicIpOnLaunch'] == 'true' }
173
return pub_subnets.first['subnetId'] if pub_subnets.count > 0
174
175
# Second, try to retrieve public subnet id by looking through route tables to find subnets
176
# associated with an Internet gateway
177
action = 'DescribeRouteTables'
178
doc = call_ec2(creds, 'Action' => action)
179
doc = print_results(doc, action)
180
vpc_route_table = doc['routeTableSet']['item'].select { |x| x['vpcId'] == vpc_id }
181
vpc_route_table.each do |route_table|
182
next if route_table['associationSet'].nil? || route_table['routeSet'].nil?
183
entries = route_table['routeSet']['item']
184
if entries.instance_of?(Hash)
185
if entries['gatewayId'].start_with?('igw-')
186
return route_table['associationSet']['item'].first['subnetId']
187
end
188
else
189
route_table['routeSet']['item'].each do |route|
190
if route['gatewayId'] && route['gatewayId'].start_with?('igw-')
191
return route_table['associationSet']['item'].first['subnetId']
192
end
193
end
194
end
195
end
196
nil
197
end
198
199
def create_sg(creds, vpc_id)
200
name = Rex::Text.rand_text_alphanumeric(8)
201
action = 'CreateSecurityGroup'
202
doc = call_ec2(creds, 'Action' => action, 'GroupName' => name, 'VpcId' => vpc_id, 'GroupDescription' => name)
203
doc = print_results(doc, action)
204
print_error("Could not create SG") && return if doc['groupId'].nil?
205
sg = doc['groupId']
206
proto, port = datastore['SEC_GROUP_PORT'].split(':')
207
cidr = URI::DEFAULT_PARSER.escape(datastore['SEC_GROUP_CIDR'])
208
action = 'AuthorizeSecurityGroupIngress'
209
doc = call_ec2(creds, 'Action' => action,
210
'IpPermissions.1.IpRanges.1.CidrIp' => cidr,
211
'IpPermissions.1.IpProtocol' => proto,
212
'IpPermissions.1.FromPort' => port,
213
'IpPermissions.1.ToPort' => port,
214
'GroupId' => sg)
215
doc = print_results(doc, action)
216
if doc['return'] && doc['return'] == 'true'
217
print_status("Created security group: #{sg}")
218
else
219
print_error("Failed creating security group")
220
end
221
sg
222
end
223
224
def vpc(creds)
225
action = 'DescribeVpcs'
226
doc = call_ec2(creds, 'Action' => action)
227
doc = print_results(doc, action)
228
if doc['vpcSet'].nil? || doc['vpcSet']['item'].nil?
229
print_error("Could not determine VPC ID for #{datastore['AccessKeyId']} in #{datastore['RHOST']}")
230
return nil
231
end
232
item = doc['vpcSet']['item']
233
return item['vpcId'] if item.instance_of?(Hash)
234
return item.first['vpcId'] if item.instance_of?(Array) && !item.first['vpcId'].nil?
235
print_error("Could not determine VPC ID for #{datastore['AccessKeyId']} in #{datastore['RHOST']}")
236
nil
237
end
238
end
239
240