Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion api/serializers/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from api.serializers.utils import PresenceFlagField
from greedybear.models import IOC, Sensor, Tag
from greedybear.regex import REGEX_DOMAIN
from greedybear.utils import is_ip_address
from greedybear.utils import is_ip_address, normalize_ip

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -57,6 +57,7 @@ class EnrichmentRequestSerializer(serializers.Serializer):
def validate(self, attrs):
"""
Validate that the query is a valid IP address (IPv4/IPv6) or domain.
IP addresses are normalized so equivalent IPv6 forms match the stored IOC.
"""
observable = attrs["query"].strip()
attrs["query"] = observable
Expand All @@ -66,6 +67,9 @@ def validate(self, attrs):

if not is_ip_address(observable) and not is_domain:
raise serializers.ValidationError("Observable is not a valid IP address or domain")

if is_ip_address(observable):
attrs["query"] = normalize_ip(observable)
return attrs


Expand Down
7 changes: 5 additions & 2 deletions api/serializers/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from rest_framework import serializers

from greedybear.models import EventStatus, Sensor
from greedybear.utils import is_ip_address
from greedybear.utils import is_ip_address, normalize_ip

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -212,7 +212,7 @@ def validate_address(self, value):
"""
if not is_ip_address(value):
raise serializers.ValidationError("Invalid IP address")
return value
return normalize_ip(value)


class SensorCreateResponseSerializer(serializers.Serializer):
Expand Down Expand Up @@ -242,6 +242,9 @@ class EventSerializer(serializers.Serializer):
payload_hash = serializers.CharField(default="", max_length=64, allow_blank=True)
data = SanitizingJSONField(default=dict)

def validate_src_ip(self, value):
return normalize_ip(value)

def validate_timestamp(self, value):
if value > timezone.now():
raise serializers.ValidationError("Timestamp cannot be in the future.")
Expand Down
3 changes: 2 additions & 1 deletion api/views/cowrie_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from api.serializers import CowrieSessionRequestSerializer, CowrieSessionSerializer
from api.views.utils import save_request_source
from greedybear.models import CommandSequence, CowrieSession, ViewType
from greedybear.utils import is_ip_address, is_sha256hash
from greedybear.utils import is_ip_address, is_sha256hash, normalize_ip


def _ip_sort_key(ip: str) -> tuple[int, ipaddress.IPv4Address | ipaddress.IPv6Address]:
Expand Down Expand Up @@ -81,6 +81,7 @@ def get(self, request: Request, *args, **kwargs):
elif not observable:
sessions = sessions_qs.prefetch_related("source", "commands", "credentials")
elif is_ip_address(observable):
observable = normalize_ip(observable)
sessions = sessions_qs.filter(source__name=observable).prefetch_related("source", "commands", "credentials")
if not sessions.exists() and not has_date_filter:
raise Http404(f"No information found for IP: {observable}")
Expand Down
4 changes: 2 additions & 2 deletions api/views/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from greedybear.consts import APISOURCE_LOCKED_THRESHOLD, CACHE_KEY_GREEDYBEAR_NEWS, CACHE_TIMEOUT_SECONDS, RSS_FEED_URL
from greedybear.cronjobs.http_client import HttpClient
from greedybear.models import IOC, APISource, AutonomousSystem, EventStatus, EventStatusType, RawEvent, Sensor, SourceType, Statistics
from greedybear.utils import is_ip_address, is_valid_domain
from greedybear.utils import is_ip_address, is_valid_domain, normalize_ip

logger = logging.getLogger(__name__)

Expand All @@ -40,7 +40,7 @@ def get_request_source_ip(request) -> str:

for candidate in candidates:
if is_ip_address(candidate):
return candidate
return normalize_ip(candidate)

logger.error("Unable to extract valid source IP from request. X-Forwarded-For: %s", forwarded_for)
raise UnableToExtractSourceIPError("No valid source IP found in request metadata")
Expand Down
18 changes: 13 additions & 5 deletions greedybear/cronjobs/extraction/hit.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Any

from greedybear.consts import REQUIRED_ELASTIC_FIELDS, REQUIRED_EVENT_FIELDS
from greedybear.utils import parse_timestamp
from greedybear.utils import normalize_ip, parse_timestamp

log = logging.getLogger(__name__)

Expand All @@ -28,8 +28,11 @@ class Hit(Mapping):

Read access is kept so a hit can be passed to code that treats hits as
plain dicts. It is a Mapping rather than a MutableMapping because the hit
is input data: the one field we add, `_sensor`, is set through
`attach_sensor` so the write lives in here rather than in the pipeline.
is input data that callers should not modify. The class makes two writes
itself: it normalizes `src_ip` on construction, so equivalent IP spellings
map to one standardized form downstream, and it adds `_sensor` through
`attach_sensor`. Both live in here rather than in the pipeline, so the hit
stays read-only from the outside.
"""

