-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshadowhunter_neo4j.py
More file actions
1425 lines (1181 loc) · 49.1 KB
/
shadowhunter_neo4j.py
File metadata and controls
1425 lines (1181 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
#!/usr/bin/env python3
"""
ShadowHunter - Dark Web Credential Intelligence Platform
Module: Neo4j Graph Database Integration
Author: Fevra
Version: 0.1.0
This module provides graph database capabilities for storing and analyzing
threat intelligence relationships between domains, credentials, threat actors,
breaches, and attack infrastructure.
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Set, Tuple, Any
from dataclasses import dataclass, asdict
import json
import hashlib
# Neo4j driver
try:
from neo4j import GraphDatabase, basic_auth
from neo4j.exceptions import ServiceUnavailable, AuthError
NEO4J_AVAILABLE = True
except ImportError:
NEO4J_AVAILABLE = False
logging.warning("Neo4j driver not installed. Install with: pip install neo4j")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('ShadowHunter.Neo4j')
# ============================================================================
# GRAPH NODE MODELS
# ============================================================================
@dataclass
class GraphNode:
"""Base class for graph nodes"""
node_id: str
node_type: str
properties: Dict[str, Any]
created_at: str = ""
def __post_init__(self):
if not self.created_at:
self.created_at = datetime.utcnow().isoformat()
@dataclass
class DomainNode(GraphNode):
"""Domain node"""
def __init__(self, domain: str, organization: str = "Unknown"):
super().__init__(
node_id=f"domain:{domain}",
node_type="Domain",
properties={
'domain': domain,
'organization': organization
}
)
@dataclass
class CredentialNode(GraphNode):
"""Credential node"""
def __init__(self, email: str, password_hash: Optional[str] = None):
super().__init__(
node_id=f"cred:{hashlib.sha256(email.encode()).hexdigest()[:16]}",
node_type="Credential",
properties={
'email': email,
'email_hash': hashlib.sha256(email.encode()).hexdigest(),
'password_hash': password_hash
}
)
@dataclass
class ThreatActorNode(GraphNode):
"""Threat actor/seller node"""
def __init__(self, username: str, platform: str, reputation: Optional[str] = None):
super().__init__(
node_id=f"actor:{platform}:{username}",
node_type="ThreatActor",
properties={
'username': username,
'platform': platform,
'reputation': reputation
}
)
@dataclass
class BreachNode(GraphNode):
"""Data breach node"""
def __init__(self, breach_name: str, record_count: int, breach_date: Optional[str] = None):
super().__init__(
node_id=f"breach:{hashlib.md5(breach_name.encode()).hexdigest()[:16]}",
node_type="Breach",
properties={
'breach_name': breach_name,
'record_count': record_count,
'breach_date': breach_date
}
)
@dataclass
class StealerLogNode(GraphNode):
"""Stealer malware log node"""
def __init__(self, log_id: str, stealer_type: str, credentials_count: int, price: Optional[float] = None):
super().__init__(
node_id=f"log:{log_id}",
node_type="StealerLog",
properties={
'log_id': log_id,
'stealer_type': stealer_type,
'credentials_count': credentials_count,
'price': price
}
)
@dataclass
class RansomwareGroupNode(GraphNode):
"""Ransomware group node"""
def __init__(self, group_name: str, leak_site_url: Optional[str] = None):
super().__init__(
node_id=f"ransom:{group_name.lower().replace(' ', '_')}",
node_type="RansomwareGroup",
properties={
'group_name': group_name,
'leak_site_url': leak_site_url
}
)
@dataclass
class IABListingNode(GraphNode):
"""Initial Access Broker listing node"""
def __init__(self, listing_id: str, access_type: str, price: float):
super().__init__(
node_id=f"iab:{listing_id}",
node_type="IABListing",
properties={
'listing_id': listing_id,
'access_type': access_type,
'price': price
}
)
@dataclass
class TelegramChannelNode(GraphNode):
"""Telegram channel node"""
def __init__(self, username: str, category: str, member_count: int = 0):
super().__init__(
node_id=f"telegram:{username}",
node_type="TelegramChannel",
properties={
'username': username,
'category': category,
'member_count': member_count
}
)
# ============================================================================
# GRAPH RELATIONSHIP MODELS
# ============================================================================
@dataclass
class GraphRelationship:
"""Graph relationship"""
from_node_id: str
to_node_id: str
relationship_type: str
properties: Dict[str, Any]
created_at: str = ""
def __post_init__(self):
if not self.created_at:
self.created_at = datetime.utcnow().isoformat()
# ============================================================================
# NEO4J DATABASE MANAGER
# ============================================================================
class Neo4jManager:
"""Neo4j database manager"""
def __init__(self, uri: str = "bolt://localhost:7687",
username: str = "neo4j",
password: str = "password"):
"""
Initialize Neo4j connection
Args:
uri: Neo4j connection URI
username: Database username
password: Database password
"""
if not NEO4J_AVAILABLE:
raise ImportError("Neo4j driver not installed. Run: pip install neo4j")
self.uri = uri
self.username = username
self.password = password
self.driver = None
logger.info(f"Neo4j manager initialized for {uri}")
def connect(self) -> bool:
"""Connect to Neo4j database"""
try:
self.driver = GraphDatabase.driver(
self.uri,
auth=basic_auth(self.username, self.password)
)
# Test connection
with self.driver.session() as session:
result = session.run("RETURN 1 as test")
result.single()
logger.info("✓ Connected to Neo4j database")
return True
except AuthError:
logger.error("Authentication failed - check username/password")
return False
except ServiceUnavailable:
logger.error("Neo4j service unavailable - is it running?")
return False
except Exception as e:
logger.error(f"Failed to connect to Neo4j: {e}")
return False
def close(self):
"""Close database connection"""
if self.driver:
self.driver.close()
logger.info("Neo4j connection closed")
def create_indexes(self):
"""Create database indexes for performance"""
with self.driver.session() as session:
# Create indexes for common lookups
indexes = [
"CREATE INDEX domain_name IF NOT EXISTS FOR (d:Domain) ON (d.domain)",
"CREATE INDEX credential_email IF NOT EXISTS FOR (c:Credential) ON (c.email)",
"CREATE INDEX actor_username IF NOT EXISTS FOR (t:ThreatActor) ON (t.username)",
"CREATE INDEX breach_name IF NOT EXISTS FOR (b:Breach) ON (b.breach_name)",
"CREATE INDEX stealer_log_id IF NOT EXISTS FOR (s:StealerLog) ON (s.log_id)",
"CREATE INDEX ransomware_group IF NOT EXISTS FOR (r:RansomwareGroup) ON (r.group_name)",
]
for index in indexes:
try:
session.run(index)
except Exception as e:
logger.debug(f"Index creation: {e}")
logger.info("✓ Database indexes created")
def clear_database(self):
"""Clear all data (use with caution!)"""
with self.driver.session() as session:
session.run("MATCH (n) DETACH DELETE n")
logger.warning("⚠️ Database cleared")
# ========================================================================
# NODE CREATION
# ========================================================================
def create_node(self, node: GraphNode) -> bool:
"""Create or update a node"""
with self.driver.session() as session:
try:
query = f"""
MERGE (n:{node.node_type} {{node_id: $node_id}})
SET n += $properties
SET n.created_at = COALESCE(n.created_at, $created_at)
SET n.updated_at = $updated_at
RETURN n
"""
result = session.run(
query,
node_id=node.node_id,
properties=node.properties,
created_at=node.created_at,
updated_at=datetime.utcnow().isoformat()
)
result.single()
return True
except Exception as e:
logger.error(f"Error creating node: {e}")
return False
def create_relationship(self, rel: GraphRelationship) -> bool:
"""Create a relationship between nodes"""
with self.driver.session() as session:
try:
query = f"""
MATCH (a {{node_id: $from_id}})
MATCH (b {{node_id: $to_id}})
MERGE (a)-[r:{rel.relationship_type}]->(b)
SET r += $properties
SET r.created_at = COALESCE(r.created_at, $created_at)
SET r.updated_at = $updated_at
RETURN r
"""
result = session.run(
query,
from_id=rel.from_node_id,
to_id=rel.to_node_id,
properties=rel.properties,
created_at=rel.created_at,
updated_at=datetime.utcnow().isoformat()
)
result.single()
return True
except Exception as e:
logger.error(f"Error creating relationship: {e}")
return False
# ========================================================================
# QUERY FUNCTIONS
# ========================================================================
def find_domain_threats(self, domain: str) -> List[Dict]:
"""Find all threats related to a domain"""
with self.driver.session() as session:
query = """
MATCH (d:Domain {domain: $domain})-[r]-(threat)
RETURN d, type(r) as relationship, threat
LIMIT 100
"""
result = session.run(query, domain=domain)
return [record.data() for record in result]
def find_threat_actor_activity(self, username: str, platform: str) -> Dict:
"""Get threat actor's activity summary"""
with self.driver.session() as session:
query = """
MATCH (t:ThreatActor {username: $username, platform: $platform})-[r]->(n)
RETURN t, type(r) as activity_type, count(n) as count
"""
result = session.run(query, username=username, platform=platform)
activity = {}
for record in result:
activity[record['activity_type']] = record['count']
return activity
def find_credential_exposure(self, email: str) -> List[Dict]:
"""Find where a credential has been exposed"""
with self.driver.session() as session:
query = """
MATCH (c:Credential {email: $email})-[r:LEAKED_IN]->(source)
RETURN source, r.timestamp as timestamp
ORDER BY r.timestamp DESC
"""
result = session.run(query, email=email)
return [record.data() for record in result]
def find_related_breaches(self, domain: str) -> List[Dict]:
"""Find breaches affecting a domain"""
with self.driver.session() as session:
query = """
MATCH (d:Domain {domain: $domain})<-[:TARGETS]-(b:Breach)
RETURN b.breach_name as breach,
b.record_count as records,
b.breach_date as date
ORDER BY b.record_count DESC
"""
result = session.run(query, domain=domain)
return [record.data() for record in result]
def find_ransomware_victims(self, group_name: str) -> List[str]:
"""Find victims of a ransomware group"""
with self.driver.session() as session:
query = """
MATCH (r:RansomwareGroup {group_name: $group_name})-[:VICTIMIZED]->(d:Domain)
RETURN d.domain as victim, d.organization as organization
"""
result = session.run(query, group_name=group_name)
return [record.data() for record in result]
def get_database_statistics(self) -> Dict:
"""Get database statistics"""
with self.driver.session() as session:
stats = {}
# Count nodes by type
node_types = ['Domain', 'Credential', 'ThreatActor', 'Breach',
'StealerLog', 'RansomwareGroup', 'IABListing', 'TelegramChannel']
for node_type in node_types:
result = session.run(f"MATCH (n:{node_type}) RETURN count(n) as count")
stats[node_type] = result.single()['count']
# Count relationships
result = session.run("MATCH ()-[r]->() RETURN count(r) as count")
stats['total_relationships'] = result.single()['count']
return stats
# ========================================================================
# ADVANCED ANALYSIS QUERIES
# ========================================================================
def find_attack_chains(self, max_depth: int = 5) -> List[Dict]:
"""Find potential attack chains"""
with self.driver.session() as session:
query = f"""
MATCH path = (start)-[*1..{max_depth}]->(end)
WHERE start:Credential OR start:IABListing
AND end:Domain
RETURN path, length(path) as chain_length
ORDER BY chain_length DESC
LIMIT 20
"""
result = session.run(query)
return [record.data() for record in result]
def find_most_active_threat_actors(self, limit: int = 10) -> List[Dict]:
"""Find most active threat actors"""
with self.driver.session() as session:
query = """
MATCH (t:ThreatActor)-[r]->()
RETURN t.username as username,
t.platform as platform,
count(r) as activity_count,
collect(DISTINCT type(r)) as activity_types
ORDER BY activity_count DESC
LIMIT $limit
"""
result = session.run(query, limit=limit)
return [record.data() for record in result]
def find_high_value_targets(self, limit: int = 10) -> List[Dict]:
"""Find domains with most threats"""
with self.driver.session() as session:
query = """
MATCH (d:Domain)<-[r]-()
WITH d, count(r) as threat_count, collect(DISTINCT type(r)) as threat_types
RETURN d.domain as domain,
d.organization as organization,
threat_count,
threat_types
ORDER BY threat_count DESC
LIMIT $limit
"""
result = session.run(query, limit=limit)
return [record.data() for record in result]
def find_stealer_log_patterns(self) -> Dict:
"""Analyze stealer log patterns"""
with self.driver.session() as session:
query = """
MATCH (s:StealerLog)
RETURN s.stealer_type as type,
count(s) as count,
avg(s.credentials_count) as avg_credentials,
avg(s.price) as avg_price
ORDER BY count DESC
"""
result = session.run(query)
return {record['type']: record.data() for record in result}
def find_credential_reuse(self, min_occurrences: int = 2) -> List[Dict]:
"""Find credentials appearing in multiple sources"""
with self.driver.session() as session:
query = """
MATCH (c:Credential)-[:LEAKED_IN]->(source)
WITH c, count(DISTINCT source) as source_count, collect(source) as sources
WHERE source_count >= $min_count
RETURN c.email as email,
source_count,
[s in sources | labels(s)[0]] as source_types
ORDER BY source_count DESC
LIMIT 50
"""
result = session.run(query, min_count=min_occurrences)
return [record.data() for record in result]
# ============================================================================
# THREAT INTELLIGENCE GRAPH BUILDER
# ============================================================================
class ThreatIntelligenceGraph:
"""Build and query threat intelligence graph"""
def __init__(self, neo4j_manager: Neo4jManager):
self.db = neo4j_manager
logger.info("ThreatIntelligenceGraph initialized")
# ========================================================================
# DATA INGESTION
# ========================================================================
def ingest_credential_leak(self, email: str, source: str, source_type: str,
password: Optional[str] = None, domain: Optional[str] = None):
"""Ingest a credential leak"""
# Create credential node
password_hash = hashlib.sha256(password.encode()).hexdigest() if password else None
cred_node = CredentialNode(email, password_hash)
self.db.create_node(cred_node)
# Create domain node if provided
if domain:
domain_node = DomainNode(domain)
self.db.create_node(domain_node)
# Link credential to domain
rel = GraphRelationship(
from_node_id=cred_node.node_id,
to_node_id=domain_node.node_id,
relationship_type="BELONGS_TO",
properties={}
)
self.db.create_relationship(rel)
# Create source node based on type
if source_type == 'breach':
source_node = BreachNode(source, record_count=1)
elif source_type == 'stealer_log':
source_node = StealerLogNode(source, 'unknown', 1)
else:
# Generic source
source_node = GraphNode(
node_id=f"source:{source}",
node_type="DataSource",
properties={'name': source, 'type': source_type}
)
self.db.create_node(source_node)
# Link credential to source
rel = GraphRelationship(
from_node_id=cred_node.node_id,
to_node_id=source_node.node_id,
relationship_type="LEAKED_IN",
properties={'timestamp': datetime.utcnow().isoformat()}
)
self.db.create_relationship(rel)
logger.info(f"✓ Ingested credential leak: {email}")
def ingest_stealer_log(self, log_data: Dict):
"""Ingest a stealer log listing"""
# Create stealer log node
log_node = StealerLogNode(
log_id=log_data['log_id'],
stealer_type=log_data['stealer_type'],
credentials_count=log_data['credentials_count'],
price=log_data.get('price')
)
self.db.create_node(log_node)
# Create seller/threat actor node
if log_data.get('seller'):
actor_node = ThreatActorNode(
username=log_data['seller'],
platform=log_data.get('channel', 'telegram')
)
self.db.create_node(actor_node)
# Link actor to log
rel = GraphRelationship(
from_node_id=actor_node.node_id,
to_node_id=log_node.node_id,
relationship_type="SELLS",
properties={'price': log_data.get('price', 0)}
)
self.db.create_relationship(rel)
# Create Telegram channel node
if log_data.get('channel'):
channel_node = TelegramChannelNode(
username=log_data['channel'],
category='stealer_logs'
)
self.db.create_node(channel_node)
# Link log to channel
rel = GraphRelationship(
from_node_id=log_node.node_id,
to_node_id=channel_node.node_id,
relationship_type="POSTED_IN",
properties={'message_id': log_data.get('message_id')}
)
self.db.create_relationship(rel)
logger.info(f"✓ Ingested stealer log: {log_data['log_id']}")
def ingest_iab_listing(self, iab_data: Dict):
"""Ingest an IAB listing"""
# Create IAB listing node
listing_id = hashlib.md5(f"{iab_data['target_company']}{iab_data['price']}".encode()).hexdigest()[:16]
iab_node = IABListingNode(
listing_id=listing_id,
access_type=iab_data['access_type'],
price=iab_data['price']
)
self.db.create_node(iab_node)
# Create target domain node
domain = iab_data['target_company'].lower().replace(' ', '') + '.com' # Simplified
domain_node = DomainNode(domain, iab_data['target_company'])
self.db.create_node(domain_node)
# Link IAB listing to target
rel = GraphRelationship(
from_node_id=iab_node.node_id,
to_node_id=domain_node.node_id,
relationship_type="OFFERS_ACCESS_TO",
properties={
'access_type': iab_data['access_type'],
'price': iab_data['price']
}
)
self.db.create_relationship(rel)
# Create seller node
if iab_data.get('seller'):
actor_node = ThreatActorNode(
username=iab_data['seller'],
platform=iab_data.get('channel', 'telegram'),
reputation=iab_data.get('seller_reputation')
)
self.db.create_node(actor_node)
# Link seller to listing
rel = GraphRelationship(
from_node_id=actor_node.node_id,
to_node_id=iab_node.node_id,
relationship_type="SELLS",
properties={'price': iab_data['price']}
)
self.db.create_relationship(rel)
logger.info(f"✓ Ingested IAB listing for: {iab_data['target_company']}")
def ingest_ransomware_victim(self, group_name: str, victim_domain: str,
victim_org: str, ransom_amount: Optional[float] = None):
"""Ingest a ransomware victim"""
# Create ransomware group node
group_node = RansomwareGroupNode(group_name)
self.db.create_node(group_node)
# Create victim domain node
domain_node = DomainNode(victim_domain, victim_org)
self.db.create_node(domain_node)
# Link group to victim
rel = GraphRelationship(
from_node_id=group_node.node_id,
to_node_id=domain_node.node_id,
relationship_type="VICTIMIZED",
properties={
'ransom_amount': ransom_amount,
'discovered_date': datetime.utcnow().isoformat()
}
)
self.db.create_relationship(rel)
logger.info(f"✓ Ingested ransomware victim: {victim_org}")
def ingest_breach(self, breach_name: str, target_domain: str,
record_count: int, data_types: List[str]):
"""Ingest a data breach"""
# Create breach node
breach_node = BreachNode(breach_name, record_count)
self.db.create_node(breach_node)
# Create target domain node
domain_node = DomainNode(target_domain)
self.db.create_node(domain_node)
# Link breach to target
rel = GraphRelationship(
from_node_id=breach_node.node_id,
to_node_id=domain_node.node_id,
relationship_type="TARGETS",
properties={
'data_types': data_types,
'record_count': record_count
}
)
self.db.create_relationship(rel)
logger.info(f"✓ Ingested breach: {breach_name}")
# ========================================================================
# ANALYSIS FUNCTIONS
# ========================================================================
def analyze_domain_risk(self, domain: str) -> Dict:
"""Comprehensive domain risk analysis"""
threats = self.db.find_domain_threats(domain)
breaches = self.db.find_related_breaches(domain)
risk_score = 0
risk_factors = []
# Calculate risk based on threats
for threat in threats:
rel_type = threat.get('relationship')
if rel_type == 'VICTIMIZED':
risk_score += 50
risk_factors.append('Ransomware victim')
elif rel_type == 'TARGETS':
risk_score += 30
risk_factors.append('Breach target')
elif rel_type == 'OFFERS_ACCESS_TO':
risk_score += 40
risk_factors.append('IAB listing')
return {
'domain': domain,
'risk_score': min(risk_score, 100),
'risk_level': 'CRITICAL' if risk_score >= 70 else 'HIGH' if risk_score >= 40 else 'MEDIUM',
'threat_count': len(threats),
'breach_count': len(breaches),
'risk_factors': risk_factors
}
def generate_threat_report(self, domain: str) -> Dict:
"""Generate comprehensive threat report"""
return {
'domain': domain,
'risk_analysis': self.analyze_domain_risk(domain),
'threats': self.db.find_domain_threats(domain),
'breaches': self.db.find_related_breaches(domain),
'generated_at': datetime.utcnow().isoformat()
}
# ============================================================================
# DEMO AND TESTING FUNCTIONS
# ============================================================================
def print_setup_instructions():
"""Print Neo4j setup instructions"""
print("\n" + "="*80)
print("🔧 NEO4J SETUP INSTRUCTIONS")
print("="*80)
print("\n1. Install Neo4j:")
print(" macOS: brew install neo4j")
print(" Linux: apt-get install neo4j")
print(" Windows: Download from https://neo4j.com/download/")
print(" Docker: docker run -p 7474:7474 -p 7687:7687 neo4j:latest")
print("\n2. Start Neo4j:")
print(" macOS: brew services start neo4j")
print(" Linux: sudo systemctl start neo4j")
print(" Docker: (container starts automatically)")
print("\n3. Access Neo4j Browser:")
print(" URL: http://localhost:7474")
print(" Default username: neo4j")
print(" Default password: neo4j (change on first login)")
print("\n4. Install Python driver:")
print(" pip install neo4j")
print("\n5. Verify connection:")
print(" Run this script with option 2")
print("\n" + "="*80)
def demo_connection_test():
"""Demo: Test Neo4j connection"""
print("\n🔌 Testing Neo4j Connection")
print("="*80)
db = Neo4jManager(
uri="bolt://localhost:7687",
username="neo4j",
password="password" # Change to your password
)
if db.connect():
print("✓ Connection successful!")
# Get statistics
stats = db.get_database_statistics()
print("\n📊 Database Statistics:")
for key, value in stats.items():
print(f" {key}: {value}")
db.close()
else:
print("❌ Connection failed")
print("\nTroubleshooting:")
print("1. Is Neo4j running? Check with: lsof -i :7687")
print("2. Is the password correct?")
print("3. Try accessing http://localhost:7474 in browser")
def demo_data_ingestion():
"""Demo: Ingest sample threat intelligence data"""
print("\n📥 Data Ingestion Demo")
print("="*80)
# Connect to database
db = Neo4jManager(password="password") # Change password
if not db.connect():
print("❌ Cannot connect to Neo4j")
return
# Create indexes
db.create_indexes()
# Initialize graph builder
graph = ThreatIntelligenceGraph(db)
print("\n1. Ingesting credential leaks...")
graph.ingest_credential_leak(
email="admin@acmecorp.com",
source="Pastebin_2025_01",
source_type="breach",
password="Password123",
domain="acmecorp.com"
)
graph.ingest_credential_leak(
email="ceo@techcompany.com",
source="Telegram_Stealer_Logs",
source_type="stealer_log",
domain="techcompany.com"
)
print("2. Ingesting stealer logs...")
graph.ingest_stealer_log({
'log_id': 'lumma_20250101_001',
'stealer_type': 'lumma',
'credentials_count': 250,
'price': 75.0,
'seller': 'seller_pro',
'channel': 'stealer_premium',
'message_id': 12345
})
print("3. Ingesting IAB listings...")
graph.ingest_iab_listing({
'target_company': 'Acme Corporation',
'access_type': 'Domain Admin',
'price': 85000.0,
'seller': 'access_broker_elite',
'channel': 'iab_market'
})
print("4. Ingesting ransomware victims...")
graph.ingest_ransomware_victim(
group_name="LockBit 4.0",
victim_domain="victimcorp.com",
victim_org="Victim Corporation",
ransom_amount=2500000.0
)
print("5. Ingesting data breaches...")
graph.ingest_breach(
breach_name="TechCompany Breach 2025",
target_domain="techcompany.com",
record_count=2500000,
data_types=['emails', 'passwords', 'phone_numbers']
)
print("\n✓ Data ingestion complete!")
# Get updated statistics
stats = db.get_database_statistics()
print("\n📊 Updated Database Statistics:")
for key, value in stats.items():
print(f" {key}: {value}")
db.close()
def demo_threat_analysis():
"""Demo: Analyze threats for a domain"""
print("\n🔍 Threat Analysis Demo")
print("="*80)
# Connect to database
db = Neo4jManager(password="password")
if not db.connect():
print("❌ Cannot connect to Neo4j")
return
graph = ThreatIntelligenceGraph(db)
# Analyze domains
test_domains = ['acmecorp.com', 'techcompany.com', 'victimcorp.com']
for domain in test_domains:
print(f"\n{'='*80}")
print(f"🎯 Analyzing: {domain}")
print('='*80)
risk_analysis = graph.analyze_domain_risk(domain)
print(f"\n📊 Risk Assessment:")
print(f" Risk Score: {risk_analysis['risk_score']}/100")
print(f" Risk Level: {risk_analysis['risk_level']}")
print(f" Threat Count: {risk_analysis['threat_count']}")
print(f" Breach Count: {risk_analysis['breach_count']}")
if risk_analysis['risk_factors']:
print(f"\n⚠️ Risk Factors:")
for factor in risk_analysis['risk_factors']:
print(f" - {factor}")
# Get detailed threats
threats = db.find_domain_threats(domain)
if threats:
print(f"\n🔴 Active Threats:")
for i, threat in enumerate(threats[:5], 1):
print(f" {i}. {threat.get('relationship', 'Unknown')}")
db.close()
def demo_advanced_queries():
"""Demo: Advanced threat intelligence queries"""
print("\n🔬 Advanced Threat Intelligence Queries")
print("="*80)
# Connect to database
db = Neo4jManager(password="password")
if not db.connect():
print("❌ Cannot connect to Neo4j")
return
print("\n1. Most Active Threat Actors:")
print("-" * 40)
actors = db.find_most_active_threat_actors(limit=5)
for i, actor in enumerate(actors, 1):
print(f" {i}. @{actor['username']} ({actor['platform']})")
print(f" Activity Count: {actor['activity_count']}")
print(f" Activity Types: {', '.join(actor['activity_types'])}")
print()
print("\n2. High-Value Targets:")
print("-" * 40)
targets = db.find_high_value_targets(limit=5)
for i, target in enumerate(targets, 1):
print(f" {i}. {target['domain']} ({target['organization']})")
print(f" Threat Count: {target['threat_count']}")
print(f" Threat Types: {', '.join(target['threat_types'])}")
print()
print("\n3. Stealer Log Patterns:")
print("-" * 40)
patterns = db.find_stealer_log_patterns()
for stealer_type, data in patterns.items():
print(f" {stealer_type.upper()}:")
print(f" Count: {data['count']}")
print(f" Avg Credentials: {data['avg_credentials']:.0f}")
print(f" Avg Price: ${data['avg_price']:.2f}")
print()
print("\n4. Credential Reuse Analysis:")
print("-" * 40)
reuse = db.find_credential_reuse(min_occurrences=2)
if reuse:
print(f" Found {len(reuse)} credentials in multiple sources:")
for i, cred in enumerate(reuse[:5], 1):
print(f" {i}. {cred['email']}")
print(f" Appearances: {cred['source_count']}")
print(f" Source Types: {', '.join(cred['source_types'])}")
print()
else:
print(" No credential reuse detected (ingest more data)")
db.close()