Skip to content

This is a developer reference. For a high-level description of BBOT events including a full list of event types, see Events

make_event

make_event(
    data,
    event_type=None,
    parent=None,
    context=None,
    module=None,
    scan=None,
    tags=None,
    dummy=False,
    internal=None,
)

Creates and returns a new event object.

This function serves as a factory for creating new event objects from raw data. If you need to modify an existing event, use update_event() instead.

Parameters:

  • data (Union[str, dict]) –

    The primary data for the event.

  • event_type (str, default: None ) –

    Type of the event, e.g., 'IP_ADDRESS'. Auto-detected if not provided.

  • parent (BaseEvent, default: None ) –

    Parent event leading to this event's discovery.

  • context (str, default: None ) –

    Description of circumstances leading to event's discovery.

  • module (str, default: None ) –

    Module that discovered the event.

  • scan (Scan, default: None ) –

    BBOT Scan object associated with the event.

  • scans (List[Scan]) –

    Multiple BBOT Scan objects, primarily used for unserialization.

  • tags (Union[str, List[str]], default: None ) –

    Descriptive tags for the event, as a list or a single string.

  • dummy (bool, default: False ) –

    Disables data validations if set to True. Defaults to False.

  • internal (Any, default: None ) –

    Makes the event internal if set to True. Defaults to None.

Returns:

  • BaseEvent

    A new event object.

Raises:

  • ValidationError

    Raised when there's an error in event data or type sanitization.

Source code in bbot/core/event/base.py
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
def make_event(
    data,
    event_type=None,
    parent=None,
    context=None,
    module=None,
    scan=None,
    tags=None,
    dummy=False,
    internal=None,
):
    """
    Creates and returns a new event object.

    This function serves as a factory for creating new event objects from raw data.
    If you need to modify an existing event, use ``update_event()`` instead.

    Parameters:
        data (Union[str, dict]): The primary data for the event.
        event_type (str, optional): Type of the event, e.g., 'IP_ADDRESS'. Auto-detected if not provided.
        parent (BaseEvent, optional): Parent event leading to this event's discovery.
        context (str, optional): Description of circumstances leading to event's discovery.
        module (str, optional): Module that discovered the event.
        scan (Scan, optional): BBOT Scan object associated with the event.
        scans (List[Scan], optional): Multiple BBOT Scan objects, primarily used for unserialization.
        tags (Union[str, List[str]], optional): Descriptive tags for the event, as a list or a single string.
        dummy (bool, optional): Disables data validations if set to True. Defaults to False.
        internal (Any, optional): Makes the event internal if set to True. Defaults to None.

    Returns:
        BaseEvent: A new event object.

    Raises:
        ValidationError: Raised when there's an error in event data or type sanitization.
    """
    if not data:
        raise ValidationError("No data provided")

    # do not allow passing an existing event here – use update_event() instead
    if is_event(data):
        raise ValidationError(
            "make_event() does not accept an existing event object. Use update_event(event, ...) to modify an event."
        )

    # allow tags to be either a string or an array
    if not tags:
        tags = []
    elif isinstance(tags, str):
        tags = [tags]
    tags = set(tags)

    # if event_type is not provided, autodetect it
    if event_type is None:
        event_seed = EventSeed(data)
        event_type = event_seed.type
        data = event_seed.data
        if not dummy:
            log.debug(f'Autodetected event type "{event_type}" based on data: "{data}"')

    event_type = sys.intern(str(event_type).strip().upper())

    # Catch these common whoopsies
    if event_type in ("DNS_NAME", "IP_ADDRESS"):
        # DNS_NAME <--> EMAIL_ADDRESS confusion
        if validators.soft_validate(data, "email"):
            event_type = "EMAIL_ADDRESS"
        else:
            # DNS_NAME <--> IP_ADDRESS confusion
            try:
                data = validators.validate_host(data)
            except Exception as e:
                log.trace(traceback.format_exc())
                data_preview = str(data)[:200] + "..." if len(str(data)) > 200 else str(data)
                raise ValidationError(f'Error sanitizing event data "{data_preview}" for type "{event_type}": {e}')
            data_is_ip = is_ip(data)
            if event_type == "DNS_NAME" and data_is_ip:
                event_type = "IP_ADDRESS"
            elif event_type == "IP_ADDRESS" and not data_is_ip:
                event_type = "DNS_NAME"
    # USERNAME <--> EMAIL_ADDRESS confusion
    if event_type == "USERNAME" and validators.soft_validate(data, "email"):
        event_type = "EMAIL_ADDRESS"
        tags.add("affiliate")
    # Convert single-host IP_RANGE to IP_ADDRESS
    if event_type == "IP_RANGE":
        with suppress(Exception):
            net = ipaddress.ip_network(data, strict=False)
            if net.prefixlen == net.max_prefixlen:
                event_type = "IP_ADDRESS"
                data = net.network_address

    event_class = globals().get(event_type, DefaultEvent)
    return event_class(
        data,
        event_type=event_type,
        parent=parent,
        context=context,
        module=module,
        scan=scan,
        tags=tags,
        _dummy=dummy,
        _internal=internal,
    )

