def get(self, request):
        tenant_id = get_tenant_id_from_token(request)
        topcount, basis = get_topcount_basis(request)
        if topcount == 0:
            topcount = None
        query = get_query_from_request(request)
        # Get all the tenant logs
        objects = get_objects_from_query(query).filter(
            firewall_rule__tenant__id=tenant_id)
        country = request.data.get('country', None)
        if (country is not None) and (country != 'undefined'):
            ips = Country.objects.filter(iso_code=country).values('ip_address')
            objects = objects.filter(source_ip__in=ips)

        # Group by minute
        objects = groupby_date(objects,
                               'logged_datetime',
                               'hour', ['bytes_sent', 'bytes_received'],
                               output_fields=['application__name'])
        top_apps = {}
        response = defaultdict(list)
        for data in objects:
            date = data['date'].timestamp()
            application = data['application__name']
            bytes_total = data['bytes_sent'] + data['bytes_received']
            top_apps[application] = top_apps.get(application, 0) + bytes_total
            response[application].append([date, bytes_total])
        final_response = {}
        for key, _ in sorted(top_apps.items(),
                             key=operator.itemgetter(1),
                             reverse=True)[:topcount]:
            final_response[key] = get_sorted(response[key])

        return Response({"data": final_response})
 def get(self, request):
     tenant_id = get_tenant_id_from_token(request)
     topcount, basis = get_topcount_basis(request)
     query = get_query_from_request(request)
     objects = get_objects_from_query(query).filter(
         firewall_rule__tenant__id=tenant_id, ).values(
             'destination_port').annotate(data=Sum(basis)).order_by('-data')
     response = []
     for data in objects[:topcount]:
         response.append([data['destination_port'], data['data']])
     return Response({"data": response})
Ejemplo n.º 3
0
def edit_rule(request):
    def handle_empty_regex(string):
        if string == '*':
            return '.*'
        return string
    tenant_id = get_tenant_id_from_token(request)
    serializer = RuleEditSerializer(data=request.data)
    if not serializer.is_valid():
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
    source_address = handle_empty_regex(serializer.data['source_address'])
    destination_address = handle_empty_regex(
        serializer.data['destination_address'])
    application = handle_empty_regex(serializer.data['application'])
    description = serializer.data.get('description', '')
    query = {
        'firewall_rule__tenant__id': tenant_id,
        'source_address__regex': source_address,
        'destination_address__regex': destination_address,
        'application__regex': application,
        'is_anomalous_rule': False,
        'parent__isnull': True
    }

    results = TrafficRule.objects.filter(**query)
    if not results.count():
        return Response({
            "error": "Input does not match any rules"
        })
    # lock_rule_table()

    # unlock_rule_table()
    firewall_rule = FirewallRule.objects.filter(tenant__id=tenant_id)[0]
    rule_name = f'{source_address}--{destination_address}--{application}'
    user = get_user_from_token(request)
    parent_rule = TrafficRule(
        firewall_rule=firewall_rule,
        name=rule_name,
        source_address=source_address,
        destination_address=destination_address,
        application=application,
        description=description,
        is_verified_rule=True,
        is_anomalous_rule=False,
        verified_by_user=user,
        is_generic=True,
        parent=None
    )
    parent_rule.save()
    results.update(parent=parent_rule)
    parent_rule.parent = None
    parent_rule.save()
    return Response(serializer.data)
Ejemplo n.º 4
0
def flag_rule(request, id):
    try:
        tenant_id = get_tenant_id_from_token(request)
        rule = TrafficRule.objects.get(
            id=id, firewall_rule__tenant__id=tenant_id)
    except Exception as e:
        return Response({
            "traceback": str(traceback.format_exc()),
            "exception": str(e)
        }, status=HTTP_400_BAD_REQUEST)
    rule.is_anomalous_rule = True
    rule.is_verified_rule = False
    rule.verified_by_user = get_user_from_token(request)
    rule.description = request.data.get('description', '')
    rule.save()
    return Response({
        "status": "Rule marked as an anomaly"
    })
Ejemplo n.º 5
0
def delete_rule(request, id):
    try:
        tenant_id = get_tenant_id_from_token(request)
        rule = TrafficRule.objects.get(
            id=id, firewall_rule__tenant__id=tenant_id)
    except Exception as e:
        return Response({
            "traceback": str(traceback.format_exc()),
            "exception": str(e)
        }, status=HTTP_400_BAD_REQUEST)
    if rule.is_generic:
        rule.delete()
    else:
        rule.is_verified_rule = False
        rule.is_anomalous_rule = False
        rule.verified_by_user = None
        rule.description = None
        rule.save()
    return Response({
        "status": "Rule deleted"
    })