49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026 | class BaseEvent:
"""
Represents a piece of data discovered during a BBOT scan.
An Event contains various attributes that provide metadata about the discovered data.
The attributes assist in understanding the context of the Event and facilitate further
filtering and querying. Events are integral in the construction of visual graphs and
are the cornerstone of data exchange between BBOT modules.
You can inherit from this class when creating a new event type. However, it's not always
necessary. You only need to subclass if you want to layer additional functionality on
top of the base class.
Attributes:
type (str): Specifies the type of the event, e.g., `IP_ADDRESS`, `DNS_NAME`.
id (str): An identifier for the event (event type + sha1 hash of data). NOT universally unique.
uuid (UUID): A universally unique identifier for the event.
data (str or dict): The main data for the event, e.g., a URL or IP address.
data_graph (str): Representation of `self.data` for graph nodes (e.g. Neo4j).
data_human (str): Representation of `self.data` for human output.
data_id (str): Representation of `self.data` used to calculate the event's ID (and ultimately its hash, which is used for deduplication)
data_json (str): Representation of `self.data` to be used in JSON serialization.
host (str, IPvXAddress, or IPvXNetwork): The associated IP address or hostname for the event
host_stem (str): An abbreviated representation of hostname that removes the TLD, e.g. "www.evilcorp". Used by the word cloud.
port (int or None): The port associated with the event, if applicable, else None.
words (set): A list of relevant keywords extracted from the event. Used by the word cloud.
scope_distance (int): Indicates how many hops the event is from the main scope; 0 means in-scope.
web_spider_distance (int): The spider distance from the web root, specific to web crawling.
scan (Scanner): The scan object that generated the event.
timestamp (datetime.datetime): The time at which the data was discovered.
resolved_hosts (list of str): List of hosts to which the event data resolves, applicable for URLs and DNS names.
parent (BaseEvent): The parent event that led to the discovery of this event.
parent_id (str): The `id` attribute of the parent event.
parent_uuid (str): The `uuid` attribute of the parent event.
tags (set of str): Descriptive tags for the event, e.g., `mx-record`, `in-scope`.
module (BaseModule): The module that discovered the event.
module_sequence (str): The sequence of modules that participated in the discovery.
Examples:
```json
{
"type": "URL",
"id": "URL:017ec8e5dc158c0fd46f07169f8577fb4b45e89a",
"data": "http://www.blacklanternsecurity.com/",
"web_spider_distance": 0,
"scope_distance": 0,
"scan": "SCAN:4d786912dbc97be199da13074699c318e2067a7f",
"timestamp": 1688526222.723366,
"resolved_hosts": ["185.199.108.153"],
"parent": "OPEN_TCP_PORT:cf7e6a937b161217eaed99f0c566eae045d094c7",
"tags": ["in-scope", "distance-0", "dir", "ip-185-199-108-153", "status-301", "http-title-301-moved-permanently"],
"module": "httpx",
"module_sequence": "httpx"
}
```
"""
# Always emit this event type even if it's not in scope
_always_emit = False
# Always emit events with these tags even if they're not in scope
_always_emit_tags = ["affiliate", "target"]
# Bypass scope checking and dns resolution, distribute immediately to modules
# This is useful for "end-of-line" events like FINDING and VULNERABILITY
_quick_emit = False
# Data validation, if data is a dictionary
_data_validator = None
# Whether to increment scope distance if the child and parent hosts are the same
# Normally we don't want this, since scope distance only increases if the host changes
# But for some events like SOCIAL media profiles, this is required to prevent spidering all of facebook.com
_scope_distance_increment_same_host = False
# Don't allow duplicates to occur within a parent chain
# In other words, don't emit the event if the same one already exists in its discovery context
_suppress_chain_dupes = False
# using __slots__ dramatically reduces memory usage in large scans
__slots__ = [
# Core identification attributes
"_uuid",
"_id",
"_hash",
"_data",
"_data_hash",
# Host-related attributes
"__host",
"_host_original",
"_port",
# Parent-related attributes
"_parent",
"_parent_id",
"_parent_uuid",
# Event metadata
"_type",
"_tags",
"_omit",
"__words",
"_priority",
"_scope_distance",
"_module_priority",
"_graph_important",
"_resolved_hosts",
"_discovery_context",
"_discovery_context_regex",
"_stats_recorded",
"_internal",
"_confidence",
"_dummy",
"_module",
# DNS-related attributes
"dns_children",
"raw_dns_records",
"dns_resolve_distance",
# Web-related attributes
"web_spider_distance",
"parsed_url",
"url_extension",
"num_redirects",
# File-related attributes
"_data_path",
# Public attributes
"module",
"scan",
"timestamp",
]
def __init__(
self,
data,
event_type,
parent=None,
context=None,
module=None,
scan=None,
tags=None,
confidence=100,
timestamp=None,
_dummy=False,
_internal=None,
):
"""
Initializes an Event object with the given parameters.
In most cases, you should use `make_event()` instead of instantiating this class directly.
`make_event()` is much friendlier, and can auto-detect the event type for you.
Attributes:
data (str, dict): The primary data for the event.
event_type (str, optional): Type of the event, e.g., 'IP_ADDRESS'.
parent (BaseEvent, optional): Parent event that led to this event's discovery. Defaults to None.
module (str, optional): Module that discovered the event. Defaults to None.
scan (Scan, optional): BBOT Scan object. Required unless _dummy is True. Defaults to None.
tags (list of str, optional): Descriptive tags for the event. Defaults to None.
confidence (int, optional): Confidence level for the event, on a scale of 1-100. Defaults to 100.
timestamp (datetime, optional): Time of event discovery. Defaults to current UTC time.
_dummy (bool, optional): If True, disables certain data validations. Defaults to False.
_internal (Any, optional): If specified, makes the event internal. Defaults to None.
Raises:
ValidationError: If either `scan` or `parent` are not specified and `_dummy` is False.
"""
self._uuid = uuid.uuid4()
self._id = None
self._hash = None
self._data = None
self.__host = None
self._tags = set()
self._port = None
self._omit = False
self.__words = None
self._parent = None
self._priority = None
self._parent_id = None
self._parent_uuid = None
self._host_original = None
self._scope_distance = None
self._module_priority = None
self._graph_important = False
self._resolved_hosts = set()
self.dns_children = {}
self.raw_dns_records = {}
self._discovery_context = ""
self._discovery_context_regex = re.compile(r"\{(?:event|module)[^}]*\}")
self.web_spider_distance = 0
# for creating one-off events without enforcing parent requirement
self._dummy = _dummy
self.module = module
self._type = event_type
# keep track of whether this event has been recorded by the scan
self._stats_recorded = False
if timestamp is not None:
self.timestamp = timestamp
else:
try:
self.timestamp = datetime.datetime.now(datetime.UTC)
except AttributeError:
self.timestamp = datetime.datetime.utcnow()
self.confidence = int(confidence)
self._internal = False
# self.scan holds the instantiated scan object (for helpers, etc.)
self.scan = scan
if (not self.scan) and (not self._dummy):
raise ValidationError("Must specify scan")
try:
self.data = self._sanitize_data(data)
except Exception as e:
log.trace(traceback.format_exc())
raise ValidationError(f'Error sanitizing event data "{data}" for type "{self.type}": {e}')
if not self.data:
raise ValidationError(f'Invalid event data "{data}" for type "{self.type}"')
self.parent = parent
if (not self.parent) and (not self._dummy):
raise ValidationError("Must specify event parent")
if tags is not None:
for tag in tags:
self.add_tag(tag)
# internal events are not ingested by output modules
if not self._dummy:
# removed this second part because it was making certain sslcert events internal
if _internal: # or parent._internal:
self.internal = True
if not context:
context = getattr(self.module, "default_discovery_context", "")
if context:
self.discovery_context = context
@property
def data(self):
return self._data
@property
def confidence(self):
return self._confidence
@confidence.setter
def confidence(self, confidence):
self._confidence = min(100, max(1, int(confidence)))
@property
def cumulative_confidence(self):
"""
Considers the confidence of parent events. This is useful for filtering out speculative/unreliable events.
E.g. an event with a confidence of 50 whose parent is also 50 would have a cumulative confidence of 25.
A confidence of 100 will reset the cumulative confidence to 100.
"""
if self._confidence == 100 or self.parent is None or self.parent is self:
return self._confidence
return int(self._confidence * self.parent.cumulative_confidence / 100)
@property
def resolved_hosts(self):
if is_ip(self.host):
return {
self.host,
}
return self._resolved_hosts
@data.setter
def data(self, data):
self._hash = None
self._data_hash = None
self._id = None
self.__host = None
self._port = None
self._data = data
@property
def internal(self):
return self._internal
@internal.setter
def internal(self, value):
"""
Marks the event as internal, excluding it from output but allowing normal exchange between scan modules.
Internal events are typically speculative and may not be interesting by themselves but can lead to
the discovery of interesting events. This method sets the `_internal` attribute to True and adds the
"internal" tag.
Examples of internal events include `OPEN_TCP_PORT`s from the `speculate` module,
`IP_ADDRESS`es from the `ipneighbor` module, or out-of-scope `DNS_NAME`s that originate
from DNS resolutions.
The purpose of internal events is to enable speculative/explorative discovery without cluttering
the console with irrelevant or uninteresting events.
"""
if value not in (True, False):
raise ValueError(f'"internal" must be boolean, not {type(value)}')
if value is True:
self.add_tag("internal")
else:
self.remove_tag("internal")
self._internal = value
@property
def host(self):
"""
An abbreviated representation of the data that allows comparison with other events.
For host types, this is a hostname.
This allows comparison of an email or a URL with a domain, and vice versa
bob@evilcorp.com --> evilcorp.com
https://evilcorp.com --> evilcorp.com
evilcorp.com:80 --> evilcorp.com
For IP_* types, this is an instantiated object representing the event's data
E.g. for IP_ADDRESS, it could be an ipaddress.IPv4Address() or IPv6Address() object
"""
if self.__host is None:
self.host = self._host()
return self.__host
@host.setter
def host(self, host):
if self._host_original is None:
self._host_original = host
self.__host = host
@property
def host_original(self):
"""
Original host data, in case it was changed due to a wildcard DNS, etc.
"""
if self._host_original is None:
return self.host
return self._host_original
@property
def host_filterable(self):
"""
A string version of the event that's used for regex-based blacklisting.
For example, the user can specify "REGEX:.*.evilcorp.com" in their blacklist, and this regex
will be applied against this property.
"""
parsed_url = getattr(self, "parsed_url", None)
if parsed_url is not None:
return parsed_url.geturl()
if self.host is not None:
return str(self.host)
return ""
@property
def port(self):
self.host
if getattr(self, "parsed_url", None):
if self.parsed_url.port is not None:
return self.parsed_url.port
elif self.parsed_url.scheme == "https":
return 443
elif self.parsed_url.scheme == "http":
return 80
return self._port
@property
def netloc(self):
if self.host and is_ip_type(self.host, network=False):
return make_netloc(self.host, self.port)
return None
@property
def host_stem(self):
"""
An abbreviated representation of hostname that removes the TLD
E.g. www.evilcorp.com --> www.evilcorp
"""
if self.host and type(self.host) == str:
return domain_stem(self.host)
else:
return f"{self.host}"
@property
def discovery_context(self):
return self._discovery_context
@discovery_context.setter
def discovery_context(self, context):
def replace(match):
s = match.group()
return s.format(module=self.module, event=self)
try:
self._discovery_context = self._discovery_context_regex.sub(replace, context)
except Exception as e:
log.trace(f"Error formatting discovery context for {self}: {e} (context: '{context}')")
self._discovery_context = context
@property
def discovery_path(self):
"""
This event's full discovery context, including those of all its parents
"""
discovery_path = []
if self.parent is not None and self.parent is not self:
discovery_path = self.parent.discovery_path
return discovery_path + [self.discovery_context]
@property
def parent_chain(self):
"""
This event's full discovery context, including those of all its parents
"""
parent_chain = []
if self.parent is not None and self.parent is not self:
parent_chain = self.parent.parent_chain
return parent_chain + [str(self.uuid)]
@property
def words(self):
if self.__words is None:
self.__words = set(self._words())
return self.__words
def _words(self):
return set()
@property
def tags(self):
return self._tags
@tags.setter
def tags(self, tags):
self._tags = set()
if isinstance(tags, str):
tags = (tags,)
for tag in tags:
self.add_tag(tag)
def add_tag(self, tag):
self._tags.add(tagify(tag))
def add_tags(self, tags):
for tag in set(tags):
self.add_tag(tag)
def remove_tag(self, tag):
with suppress(KeyError):
self._tags.remove(tagify(tag))
@property
def always_emit(self):
"""
If this returns True, the event will always be distributed to output modules regardless of scope distance
"""
always_emit_tags = any(t in self.tags for t in self._always_emit_tags)
no_host_information = not bool(self.host)
return self._always_emit or always_emit_tags or no_host_information
@property
def id(self):
"""
A uniquely identifiable hash of the event from the event type + a SHA1 of its data
"""
if self._id is None:
self._id = f"{self.type}:{self.data_hash.hex()}"
return self._id
@property
def uuid(self):
"""
A universally unique identifier for the event
"""
return f"{self.type}:{self._uuid}"
@property
def data_hash(self):
"""
A raw byte hash of the event's data
"""
if self._data_hash is None:
self._data_hash = sha1(self.data_id).digest()
return self._data_hash
@property
def scope_distance(self):
return self._scope_distance
@scope_distance.setter
def scope_distance(self, scope_distance):
"""
Setter for the scope_distance attribute, ensuring it only decreases.
The scope_distance attribute is designed to never increase; it can only be set to smaller values than
the current one. If a larger value is provided, it is ignored. The setter also updates the event's
tags to reflect the new scope distance.
Parameters:
scope_distance (int): The new scope distance to set, must be a non-negative integer.
Note:
The method will automatically update the relevant 'distance-' tags associated with the event.
"""
if scope_distance < 0:
raise ValueError(f"Invalid scope distance: {scope_distance}")
# ensure scope distance does not increase (only allow setting to smaller values)
if self.scope_distance is None:
new_scope_distance = scope_distance
else:
new_scope_distance = min(self.scope_distance, scope_distance)
if self._scope_distance != new_scope_distance:
# remove old scope distance tags
self._scope_distance = new_scope_distance
self.refresh_scope_tags()
# apply recursively to parent events
parent_scope_distance = getattr(self.parent, "scope_distance", None)
if parent_scope_distance is not None and self.parent is not self:
self.parent.scope_distance = new_scope_distance + 1
def refresh_scope_tags(self):
for t in list(self.tags):
if t.startswith("distance-"):
self.remove_tag(t)
if self.host:
if self.scope_distance == 0:
self.add_tag("in-scope")
self.remove_tag("affiliate")
else:
self.remove_tag("in-scope")
self.add_tag(f"distance-{self.scope_distance}")
@property
def scope_description(self):
"""
Returns a single word describing the scope of the event.
"in-scope" if the event is in scope, "affiliate" if it's an affiliate, otherwise "distance-{scope_distance}"
"""
if self.scope_distance == 0:
return "in-scope"
elif "affiliate" in self.tags:
return "affiliate"
return f"distance-{self.scope_distance}"
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, parent):
"""
Setter for the parent attribute, ensuring it's a valid event and updating scope distance.
Sets the parent of the event and automatically adjusts the scope distance based on the parent event's
scope distance. The scope distance is incremented by 1 if the host of the parent event is different
from the current event's host.
Parameters:
parent (BaseEvent): The new parent event to set. Must be a valid event object.
Note:
If an invalid parent is provided and the event is not a dummy, a warning will be logged.
"""
if is_event(parent):
self._parent = parent
hosts_are_same = (self.host and parent.host) and (self.host == parent.host)
new_scope_distance = int(parent.scope_distance)
if self.host and parent.scope_distance is not None:
# only increment the scope distance if the host changes
if self._scope_distance_increment_same_host or not hosts_are_same:
new_scope_distance += 1
self.scope_distance = new_scope_distance
# inherit certain tags
if hosts_are_same:
# inherit web spider distance from parent
self.web_spider_distance = getattr(parent, "web_spider_distance", 0)
event_has_url = getattr(self, "parsed_url", None) is not None
for t in parent.tags:
if t in ("affiliate",):
self.add_tag(t)
elif t.startswith("mutation-"):
self.add_tag(t)
# only add these tags if the event has a URL
if event_has_url:
if t in ("spider-danger", "spider-max"):
self.add_tag(t)
elif not self._dummy:
log.warning(f"Tried to set invalid parent on {self}: (got: {repr(parent)} ({type(parent)}))")
@property
def children(self):
return []
@property
def parent_id(self):
parent_id = getattr(self.get_parent(), "id", None)
if parent_id is not None:
return parent_id
return self._parent_id
@property
def parent_uuid(self):
parent_uuid = getattr(self.get_parent(), "uuid", None)
if parent_uuid is not None:
return parent_uuid
return self._parent_uuid
@property
def validators(self):
"""
Depending on whether the scan attribute is accessible, return either a config-aware or non-config-aware validator
This exists to prevent a chicken-and-egg scenario during the creation of certain events such as URLs,
whose sanitization behavior is different depending on the config.
However, thanks to this property, validation can still work in the absence of a config.
"""
if self.scan is not None:
return self.scan.helpers.config_aware_validators
return validators
def get_parent(self):
"""
Takes into account events with the _omit flag
"""
if getattr(self.parent, "_omit", False):
return self.parent.get_parent()
return self.parent
def get_parents(self, omit=False, include_self=False):
parents = []
e = self
if include_self:
parents.append(self)
while 1:
if omit:
parent = e.get_parent()
else:
parent = e.parent
if parent is None:
break
if e == parent:
break
parents.append(parent)
e = parent
return parents
def clone(self):
# Create a shallow copy of the event first
cloned_event = copy(self)
# Re-assign a new UUID
cloned_event._uuid = uuid.uuid4()
return cloned_event
def _host(self):
return ""
def _sanitize_data(self, data):
"""
Validates and sanitizes the event's data during instantiation.
By default, uses the '_data_load' method to pre-process the data and then applies the '_data_validator'
to validate and create a sanitized dictionary. Raises a ValidationError if any of the validations fail.
Subclasses can override this method to provide custom validation logic.
Returns:
Any: The sanitized data.
Raises:
ValidationError: If the data fails to validate.
"""
data = self._data_load(data)
if self._data_validator is not None:
if not isinstance(data, dict):
raise ValidationError(f"data is not of type dict: {data}")
data = self._data_validator(**data).model_dump(exclude_none=True)
return self.sanitize_data(data)
def sanitize_data(self, data):
return data
@property
def data_human(self):
"""
Human representation of event.data
"""
return self._data_human()
def _data_human(self):
if isinstance(self.data, (dict, list)):
with suppress(Exception):
return json.dumps(self.data, sort_keys=True)
return smart_decode(self.data)
def _data_load(self, data):
"""
How to load the event data (JSON-decode it, etc.)
"""
return data
@property
def data_id(self):
"""
Representation of the event.data used to calculate the event's ID
"""
return self._data_id()
def _data_id(self):
return self.data
@property
def pretty_string(self):
"""
A human-friendly representation of the event's data. Used for graph representation.
If the event's data is a dictionary, the function will try to return a JSON-formatted string.
Otherwise, it will use smart_decode to convert the data into a string representation.
Override if necessary.
Returns:
str: The graphical representation of the event's data.
"""
return self._pretty_string()
def _pretty_string(self):
return self._data_human()
@property
def data_graph(self):
"""
Representation of event.data for neo4j graph nodes
"""
return self.pretty_string
@property
def data_json(self):
"""
JSON representation of event.data
"""
return self.data
def __contains__(self, other):
"""
Membership checks for Events.
Supports:
- some_event in other_event (event vs event)
- "host:port" in other_event (string coerced to an event)
"""
# Fast path: already an Event
if is_event(other):
other_event = other
else:
try:
other_event = make_event(other, dummy=True)
except ValidationError:
return False
# if hashes match
if other_event == self:
return True
# if hosts match (including subnet / domain containment)
if self.host and other_event.host:
if self.host == other_event.host:
return True
# hostnames and IPs
radixtarget = RadixTarget()
radixtarget.insert(self.host)
return bool(radixtarget.search(other_event.host))
return False
def json(self, mode="json", siem_friendly=False):
"""
Serializes the event object to a JSON-compatible dictionary.
By default, it includes attributes such as 'type', 'id', 'data', 'scope_distance', and others that are present.
Additional specific attributes can be serialized based on the mode specified.
Parameters:
mode (str): Specifies the data serialization mode. Default is "json". Other options include "graph", "human", and "id".
siem_friendly (bool): Whether to format the JSON in a way that's friendly to SIEM ingestion by Elastic, Splunk, etc. This ensures the value of "data" is always the same type (a dictionary).
Returns:
dict: JSON-serializable dictionary representation of the event object.
"""
j = {}
# type, ID, scope description
for i in ("type", "id", "uuid", "scope_description", "netloc"):
v = getattr(self, i, "")
if v:
j.update({i: str(v)})
# event data
data_attr = getattr(self, f"data_{mode}", None)
if data_attr is not None:
data = data_attr
else:
data = smart_decode(self.data)
if siem_friendly:
j["data"] = {self.type: data}
else:
j["data"] = data
# host, dns children
if self.host:
j["host"] = str(self.host)
j["resolved_hosts"] = sorted(str(h) for h in self.resolved_hosts)
j["dns_children"] = {k: list(v) for k, v in self.dns_children.items()}
if isinstance(self.port, int):
j["port"] = self.port
# web spider distance
web_spider_distance = getattr(self, "web_spider_distance", None)
if web_spider_distance is not None:
j["web_spider_distance"] = web_spider_distance
# scope distance
j["scope_distance"] = self.scope_distance
# scan
if self.scan:
j["scan"] = self.scan.id
# timestamp
j["timestamp"] = self.timestamp.isoformat()
# parent event
parent_id = self.parent_id
if parent_id:
j["parent"] = parent_id
parent_uuid = self.parent_uuid
if parent_uuid:
j["parent_uuid"] = parent_uuid
# tags
if self.tags:
j.update({"tags": list(self.tags)})
# parent module
if self.module:
j.update({"module": str(self.module)})
# sequence of modules that led to discovery
if self.module_sequence:
j.update({"module_sequence": str(self.module_sequence)})
# discovery context
j["discovery_context"] = self.discovery_context
j["discovery_path"] = self.discovery_path
j["parent_chain"] = self.parent_chain
# parameter envelopes
parameter_envelopes = getattr(self, "envelopes", None)
if parameter_envelopes is not None:
j["envelopes"] = parameter_envelopes.to_dict()
# normalize non-primitive python objects
for k, v in list(j.items()):
if k == "data":
continue
if type(v) not in (str, int, float, bool, list, dict, type(None)):
try:
j[k] = json.dumps(v, sort_keys=True)
except Exception:
j[k] = smart_decode(v)
return j
@staticmethod
def from_json(j):
"""
Convenience shortcut to create an Event object from a JSON-compatible dictionary.
Calls the `event_from_json()` function to deserialize the event.
Parameters:
j (dict): The JSON-compatible dictionary containing event data.
Returns:
Event: The deserialized Event object.
"""
return event_from_json(j)
@property
def module_sequence(self):
"""
Get a human-friendly string that represents the sequence of modules responsible for generating this event.
Includes the names of omitted parent events to provide a complete view of the module sequence leading to this event.
Returns:
str: The module sequence in human-friendly format.
"""
module_name = getattr(self.module, "name", "")
if getattr(self.parent, "_omit", False):
module_name = f"{self.parent.module_sequence}->{module_name}"
return module_name
@property
def module_priority(self):
if self._module_priority is None:
module = getattr(self, "module", None)
self._module_priority = int(max(1, min(5, getattr(module, "priority", 3))))
return self._module_priority
@module_priority.setter
def module_priority(self, priority):
self._module_priority = int(max(1, min(5, priority)))
@property
def priority(self):
if self._priority is None:
timestamp = self.timestamp.timestamp()
if self.parent.timestamp == self.timestamp:
self._priority = (timestamp,)
else:
self._priority = getattr(self.parent, "priority", ()) + (timestamp,)
return self._priority
@property
def type(self):
return self._type
@type.setter
def type(self, val):
self._type = val
self._hash = None
self._id = None
@property
def _host_size(self):
"""
Used for sorting events by their host size, so that parent ones (e.g. IP subnets) come first
"""
if self.host:
if isinstance(self.host, str):
# smaller domains should come first
return len(self.host)
else:
try:
# bigger IP subnets should come first
return -self.host.num_addresses
except AttributeError:
# IP addresses default to 1
return 1
return 0
def __iter__(self):
"""
For dict(event)
"""
yield from self.json().items()
def __lt__(self, other):
"""
For queue sorting
"""
return self.priority < getattr(other, "priority", (0,))
def __gt__(self, other):
"""
For queue sorting
"""
return self.priority > getattr(other, "priority", (0,))
def __eq__(self, other):
"""
Event equality is **only** defined between Event instances.
Equality is based on the event hash (derived from its id). Comparisons to
non-Event types raise a ValueError to make incorrect comparisons explicit.
"""
if not is_event(other):
raise ValueError("Event equality is only defined between Event instances")
return hash(self) == hash(other)
def __hash__(self):
if self._hash is None:
self._hash = hash(self.id)
return self._hash
def __str__(self):
max_event_len = 80
d = str(self.data).replace("\n", "\\n")
return f'{self.type}("{d[:max_event_len]}{("..." if len(d) > max_event_len else "")}", module={self.module}, tags={self.tags})'
def __repr__(self):
return str(self)
|