Skip to content

Commit 309a294

Browse files
committed
Update
1 parent fe245ea commit 309a294

12 files changed

+474
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# blstsecurity-aws-loggers
2+
3+
## BLST connector agents
4+
### What this is all about?
5+
BLST aims to replace the manual penetration tester by developing an advanced AI model that uses Machine Learning to identify anomalies and simulate real-world logic attacks on your application.
6+
7+
### What is this repo for?
8+
These connector agents are meant to connect users to our systems via varius methods.
9+
10+
### How to install and test?
11+
You can find instructions on how to install the EC2 traffic mirroring agent in this [address](mirror-traffic/EC2/EC2_Lambda_installation_instructions.pdf) <br>
12+
You can find instructions on how to install the API Gateway agent in this [address](api-gateway/API_Gateway_Lambda_installation_instructions.pdf)
13+
14+
#### We would love to hear your comments and responses!
96 KB
Binary file not shown.

api-gateway/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# blstsecurity-aws-loggers
2+
676 KB
Binary file not shown.

api-gateway/lambda_function.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import json
2+
import boto3
3+
from datetime import datetime, timedelta
4+
import time
5+
import requests
6+
import random
7+
8+
logs = boto3.client('logs')
9+
gateways = boto3.client('apigateway')
10+
events = boto3.client('events')
11+
lambdas = boto3.client('lambda')
12+
13+
def put_rule(name):
14+
rule_name = name + '-rule'
15+
lambda_details = lambdas.get_function(FunctionName=name)
16+
lambda_arn = ''
17+
lambda_role = ''
18+
if 'Configuration' in lambda_details:
19+
lambda_arn = lambda_details['Configuration']['FunctionArn']
20+
lambda_role = lambda_details['Configuration']['Role']
21+
if lambda_arn != '':
22+
response = events.list_rule_names_by_target(
23+
TargetArn=lambda_arn
24+
)
25+
if not len(response['RuleNames']):
26+
rule_arn = events.put_rule(
27+
Name=rule_name,
28+
ScheduleExpression='rate(10 minutes)',
29+
State='ENABLED',
30+
Description='rule for running blstsecurity logs'
31+
)
32+
events.put_targets(
33+
Rule=rule_name,
34+
Targets=[
35+
{
36+
'Arn': lambda_arn,
37+
'Id': 'blstsecurity_logs_event_target',
38+
}
39+
]
40+
)
41+
lambdas.add_permission(
42+
FunctionName=name,
43+
StatementId='AWS_Event' + str(random.randint(100000,999999)),
44+
Action='lambda:InvokeFunction',
45+
Principal='events.amazonaws.com',
46+
SourceArn=rule_arn['RuleArn']
47+
)
48+
49+
def get_timestamp(data):
50+
return data[0]['value']
51+
52+
def get_id(data):
53+
return data[1]['value'][1:36]
54+
55+
def get_logs_from_group(log_group, start_time, query):
56+
date_start_time = datetime.fromtimestamp(start_time)
57+
start_query_response = logs.start_query(
58+
logGroupName=log_group,
59+
startTime=start_time - 30,
60+
endTime=start_time + 600,
61+
queryString=query,
62+
)
63+
query_id = start_query_response['queryId']
64+
response = None
65+
while response == None or response['status'] == 'Running':
66+
time.sleep(1)
67+
response = logs.get_query_results(
68+
queryId=query_id
69+
)
70+
data=[]
71+
response['results'].sort(key=lambda data: (get_id(data), get_timestamp(data)))
72+
prev_stream_key = ''
73+
stream_arr = []
74+
add_stream = False
75+
for stream in response['results']:
76+
stream_key = stream[1]['value'][1:36]
77+
log_time = stream[0]['value']
78+
stream_message = stream[1]['value'][39:]
79+
date_log_time = datetime.strptime(log_time, '%Y-%m-%d %H:%M:%S.%f')
80+
if date_log_time > date_start_time and 'response body after transformations:' in stream_message[0:85]:
81+
add_stream = True
82+
if prev_stream_key != '' and stream_key != prev_stream_key:
83+
if add_stream and len(stream_arr):
84+
data.append(stream_arr)
85+
stream_arr = []
86+
add_stream = False
87+
stream_arr.append({"time":log_time,"message":stream_message,"id":stream_key})
88+
prev_stream_key = stream_key
89+
if add_stream:
90+
data.append(stream_arr)
91+
return {"log_group_name":log_group,"data":data}
92+
93+
def lambda_handler(event, context):
94+
start_time = int((datetime.today() - timedelta(minutes=13)).timestamp())
95+
query = "fields @timestamp, @message"
96+
put_rule('blstsecurity-logs')
97+
for log_group in logs.describe_log_groups(logGroupNamePrefix='API-Gateway-Execution-Logs_')['logGroups']:
98+
api_log_group = get_logs_from_group(log_group['logGroupName'], start_time, query)
99+
if 'data' in api_log_group and len(api_log_group['data']):
100+
requests.post('https://z2yh3zbaw1.execute-api.eu-central-1.amazonaws.com/poc/send', data = json.dumps(api_log_group))
101+
102+
return 'success'
47 KB
Binary file not shown.