def __init__(self, data: dict, required: Iterable[str] = ()):
Expand All @@ -48,6 +51,11 @@ def __init__(self, data: dict, required: Iterable[str] = ()):
for key in required:
self.require(key)

# equivalent IP spellings must map to one canonical form everywhere downstream
src_ip = self._data.get("src_ip")
if isinstance(src_ip, str) and src_ip.strip():
self._data["src_ip"] = normalize_ip(src_ip)
Comment on lines +54 to +57

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The class docstring says it's a read-only mapping but we're changing it here (and I think it's the right pace to do that). Please update the docstring.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated.


@classmethod
def from_elastic(cls, raw: dict) -> "Hit":
"""
Expand Down Expand Up @@ -85,8 +93,8 @@ def attach_sensor(self, sensor) -> None:
"""
Record the sensor that reported this hit, for the strategies to read.

This is the only field GreedyBear adds to a hit, so it is the only
write the class allows.
This is the only field GreedyBear adds to a hit. Apart from the `src_ip`
normalization in `__init__`, it is the only write the class makes.

Args:
sensor: The Sensor the hit was reported by.
Expand Down
2 changes: 2 additions & 0 deletions greedybear/cronjobs/extraction/ioc_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from greedybear.cronjobs.extraction.utils import is_whatsmyip_domain
from greedybear.cronjobs.repositories import IocRepository, SensorRepository
from greedybear.models import IOC, IocType, WhatsMyIPDomain
from greedybear.utils import normalize_ip


class IocProcessor:
Expand Down Expand Up @@ -48,6 +49,7 @@ def add_ioc(
The persisted IOC record, or None if filtered out.
"""
self.log.info(f"processing ioc {ioc} for attack_type {attack_type}")
ioc.name = normalize_ip(ioc.name) # Normalize IP addresses for consistent storage

if ioc.name in self.sensor_repo.cache:
self.log.debug(f"not saved {ioc} because it is a sensor")
Expand Down
10 changes: 6 additions & 4 deletions greedybear/cronjobs/repositories/firehol.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
from django.contrib.postgres.expressions import ArraySubquery
from django.core.exceptions import ValidationError
from django.db import DataError, transaction
from django.db.models import Exists, OuterRef
from django.db.models import Exists, OuterRef, Q
from django.db.models.functions import Cast, Now
from netfields import InetAddressField

from greedybear.models import IOC, FireHolList, IocType
from greedybear.utils import normalize_ip


class FireHolRepository:
Expand Down Expand Up @@ -72,7 +73,7 @@ def get_or_create(self, ip_address: str, source: str) -> tuple[FireHolList | Non

def get_entries_by_ip(self, sources: str | Iterable[str]) -> dict[str, list[str]]:
"""
Get the stored exact IP entries of the given sources, grouped by IP.
Get the stored exact IP entries of the given sources, grouped by normalized IP.

CIDR entries are left out. They need a membership test, not an
equality match, so they are handled separately.
Expand All @@ -83,14 +84,15 @@ def get_entries_by_ip(self, sources: str | Iterable[str]) -> dict[str, list[str]
Returns:
Dict mapping IP address to the list of sources it appears in.
"""
single_hosts = Q(ip_address__family=4, ip_address__prefixlen=32) | Q(ip_address__family=6, ip_address__prefixlen=128)
entries_by_ip = defaultdict(list)
queryset = FireHolList.objects.filter(
ip_address__prefixlen=32,
single_hosts,
source__in=self._normalize_sources(sources),
)

for network, source in queryset.values_list("ip_address", "source"):
entries_by_ip[str(network.network_address)].append(source)
entries_by_ip[normalize_ip(str(network.network_address))].append(source)
return dict(entries_by_ip)

def get_cidr_matches(self, sources: str | Iterable[str]) -> list[tuple[int, list[str]]]:
Expand Down
11 changes: 8 additions & 3 deletions greedybear/cronjobs/repositories/ioc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.db.models import F

from greedybear.models import IOC, Honeypot
from greedybear.utils import normalize_ip

BULK_UPDATE_BATCH_SIZE = 2000

Expand Down Expand Up @@ -123,8 +124,9 @@ def get_ioc_by_name(self, name: str) -> IOC | None:
Returns:
The matching IOC, or None if not found.
"""
normalized_name = normalize_ip(name)
try:
return IOC.objects.prefetch_related("honeypots").get(name=name)
return IOC.objects.prefetch_related("honeypots").get(name=normalized_name)
except IOC.DoesNotExist:
return None

Expand Down Expand Up @@ -188,6 +190,7 @@ def save(self, ioc: IOC) -> IOC:
Returns:
The saved IOC instance.
"""
ioc.name = normalize_ip(ioc.name)
ioc.save()
return ioc

Expand Down Expand Up @@ -295,8 +298,9 @@ def update_ioc_reputation(self, ip_address: str, reputation: str) -> bool:
Returns:
True if IOC was found and updated, False otherwise.
"""
normalized_ip = normalize_ip(ip_address)
try:
ioc = IOC.objects.get(name=ip_address)
ioc = IOC.objects.get(name=normalized_ip)
except IOC.DoesNotExist:
return False
else:
Expand All @@ -318,4 +322,5 @@ def bulk_update_ioc_reputation(self, ip_addresses: list[str], reputation: str) -
"""
if not ip_addresses:
return 0
return IOC.objects.filter(name__in=ip_addresses).update(ip_reputation=reputation)
normalized_ips = [normalize_ip(ip) for ip in ip_addresses]
return IOC.objects.filter(name__in=normalized_ips).update(ip_reputation=reputation)
3 changes: 2 additions & 1 deletion greedybear/cronjobs/repositories/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ def get_or_create_sensor(self, ip: str) -> Sensor | None:
Returns:
Sensor object if valid, None if invalid IP format.
"""
from greedybear.utils import get_ioc_type
from greedybear.utils import get_ioc_type, normalize_ip

ip = normalize_ip(ip)
if ip in self.cache:
return self.cache[ip]
if get_ioc_type(ip) != IP:
Expand Down
19 changes: 19 additions & 0 deletions greedybear/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ def is_ip_address(string: str) -> bool:
return True


def normalize_ip(ip_str: str) -> str:
"""
Normalizes an IP address string.
IPv4 addresses are returned unchanged, IPv4-mapped IPv6 addresses are
converted back to IPv4 and other IPv6 addresses are returned in
lower-case compressed format while invalid input is stripped.
"""
ip_str = ip_str.strip()
try:
ip = ip_address(ip_str)
except ValueError:
return ip_str

if ip.version == 6 and ip.ipv4_mapped:
return str(ip.ipv4_mapped)

return ip.compressed
Comment on lines +37 to +53

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! 👍



def is_non_global_ip(value) -> bool:
"""
Return True when an IP should be treated as non-global/unroutable.
Expand Down
8 changes: 8 additions & 0 deletions tests/api/views/test_cowrie_session_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ def test_ip_address_query_with_similar(self):
self.assertNotIn("sessions", response.data)
self.assertEqual(len(response.data["sources"]), 2)

def test_ipv6_query_is_normalized(self):
"""Test that equivalent IPv6 spellings find the session stored in normalized form."""
ioc = IOC.objects.create(name="2001:db8::1", type=IocType.IP.value)
CowrieSession.objects.create(session_id=0xABC123, source=ioc, duration=10, start_time=self.current_time)
response = self.client.get("/api/cowrie_session?query=2001:DB8:0:0:0:0:0:1")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["sources"], ["2001:db8::1"])

def test_include_similar_excludes_non_positive_duration_sessions(self):
"""Test that include_similar only returns sessions with duration > 0."""
CowrieSession.objects.create(
Expand Down
16 changes: 15 additions & 1 deletion tests/api/views/test_enrichment_view.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rest_framework.test import APIClient

from greedybear.models import HoneypotPayload, Sensor, Statistics, ViewType
from greedybear.models import IOC, HoneypotPayload, IocType, Sensor, Statistics, ViewType
from tests import CustomTestCase


Expand Down Expand Up @@ -94,6 +94,20 @@ def test_valid_domain(self):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["found"], False)

def test_enrichment_normalizes_ipv6_query(self):
"""Equivalent IPv6 spellings find the IOC stored in normalized form."""
IOC.objects.create(
name="2001:db8::1",
type=IocType.IP.value,
first_seen=self.current_time,
last_seen=self.current_time,
)
for query in ["2001:DB8::1", "2001:0db8:0:0:0:0:0:0001"]:
with self.subTest(query=query):
response = self.client.get(f"/api/enrichment?query={query}")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["found"], True)

def test_enrichment_includes_sensors(self):
"""Sensors field appears in enrichment response for authenticated users."""

Expand Down
13 changes: 13 additions & 0 deletions tests/api/views/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ def test_locked_api_source_returns_403(self):


class TestEventsCreateValidation(BaseEventTestCase):
def test_src_ip_normalized(self):
cases = {
"::ffff:1.2.3.4": "1.2.3.4",
"2001:DB8:0:0:0:0:0:1": "2001:db8::1",
}
for raw_ip, expected in cases.items():
with self.subTest(src_ip=raw_ip):
event = valid_event(self.sensor.id, src_ip=raw_ip)
res = self.client.post(EVENTS_URL, {"events": [event]}, format="json")
self.assertEqual(res.status_code, status.HTTP_202_ACCEPTED)
raw = RawEvent.objects.get(batch__task_id=res.data["task_id"])
self.assertEqual(raw.src_ip, expected)

def test_empty_events_list_returns_400(self):
res = self.client.post(EVENTS_URL, {"events": []}, format="json")
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Expand Down
12 changes: 12 additions & 0 deletions tests/api/views/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ def test_creates_sensor(self):
self.assertEqual(sensor.api_source, self.api_source)
self.assertEqual(sensor.source_type, SourceType.EXTERNAL)

def test_ipv4_mapped_address_is_normalized(self):
"""An IPv4-mapped address is stored as plain IPv4 and matches the same sensor."""
mapped_payload = {**VALID_PAYLOAD, "address": "::ffff:1.2.3.4"}
response = self.client.post(SENSOR_CREATE_URL, mapped_payload, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(Sensor.objects.filter(address="1.2.3.4").exists())

# the plain IPv4 form must hit the same sensor
response = self.client.post(SENSOR_CREATE_URL, VALID_PAYLOAD, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Sensor.objects.filter(address="1.2.3.4").count(), 1)

def test_existing_sensor_returns_existing_record(self):
# first request creates sensor
self.client.post(
Expand Down
11 changes: 11 additions & 0 deletions tests/api/views/test_validation_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ def test_get_request_source_ip_supports_ipv6(self):
)
self.assertEqual(get_request_source_ip(request), "2001:db8::1")

def test_get_request_source_ip_normalizes_ip(self):
"""Equivalent IP forms in the forwarded header should be normalized."""
cases = {
"2001:DB8:0:0:0:0:0:1": "2001:db8::1",
"::ffff:203.0.113.5": "203.0.113.5",
}
for header, expected in cases.items():
with self.subTest(header=header):
request = SimpleNamespace(META={"HTTP_X_FORWARDED_FOR": header})
self.assertEqual(get_request_source_ip(request), expected)

def test_get_request_source_ip_raises_exception_when_invalid(self):
"""Raise UnableToExtractSourceIPError when no valid source IP can be extracted."""
request = SimpleNamespace(
Expand Down
11 changes: 11 additions & 0 deletions tests/greedybear/cronjobs/test_hit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ def test_reads_like_a_dict(self):
self.assertIn("src_ip", hit)
self.assertEqual(len(hit), 1)

def test_src_ip_is_normalized(self):
"""Equivalent IP spellings are stored in one canonical form."""
cases = {
"2001:DB8:0:0:0:0:0:1": "2001:db8::1",
"::ffff:1.2.3.4": "1.2.3.4",
}
for raw_ip, expected in cases.items():
with self.subTest(src_ip=raw_ip):
hit = Hit.from_elastic({"src_ip": raw_ip, "type": "Cowrie"})
self.assertEqual(hit["src_ip"], expected)

def test_attach_sensor_is_the_only_write(self):
"""ExtractionPipeline.execute() records the sensor on the way through."""
hit = Hit({"src_ip": "1.2.3.4"})
Expand Down
Loading
Loading