-
-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathapp.py
More file actions
427 lines (382 loc) · 14.7 KB
/
app.py
File metadata and controls
427 lines (382 loc) · 14.7 KB
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
import datetime
import socket
import asyncio
import time
import random
import json
import boto3
import botocore
from botocore.config import Config
from walkoff_app_sdk.app_base import AppBase
def datetime_handler(x):
""" This function is used make datetime object json serilizable,
removing this function can cause error in some actions """
if isinstance(x, datetime.datetime):
return x.isoformat()
raise TypeError("Unknown type")
class AWSEC2(AppBase):
__version__ = "1.0.0"
app_name = "AWS ec2"
def __init__(self, redis, logger, console_logger=None):
"""
Each app should have this __init__ to set up Redis and logging.
:param redis:
:param logger:
:param console_logger:
"""
super().__init__(redis, logger, console_logger)
def auth_ec2(self, access_key, secret_key, region):
my_config = Config(
region_name = region,
signature_version = 'v4',
retries = {
'max_attempts': 10,
'mode': 'standard'
},
)
if access_key!="":
self.ec2 = boto3.resource(
'ec2',
config=my_config,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
)
else:
self.ec2 = boto3.resource(
'ec2',
config=my_config,
)
return self.ec2
# Write your data inside this function
def get_rules(self, access_key, secret_key, region, NetworkAclId):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
network_acl = self.ec2.NetworkAcl(NetworkAclId)
return network_acl.entries
# Write your data inside this function
def block_ip(self, access_key, secret_key, region, NetworkAclId, ip, direction):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
network_acl = self.ec2.NetworkAcl(NetworkAclId)
if "/" not in ip:
ip = "%s/32" % ip
egress = True
if direction == "inbound":
egress = False
# This is a shitty system :)
minimum = 100
max_range = 30000
numbers = []
#found = False
for item in network_acl.entries:
if egress != item["Egress"]:
continue
if ip == item["CidrBlock"]:
raise Exception("IP %s is already being blocked." % ip)
numbers.append(item["RuleNumber"])
for index in range(minimum, max_range):
if index in numbers:
continue
minimum = index
break
print("New number: %d" % minimum)
try:
return network_acl.create_entry(
CidrBlock = ip,
DryRun = False,
Egress = egress,
IcmpTypeCode = {
'Code': 123,
'Type': 123
},
PortRange = {
'From': 0,
'To': 65535
},
Protocol = "6",
RuleAction = "DENY",
RuleNumber = minimum,
)
except botocore.exceptions.ClientError as e:
print("Error: %s" % e)
return "%s" % e
# Write your data inside this function
def create_acl_entry(self, access_key, secret_key, region, NetworkAclId , cidr_block, dryrun, direction, portrange_from, portrange_to, protocol, rule_action, rule_number):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
network_acl = self.ec2.NetworkAcl(NetworkAclId)
if protocol.lower() == "tcp":
protocol = "6"
elif protocol.lower() == "udp":
protocol = "17"
egress = True
if direction == "inbound":
egress = False
else:
egress = True
if dryrun.lower() == "false":
dryrun = False
else:
dryrun = True
try:
return network_acl.create_entry(
CidrBlock = cidr_block,
DryRun = dryrun,
Egress = egress,
IcmpTypeCode = {
'Code': 123,
'Type': 123
},
PortRange = {
'From': int(portrange_from),
'To': int(portrange_to)
},
Protocol = protocol,
RuleAction = rule_action,
RuleNumber = int(rule_number),
)
except botocore.exceptions.ClientError as e:
print("Error: %s" % e)
return "%s" % e
#Terminate, Start and Stop Instance
def instance_state_change(self, access_key, secret_key, region, instance_id, action, dryrun):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
instance = self.ec2.Instance(instance_id)
dryrun = True if dryrun in ["True", "true"] else False
try:
if action == "terminate":
return instance.terminate(DryRun = dryrun)
elif action == "start":
return instance.start(DryRun = dryrun)
else:
return instance.stop(DryRun = dryrun)
except botocore.exceptions.ClientError as e:
print("Error: %s" % e)
return "%s" % e
#Create Network Interface
def create_network_interface(self, access_key, secret_key, region, subnetid, description, dryrun ):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
return client.create_network_interface(
Description = description,
DryRun = dryrun,
SubnetId = subnetid
)
except Exception as e:
return e
#Create Image
def create_image(self, access_key, secret_key, region, description, instance_id, name, dryrun, noreboot):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
noreboot = True if dryrun in ["True", "true"] else False
try:
return client.create_image(
Description=description,
DryRun = dryrun,
InstanceId = instance_id,
Name = name,
NoReboot = noreboot
)
except Exception as e:
return e
#Deregister Image
def deregister_an_image(self, access_key, secret_key, region, image_id, dryrun):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
return client.deregister_image(
ImageId = image_id,
DryRun = dryrun
)
except Exception as e:
return e
#Create Snapshot
def create_snapshot(self, access_key, secret_key, region, description, volume_id, dryrun):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
response = client.create_snapshot(
Description = description,
VolumeId = volume_id,
DryRun = dryrun
)
return json.dumps(response, default=datetime_handler)
except Exception as e:
return e
#Delete Snapshot
def delete_snapshot(self, access_key, secret_key, region, snapshot_id, dryrun):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
return client.delete_snapshot(
SnapshotId = snapshot_id,
DryRun = dryrun
)
except Exception as e:
return e
#Delete Network Interface
def delete_network_interface(self, access_key, secret_key, region, networkinterface_id, dryrun):
self.ec2 = self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
return client.delete_network_interface(
NetworkInterfaceId = networkinterface_id,
DryRun=dryrun
)
except Exception as e:
return e
#Describing address
def describe_address(self, access_key, secret_key, region, publicips, dryrun):
self.ec2=self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
if len(publicips)==0:
lt = []
else:
lt=publicips.split(','),
return client.describe_addresses(
PublicIps = lt,
DryRun = dryrun
)
except Exception as e:
return e
#Describing key pair
def describe_keypair(self, access_key, secret_key, region, dryrun, option, value):
self.ec2=self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
if len(value)==0:
lt=[]
else:
lt=value.split(',')
if option == 'KeyNames':
return client.describe_key_pairs(
KeyNames=lt,
DryRun = dryrun
)
elif option == 'KeyPairIds':
return client.describe_key_pairs(
KeyPairIds=lt,
DryRun = dryrun
)
else:
return client.describe_key_pairs(
DryRun = dryrun
)
except Exception as e:
return e
#Describing network acls
def describe_networkacls(self, access_key, secret_key, region, dryrun, networkAcl_Id):
self.ec2=self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
if len(networkAcl_Id)!=0:
lt=networkAcl_Id.split(',')
return client.describe_network_acls(
DryRun = dryrun,
NetworkAclIds = lt
)
else:
return client.describe_network_acls(
DryRun = dryrun,
)
except Exception as e:
return e
#Describing Security groups
def describe_securitygroups(self, access_key, secret_key, region, dryrun, option, value):
self.ec2=self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
if len(value)==0:
lt=[]
else:
lt=value.split(',')
if option == 'GroupIds':
return client.describe_security_groups(
GroupIds=lt,
DryRun = dryrun
)
# elif option == 'GroupNames':
# return client.describe_security_groups(
# GroupNames=lt,
# DryRun = dryrun
# )
else:
return client.describe_security_groups(
DryRun = dryrun
)
except Exception as e:
return e
#Describing vpcs
def describe_vpc(self, access_key, secret_key, region, dryrun, vpcid):
self.ec2=self.auth_ec2(access_key, secret_key, region)
client = self.ec2.meta.client
dryrun = True if dryrun in ["True", "true"] else False
try:
if len(vpcid)==0:
lt=[]
return client.describe_vpcs(
DryRun = dryrun,
VpcIds = lt
)
else:
lt=vpcid.split(',')
return client.describe_vpcs(
DryRun = dryrun,
VpcIds = lt
)
except Exception as e:
return e
def create_an_instance(self, access_key, secret_key, region, dryrun, image_id, min_count, max_count, instance_type, user_data, key_name, security_group_ids):
client = boto3.resource('ec2',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=region)
dryrun = True if dryrun in ["True", "true"] else False
try:
if security_group_ids:
security_group_ids_list = [i for i in security_group_ids.split(" ")]
instance = client.create_instances(
DryRun= dryrun,
ImageId=image_id,
MinCount=int(min_count),
MaxCount=int(max_count),
InstanceType=instance_type,
KeyName=key_name,
SecurityGroupIds= security_group_ids_list,
UserData= user_data
)
#parsing response
total_instances = ["instance_id_"+str(i) for i in range(1,len(instance)+1)]
instance_id_list = [i.id for i in instance]
response = dict(zip(total_instances,instance_id_list))
response.update({"Success":"True"})
return response
else:
instance = client.create_instances(
DryRun= dryrun,
ImageId=image_id,
MinCount=int(min_count),
MaxCount=int(max_count),
InstanceType=instance_type,
KeyName=key_name,
UserData= user_data
)
#parsing response
total_instances = ["instance_id_"+str(i) for i in range(1,len(instance)+1)]
instance_id_list = [i.id for i in instance]
response = dict(zip(total_instances,instance_id_list))
response.update({"Success":"True"})
return response
except Exception as e:
return f"Exception occured: {e}"
if __name__ == "__main__":
AWSEC2.run()