mirror-traffic/EC2/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# blstsecurity-aws-loggers
2+
1.8 KB
Binary file not shown.
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import json
2+
import boto3
3+
import os
4+
import time
5+
6+
ram = boto3.client('ram')
7+
ec2 = boto3.client('ec2')
8+
9+
blstsec_account = os.environ['BLSTSECURITY_ACCOUNT']
10+
blstsec_destination = os.environ['BLSTSECURITY_ROUTE_DESTINATION']
11+
source_instance_id = os.environ['SOURCE_INSTANCE_ID']
12+
13+
def get_instance_data():
14+
instance_data = ec2.describe_instances(
15+
InstanceIds=[
16+
source_instance_id
17+
]
18+
)['Reservations'][0]['Instances'][0]['NetworkInterfaces'][0]
19+
source_cidr = ec2.describe_vpcs(
20+
VpcIds=[
21+
instance_data['VpcId']
22+
]
23+
)['Vpcs'][0]['CidrBlock']
24+
print('Your CIDR Block is: ' + source_cidr)
25+
route_table_id = ''
26+
try:
27+
route_table_id = ec2.describe_route_tables(
28+
Filters=[
29+
{
30+
'Name': 'association.subnet-id',
31+
'Values': [
32+
instance_data['SubnetId']
33+
]
34+
}
35+
]
36+
)['RouteTables'][0]['RouteTableId']
37+
except Exception as e:
38+
route_tables_data = ec2.describe_route_tables(
39+
Filters=[
40+
{
41+
'Name': 'vpc-id',
42+
'Values': [
43+
instance_data['VpcId']
44+
]
45+
}
46+
]
47+
)['RouteTables']
48+
is_main = False
49+
if route_tables_data[0]['Associations'][0]['Main']:
50+
route_table_id = route_tables_data[0]['Associations'][0]['RouteTableId']
51+
is_main = True
52+
route_tables_index = 1
53+
while not is_main and len(route_tables_data) > route_tables_index:
54+
if route_tables_data[route_tables_index]['Associations'][0]['Main']:
55+
route_table_id = route_tables_data[route_tables_index]['Associations'][0]['RouteTableId']
56+
is_main = True
57+
if not is_main:
58+
print('There was an error with finding your route table id, please contact blstsecurity')
59+
return {'vpc_id':instance_data['VpcId'], 'subnet_id':instance_data['SubnetId'], 'network_interface_id':instance_data['NetworkInterfaceId'], 'cidr':source_cidr, 'route_table_id':route_table_id}
60+
61+
def get_resource_share_list():
62+
shared_resources_inv = ram.get_resource_share_invitations()
63+
shared_resources_list = []
64+
for resource in shared_resources_inv['resourceShareInvitations']:
65+
if resource['senderAccountId'] == blstsec_account:
66+
if resource['status'] != 'ACCEPTED':
67+
ram.accept_resource_share_invitation(
68+
resourceShareInvitationArn=resource['resourceShareInvitationArn']
69+
)
70+
shared_resources_list.append(resource['resourceShareArn'])
71+
return shared_resources_list
72+
73+
def get_resource_share_ids(shared_resources_list):
74+
shared_resources_ids_list = {}
75+
shared_resources_ram_list = []
76+
if not len(shared_resources_list):
77+
return shared_resources_ram_list
78+
while len(shared_resources_ram_list) != 2:
79+
shared_resources_ram_list = ram.list_resources(
80+
resourceOwner='OTHER-ACCOUNTS',
81+
resourceShareArns=shared_resources_list
82+
)['resources']
83+
time.sleep(0.05)
84+
for resource in shared_resources_ram_list:
85+
if resource['type'] == 'ec2:TransitGateway':
86+
shared_resources_ids_list['tgw'] = resource['arn'].split('/')[1]
87+
elif resource['type'] == 'ec2:TrafficMirrorTarget':
88+
shared_resources_ids_list['tmt'] = resource['arn'].split('/')[1]
89+
return shared_resources_ids_list
90+
91+
def create_transit_gateway_attachment(tgw_id, source_vpc_id, source_subnet_id):
92+
tgwa = ''
93+
try:
94+
tgwa = ec2.create_transit_gateway_vpc_attachment(
95+
TransitGatewayId=tgw_id,
96+
VpcId=source_vpc_id,
97+
SubnetIds=[source_subnet_id]
98+
)['TransitGatewayVpcAttachment']['TransitGatewayAttachmentId']
99+
except Exception as e:
100+
tgwa = e
101+
102+
def create_traffic_mirror_filter_rule(tmf_id, direction, number):
103+
tmf_rule_id = ''
104+
while tmf_rule_id == '':
105+
try:
106+
tmf_rule_id = ec2.create_traffic_mirror_filter_rule(
107+
TrafficMirrorFilterId=tmf_id,
108+
TrafficDirection=direction,
109+
RuleNumber=number,
110+
RuleAction='accept',
111+
Protocol=6,
112+
DestinationCidrBlock='0.0.0.0/0',
113+
SourceCidrBlock='0.0.0.0/0'
114+
)['TrafficMirrorFilterRule']['TrafficMirrorFilterRuleId']
115+
except Exception as e:
116+
print(e)
117+
time.sleep(0.05)
118+
119+
def create_traffic_mirror_filter():
120+
traffic_mirror_filters = ec2.describe_traffic_mirror_filters(
121+
Filters=[
122+
{
123+
'Name': 'description',
124+
'Values': [
125+
'blstsecurity traffic mirror filter'
126+
]
127+
},
128+
]
129+
)['TrafficMirrorFilters']
130+
if len(traffic_mirror_filters):
131+
return ''
132+
133+
tmf_id = ec2.create_traffic_mirror_filter(
134+
Description='blstsecurity traffic mirror filter'
135+
)['TrafficMirrorFilter']['TrafficMirrorFilterId']
136+
create_traffic_mirror_filter_rule(tmf_id, 'ingress', 100)
137+
create_traffic_mirror_filter_rule(tmf_id, 'egress', 100)
138+
return tmf_id
139+
140+
def create_traffic_mirror_session(source_network_interface_id, tmt_id, tmf_id):
141+
if tmf_id == '':
142+
return
143+
tms = ec2.create_traffic_mirror_session(
144+
NetworkInterfaceId=source_network_interface_id,
145+
TrafficMirrorTargetId=tmt_id,
146+
TrafficMirrorFilterId=tmf_id,
147+
SessionNumber=1,
148+
Description='blstsecurity traffic mirror session'
149+
)
150+
151+
def add_tgw_route_table(route_table_id, tgw_id):
152+
try:
153+
ec2.create_route(
154+
DestinationCidrBlock=blstsec_destination,
155+
TransitGatewayId=tgw_id,
156+
RouteTableId=route_table_id
157+
)
158+
return 'traffic mirroring integration installed successfully'
159+
except:
160+
return 'Wait until blstsecurity will accept the transit gateway attachment and then run the lambda again'
161+
162+
def lambda_handler(event, context):
163+
source_instance_data = get_instance_data()
164+
shared_resources_ids = get_resource_share_ids(get_resource_share_list())
165+
if len(shared_resources_ids):
166+
create_transit_gateway_attachment(shared_resources_ids['tgw'], source_instance_data['vpc_id'] , source_instance_data['subnet_id'])
167+
create_traffic_mirror_session(source_instance_data['network_interface_id'], shared_resources_ids['tmt'], create_traffic_mirror_filter())
168+
return add_tgw_route_table(source_instance_data['route_table_id'], shared_resources_ids['tgw'])
169+
else:
170+
return 'Shared resources not found, please contact blstsecurity for more information'

mirror-traffic/ELB/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# blstsecurity-aws-loggers
2+

0 commit comments

Comments
 (0)