event_from_json

event_from_json(j)

Creates an event object from a JSON dictionary.

This function deserializes a JSON dictionary to create a new event object, using the make_event function for the actual object creation. It sets additional attributes such as the timestamp and scope distance based on the input JSON.

Parameters:

  • j (Dict) –

    JSON dictionary containing the event attributes. Must include keys "data" and "type".

Returns:

  • BaseEvent

    A new event object initialized with attributes from the JSON dictionary.

Raises:

  • ValidationError

    Raised when the JSON dictionary is missing required fields.

Note

The function assumes that the input JSON dictionary is valid and may raise exceptions if required keys are missing. Make sure to validate the JSON input beforehand.

Source code in bbot/core/event/base.py
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
def event_from_json(j):
    """
    Creates an event object from a JSON dictionary.

    This function deserializes a JSON dictionary to create a new event object, using the `make_event` function
    for the actual object creation. It sets additional attributes such as the timestamp and scope distance
    based on the input JSON.

    Parameters:
        j (Dict): JSON dictionary containing the event attributes.
                  Must include keys "data" and "type".

    Returns:
        BaseEvent: A new event object initialized with attributes from the JSON dictionary.

    Raises:
        ValidationError: Raised when the JSON dictionary is missing required fields.

    Note:
        The function assumes that the input JSON dictionary is valid and may raise exceptions
        if required keys are missing. Make sure to validate the JSON input beforehand.
    """
    try:
        event_type = j["type"]
        kwargs = {
            "event_type": event_type,
            "tags": j.get("tags", []),
            "context": j.get("discovery_context", None),
            "dummy": True,
        }
        data = j.get("data_json", None)
        if data is None:
            data = j.get("data", None)
        if data is None:
            json_pretty = json.dumps(j, indent=2)
            raise ValueError(f"data or data_json must be provided. JSON: {json_pretty}")
        kwargs["data"] = data
        event = make_event(**kwargs)
        event_uuid = j.get("uuid", None)
        if event_uuid is not None:
            event._uuid = uuid.UUID(event_uuid.split(":")[-1])

        resolved_hosts = j.get("resolved_hosts", [])
        event._resolved_hosts = frozenset(resolved_hosts) if resolved_hosts else None

        http_title = j.get("http_title", "")
        if http_title:
            try:
                event.http_title = http_title
            except AttributeError:
                pass

        # accept both isoformat and unix timestamp
        try:
            event.timestamp = datetime.datetime.fromtimestamp(j["timestamp"], ZoneInfo("UTC"))
        except Exception:
            event.timestamp = datetime.datetime.fromisoformat(j["timestamp"])
        event.scope_distance = j["scope_distance"]
        parent_id = j.get("parent", None)
        if parent_id is not None:
            event._parent_id = parent_id
        parent_uuid = j.get("parent_uuid", None)
        if parent_uuid is not None:
            parent_type, parent_uuid = parent_uuid.split(":", 1)
            event._parent_uuid = parent_type + ":" + str(uuid.UUID(parent_uuid))
        return event
    except KeyError as e:
        raise ValidationError(f"Event missing required field: {e}")

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) –

    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:

{
    "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", "status-301"],
    "http_title": "301 Moved Permanently",
    "module": "http",
    "module_sequence": "http"
}
Source code in bbot/core/event/base.py
  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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
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", "status-301"],
            "http_title": "301 Moved Permanently",
            "module": "http",
            "module_sequence": "http"
        }
        ```
    """

    # 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", "seed"]
    # Bypass scope checking and dns resolution, distribute immediately to modules
    # This is useful for "end-of-line" events like FINDING
    _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
    # Shared compiled regex for discovery context formatting (class-level to avoid per-instance overhead)
    _discovery_context_regex = re.compile(r"\{(?:event|module)[^}]*\}")
    # Stats class for the status line — override in subclasses for custom formatting
    _stats_class = None

    # 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",
        "_stats_recorded",
        "_internal",
        "_dummy",
        "_module",
        # DNS-related attributes — backing slots; public access via the
        # ``dns_children`` / ``raw_dns_records`` properties so a None
        # underlying slot transparently reads as an empty dict (lazy-init
        # saves ~128 bytes per event).
        "_dns_children",
        "_raw_dns_records",
        "dns_resolve_distance",
        # Host metadata (cloud providers, ASN, whois, etc.)
        "_host_metadata",
        "_cloudcheck_done",
        # Memory management
        "_module_consumers",
        # Public attributes
        "module",
        "scan",
        "timestamp",
    ]

    def __init__(
        self,
        data,
        event_type,
        parent=None,
        context=None,
        module=None,
        scan=None,
        tags=None,
        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.
            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
        # Lazy-init: replaced with a real set/dict on first mutation.
        # Reading via the property returns a shared empty frozenset/dict
        # so callers never see None.
        self._tags = None
        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 = None
        self._dns_children = None
        self._raw_dns_records = None
        self._discovery_context = ""
        self._module_consumers = 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._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())
            data_preview = str(data)[:200] + "..." if len(str(data)) > 200 else str(data)
            raise ValidationError(f'Error sanitizing event data "{data_preview}" 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 resolved_hosts(self):
        if is_ip(self.host):
            return frozenset({self.host})
        return self._resolved_hosts if self._resolved_hosts is not None else _EMPTY_FROZENSET

    @resolved_hosts.setter
    def resolved_hosts(self, value):
        """Assign ``_resolved_hosts`` as a frozenset (or None for unset).

        Resolved hosts are naturally immutable: there is no in-place mutation
        API. Callers (typically ``dnsresolve``) build the set locally and then
        assign it once via this setter, after which the slot holds a
        ``frozenset`` that downstream consumers can read but cannot modify.
        """
        if value is None:
            self._resolved_hosts = None
        elif isinstance(value, frozenset):
            self._resolved_hosts = value
        else:
            self._resolved_hosts = frozenset(value)

    @property
    def dns_children(self):
        return self._dns_children if self._dns_children is not None else _EMPTY_DICT

    @property
    def raw_dns_records(self):
        return self._raw_dns_records if self._raw_dns_records is not None else _EMPTY_DICT

    def add_dns_child(self, rdtype, host):
        """Record a DNS child host under ``rdtype``, lazy-allocating dict + child set."""
        if self._dns_children is None:
            self._dns_children = {}
        existing = self._dns_children.get(rdtype)
        if existing is None:
            self._dns_children[rdtype] = {host}
        else:
            existing.add(host)

    def set_raw_dns_record(self, rdtype, answers):
        """Store the raw DNS answer list for ``rdtype``, lazy-allocating the dict."""
        if self._raw_dns_records is None:
            self._raw_dns_records = {}
        self._raw_dns_records[rdtype] = answers

    @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 host_metadata(self):
        try:
            return self._host_metadata
        except AttributeError:
            self._host_metadata = {}
            return self._host_metadata

    @host_metadata.setter
    def host_metadata(self, value):
        self._host_metadata = value

    @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 url(self):
        parsed_url = getattr(self, "parsed_url", None)
        if parsed_url is not None:
            return parsed_url.geturl()
        return ""

    @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 self._port:
            return self._port
        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

    @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 if self._tags is not None else _EMPTY_FROZENSET

    @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):
        if self._tags is None:
            self._tags = set()
        self._tags.add(sys.intern(tagify(tag)))

    def add_tags(self, tags):
        for tag in set(tags):
            self.add_tag(tag)

    def remove_tag(self, tag):
        if not self._tags:
            return
        with suppress(KeyError):
            self._tags.remove(sys.intern(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
            # inherit seed tag from DNS_NAME_UNRESOLVED -> DNS_NAME only
            if "seed" in parent.tags and parent.type == "DNS_NAME_UNRESOLVED" and self.type == "DNS_NAME":
                self.add_tag("seed")
            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", "from-wayback", "from-lightfuzz"):
                        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 archive_url(self):
        """Traverse the parent chain to find the nearest archive_url.

        The 'from-wayback' tag signals that this event descends from archived content.
        The actual archive URL is stored only in the data dict of the originating
        wayback HTTP_RESPONSE; this property walks upward to find it.
        """
        if "from-wayback" not in self.tags:
            return None
        event = self
        while event is not None:
            if isinstance(event.data, dict) and "archive_url" in event.data:
                return event.data["archive_url"]
            parent = getattr(event, "parent", None)
            if parent is None or parent is event:
                break
            event = parent
        return None

    @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 _minimize(self):
        """
        Called when a module is done processing this event.

        Decrements the consumer count. When no modules are left waiting to
        process this event, heavy payload data is stripped to free memory.
        """
        self._module_consumers = max(0, self._module_consumers - 1)
        if self._module_consumers <= 0:
            # release container slots; lazy-init pattern means None == empty
            self._dns_children = None
            self._raw_dns_records = None
            self._resolved_hosts = None

    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(str(self.host))
            return bool(radixtarget.search(str(other_event.host)))
        return False

    def json(self, mode="json"):
        """
        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".

        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 isinstance(data, str):
            j["data"] = data
        elif isinstance(data, dict):
            j["data_json"] = data
        else:
            raise ValueError(f"Invalid data type: {type(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"] = utc_datetime_validator(self.timestamp).timestamp()
        # 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
        j.update({"tags": sorted(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

        # host metadata (cloud providers, ASN, etc.)
        host_metadata = getattr(self, "host_metadata", None)
        if host_metadata:
            j["host_metadata"] = host_metadata
        # 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)

pretty_string property

pretty_string

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.

module_sequence property

module_sequence

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.

__init__

__init__(
    data,
    event_type,
    parent=None,
    context=None,
    module=None,
    scan=None,
    tags=None,
    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) –

    Type of the event, e.g., 'IP_ADDRESS'.

  • parent (BaseEvent) –

    Parent event that led to this event's discovery. Defaults to None.

  • module (str) –

    Module that discovered the event. Defaults to None.

  • scan (Scan) –

    BBOT Scan object. Required unless _dummy is True. Defaults to None.

  • tags (list of str) –

    Descriptive tags for the event. Defaults to None.

  • timestamp (datetime) –

    Time of event discovery. Defaults to current UTC time.

  • _dummy (bool) –

    If True, disables certain data validations. Defaults to False.

  • _internal (Any) –

    If specified, makes the event internal. Defaults to None.

Raises:

  • ValidationError

    If either scan or parent are not specified and _dummy is False.

Source code in bbot/core/event/base.py
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
def __init__(
    self,
    data,
    event_type,
    parent=None,
    context=None,
    module=None,
    scan=None,
    tags=None,
    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.
        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
    # Lazy-init: replaced with a real set/dict on first mutation.
    # Reading via the property returns a shared empty frozenset/dict
    # so callers never see None.
    self._tags = None
    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 = None
    self._dns_children = None
    self._raw_dns_records = None
    self._discovery_context = ""
    self._module_consumers = 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._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())
        data_preview = str(data)[:200] + "..." if len(str(data)) > 200 else str(data)
        raise ValidationError(f'Error sanitizing event data "{data_preview}" 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

json

json(mode='json')

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, default: 'json' ) –

    Specifies the data serialization mode. Default is "json". Other options include "graph", "human", and "id".

Returns:

  • dict

    JSON-serializable dictionary representation of the event object.

Source code in bbot/core/event/base.py
 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
def json(self, mode="json"):
    """
    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".

    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 isinstance(data, str):
        j["data"] = data
    elif isinstance(data, dict):
        j["data_json"] = data
    else:
        raise ValueError(f"Invalid data type: {type(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"] = utc_datetime_validator(self.timestamp).timestamp()
    # 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
    j.update({"tags": sorted(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

    # host metadata (cloud providers, ASN, etc.)
    host_metadata = getattr(self, "host_metadata", None)
    if host_metadata:
        j["host_metadata"] = host_metadata
    # 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

from_json staticmethod

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.

Source code in bbot/core/event/base.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
@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)