Skip to content
Open
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
47 changes: 32 additions & 15 deletions greedybear/process_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,23 @@ def _process_related_urls(saved_ioc: IOC, ip_hits: list[Hit]) -> None:

def _process_commands(ip_hits: list[Hit]) -> None:
"""
Deduplicates and registers order-preserving sequences of executed commands from raw hits.
Deduplicates and registers order-preserving sequences of executed commands
from raw hits.

Generates a unique SHA-256 hash representing the complete sequence to handle
idempotent generation of CommandSequence records.
Uses the latest event timestamp as last_seen. If no valid event timestamp
is available, falls back to the current time.
"""
# commands have semantic meaning in order ("cd /tmp; wget ...").
# A set would lose that. We deduplicate repeated identical lines
# while keeping the first occurrence in sequence.
# Preserve command order while removing duplicate commands.
seen: set[str] = set()
unique_commands: list[str] = []
observed_at: datetime | None = None

for hit in ip_hits:
# Track the latest actual event timestamp.
timestamp = hit.get_time("@timestamp")
if timestamp is not None and (observed_at is None or timestamp > observed_at):
observed_at = timestamp

cmd = hit.get("_command")
if cmd and cmd.strip() and cmd not in seen:
seen.add(cmd)
Expand All @@ -147,22 +153,33 @@ def _process_commands(ip_hits: list[Hit]) -> None:
if not unique_commands:
return

# CommandSequence.commands_hash is a unique constraint. The hash
# is the deduplication key, same commands = same hash = same row.
# Fall back to processing time only when no valid event timestamp exists.
if observed_at is None:
observed_at = timezone.now()

# Same ordered command sequence produces the same hash.
commands_hash = hash_command_sequence(unique_commands)
_, created = CommandSequence.objects.get_or_create(

cmd_seq, created = CommandSequence.objects.get_or_create(
commands_hash=commands_hash,
defaults={
"commands": unique_commands,
"first_seen": timezone.now(),
"last_seen": timezone.now(),
"first_seen": observed_at,
"last_seen": observed_at,
},
)
# the link goes through CowrieSession, which needs a valid hex

# For an existing sequence, update only last_seen.
# Never move it backwards when an older event is processed.
if not created and observed_at > cmd_seq.last_seen:
cmd_seq.last_seen = observed_at
cmd_seq.save(update_fields=["last_seen"])

# The link goes through CowrieSession, which needs a valid hex
# session_id. RawEvent.session_id is free text (may be empty or
# non-hex). our discussion https://github.com/GreedyBear-Project/GreedyBear/discussions/1348
# marked session_id → None for now. The ClusterCommandSequences cronjob picks up all sequences in DB
# automatically, no action needed from us.
# non-hex). Our discussion https://github.com/GreedyBear-Project/GreedyBear/discussions/1348
# marked session_id → None for now. The ClusterCommandSequences cronjob
# picks up all sequences in DB automatically; no action needed from us.
if created:
logger.debug(f"created CommandSequence hash={commands_hash[:12]}…")

Expand Down
64 changes: 56 additions & 8 deletions tests/greedybear/test_process_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from api.serializers.events import EventSerializer
from greedybear.cache import Cache
from greedybear.consts import API_CACHE_ALIAS, IOC_DATA_VERSION_KEY
from greedybear.cronjobs.extraction.hit import InvalidHitError
from greedybear.cronjobs.extraction.hit import Hit, InvalidHitError
from greedybear.cronjobs.extraction.strategies.cowrie import CowrieExtractionStrategy
from greedybear.cronjobs.repositories import CowrieSessionRepository, IocRepository, PayloadRepository
from greedybear.models import IOC, CommandSequence, CowrieFileTransfer, CowrieSession, Credential, EventStatus, Honeypot, HoneypotPayload, RawEvent, Sensor
Expand Down Expand Up @@ -284,11 +284,14 @@ def test_urls_sorted_in_db(self):
class TestProcessCommands(CustomTestCase):
def setUp(self):
super().setUp()
# enabling isolated test
# Enabling isolated test
CommandSequence.objects.all().delete()

def _hit(self, cmd):
return {"_command": cmd}
def _hit(self, cmd, timestamp=None):
data = {"_command": cmd}
if timestamp is not None:
data["@timestamp"] = timestamp.isoformat()
return Hit(data)

def test_command_sequence_created(self):
_process_commands([self._hit("whoami"), self._hit("id")])
Expand Down Expand Up @@ -344,21 +347,66 @@ def test_cowrie_extraction_reuses_sequence_stored_by_event_path(self):
_process_commands([self._hit(c) for c in cmds])
event_seq = CommandSequence.objects.get()

session = CowrieSession(session_id=0xABC, source=IOC.objects.create(name="5.6.7.8", type="ip"))
session.commands = CommandSequence(commands=list(cmds), first_seen=timezone.now(), last_seen=timezone.now())
strategy = CowrieExtractionStrategy("Cowrie", ioc_repo=None, sensor_repo=None, session_repo=CowrieSessionRepository())
session = CowrieSession(
session_id=0xABC,
source=IOC.objects.create(name="5.6.7.8", type="ip"),
)
session.commands = CommandSequence(
commands=list(cmds),
first_seen=timezone.now(),
last_seen=timezone.now(),
)
strategy = CowrieExtractionStrategy(
"Cowrie",
ioc_repo=None,
sensor_repo=None,
session_repo=CowrieSessionRepository(),
)

self.assertTrue(strategy._deduplicate_command_sequence(session))
self.assertEqual(session.commands.pk, event_seq.pk)

def test_empty_hits_creates_nothing(self):
_process_commands([{"src_ip": "1.1.1.1"}])
_process_commands([Hit({"src_ip": "1.1.1.1"})])
self.assertEqual(CommandSequence.objects.count(), 0)

def test_empty_command_string_skipped(self):
_process_commands([self._hit("")])
self.assertEqual(CommandSequence.objects.count(), 0)

def test_first_and_last_seen_use_event_timestamp(self):
observed_at = datetime(2026, 1, 1, 12, 0, 0)

_process_commands([self._hit("whoami", observed_at)])

sequence = CommandSequence.objects.get()
self.assertEqual(sequence.first_seen, observed_at)
self.assertEqual(sequence.last_seen, observed_at)

def test_repeated_sequence_updates_last_seen_only(self):
first_seen = datetime(2026, 1, 1, 12, 0, 0)
later_seen = datetime(2026, 1, 2, 12, 0, 0)

_process_commands([self._hit("whoami", first_seen)])
_process_commands([self._hit("whoami", later_seen)])

sequence = CommandSequence.objects.get()
self.assertEqual(sequence.first_seen, first_seen)
self.assertEqual(sequence.last_seen, later_seen)

def test_older_event_does_not_move_last_seen_backwards(self):
first_seen = datetime(2026, 1, 1, 12, 0, 0)
later_seen = datetime(2026, 1, 3, 12, 0, 0)
older_event = datetime(2026, 1, 2, 12, 0, 0)

_process_commands([self._hit("whoami", first_seen)])
_process_commands([self._hit("whoami", later_seen)])
_process_commands([self._hit("whoami", older_event)])

sequence = CommandSequence.objects.get()
self.assertEqual(sequence.first_seen, first_seen)
self.assertEqual(sequence.last_seen, later_seen)


class TestProcessIncomingEvent(CustomTestCase):
def setUp(self):
Expand Down
Loading