-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreat_intelligence.py
More file actions
1737 lines (1441 loc) · 61.6 KB
/
Copy paththreat_intelligence.py
File metadata and controls
1737 lines (1441 loc) · 61.6 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
"""
Advanced Threat Intelligence Integration System
Real-time threat data collection, analysis, and dissemination
"""
import os
import sys
import time
import threading
import logging
import json
import hashlib
import base64
import requests
import yaml
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Optional, Set, Union
from dataclasses import dataclass
from pathlib import Path
import sqlite3
# Threat intelligence libraries
try:
import feedparser
import dns.resolver
import geoip2.database
import iocextract
import vt
except ImportError:
print("Installing threat intelligence libraries...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "feedparser", "dnspython", "geoip2", "iocextract", "virustotal-api"])
import feedparser
import dns.resolver
import geoip2.database
import iocextract
import vt
# ML libraries
try:
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import DBSCAN
import joblib
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "scikit-learn", "pandas", "numpy"])
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import DBSCAN
import joblib
logger = logging.getLogger(__name__)
@dataclass
class ThreatIndicator:
"""Threat intelligence indicator"""
indicator_id: str
indicator_type: str # ip, domain, hash, url, email
value: str
source: str
confidence: float
severity: str
first_seen: datetime
last_seen: datetime
tags: Set[str]
context: Dict
malware_families: Set[str]
actors: Set[str]
@dataclass
class ThreatReport:
"""Threat intelligence report"""
report_id: str
title: str
source: str
published: datetime
author: str
tags: Set[str]
indicators: List[ThreatIndicator]
tactics: Set[str]
techniques: Set[str]
malware_families: Set[str]
threat_actors: Set[str]
severity: str
confidence: float
summary: str
@dataclass
class ThreatAlert:
"""Threat intelligence alert"""
alert_id: str
timestamp: datetime
alert_type: str
severity: str
indicator: ThreatIndicator
context: Dict
correlation_score: float
recommended_actions: List[str]
class ThreatIntelligence:
"""Advanced threat intelligence integration system"""
def __init__(self, db_path: str = "prix_threatintel.db"):
self.db_path = db_path
self.monitoring = False
# Threat intelligence components
self.indicators = {}
self.reports = {}
self.alerts = []
self.feed_sources = {}
self.analyzers = {}
# API keys and configurations
self.api_keys = {}
self.feed_configs = {}
# Threat data storage
self.malicious_ips = set()
self.malicious_domains = set()
self.malicious_hashes = set()
self.malicious_urls = set()
self.suspicious_emails = set()
# Correlation engine
self.correlation_engine = None
self.anomaly_detector = None
# Initialize threat intelligence
self.init_database()
self.load_configurations()
self.init_analyzers()
self.init_correlation_engine()
self.load_historical_data()
self.start_threat_monitoring()
def init_database(self):
"""Initialize threat intelligence database"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Threat indicators table
cursor.execute('''
CREATE TABLE IF NOT EXISTS threat_indicators (
indicator_id TEXT PRIMARY KEY,
indicator_type TEXT,
value TEXT,
source TEXT,
confidence REAL,
severity TEXT,
first_seen TEXT,
last_seen TEXT,
tags TEXT,
context TEXT,
malware_families TEXT,
actors TEXT,
is_active BOOLEAN DEFAULT 1,
created_at TEXT,
updated_at TEXT
)
''')
# Threat reports table
cursor.execute('''
CREATE TABLE IF NOT EXISTS threat_reports (
report_id TEXT PRIMARY KEY,
title TEXT,
source TEXT,
published TEXT,
author TEXT,
tags TEXT,
indicators TEXT,
tactics TEXT,
techniques TEXT,
malware_families TEXT,
threat_actors TEXT,
severity TEXT,
confidence REAL,
summary TEXT,
processed BOOLEAN DEFAULT 0,
created_at TEXT,
updated_at TEXT
)
''')
# Threat alerts table
cursor.execute('''
CREATE TABLE IF NOT EXISTS threat_alerts (
alert_id TEXT PRIMARY KEY,
timestamp TEXT,
alert_type TEXT,
severity TEXT,
indicator_id TEXT,
context TEXT,
correlation_score REAL,
recommended_actions TEXT,
acknowledged BOOLEAN DEFAULT 0,
created_at TEXT
)
''')
# Feed sources table
cursor.execute('''
CREATE TABLE IF NOT EXISTS feed_sources (
source_id TEXT PRIMARY KEY,
name TEXT,
url TEXT,
feed_type TEXT,
format TEXT,
api_key_required BOOLEAN DEFAULT 0,
last_updated TEXT,
update_frequency INTEGER,
is_active BOOLEAN DEFAULT 1,
created_at TEXT
)
''')
# Correlations table
cursor.execute('''
CREATE TABLE IF NOT EXISTS threat_correlations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
correlation_id TEXT,
indicator_ids TEXT,
correlation_type TEXT,
confidence REAL,
context TEXT,
discovered_at TEXT
)
''')
# Threat statistics table
cursor.execute('''
CREATE TABLE IF NOT EXISTS threat_statistics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT,
indicator_type TEXT,
source TEXT,
new_indicators INTEGER,
total_indicators INTEGER,
high_severity INTEGER,
medium_severity INTEGER,
low_severity INTEGER
)
''')
conn.commit()
conn.close()
def load_configurations(self):
"""Load threat intelligence configurations"""
logger.info("Loading threat intelligence configurations...")
# Load feed sources
self._load_feed_sources()
# Load API keys
self._load_api_keys()
logger.info(f"Loaded {len(self.feed_sources)} feed sources")
def _load_feed_sources(self):
"""Load threat feed sources"""
default_feeds = [
{
'source_id': 'malware_domain_list',
'name': 'Malware Domain List',
'url': 'http://www.malwaredomainlist.com/hostslist/hosts.txt',
'feed_type': 'domain',
'format': 'text',
'api_key_required': False,
'update_frequency': 3600 # 1 hour
},
{
'source_id': 'phish tank',
'name': 'PhishTank',
'url': 'https://checkurl.phishtank.com/api/',
'feed_type': 'url',
'format': 'json',
'api_key_required': True,
'update_frequency': 1800 # 30 minutes
},
{
'source_id': 'vxvault',
'name': 'VXVault',
'url': 'http://vxvault.net/VirusList.txt',
'feed_type': 'url',
'format': 'text',
'api_key_required': False,
'update_frequency': 3600
},
{
'source_id': 'abuse_ch',
'name': 'Abuse.ch Feeds',
'url': 'https://feodotracker.abuse.ch/downloads/feodotracker.txt',
'feed_type': 'domain',
'format': 'text',
'api_key_required': False,
'update_frequency': 3600
},
{
'source_id': 'cve_feed',
'name': 'CVE Feed',
'url': 'https://cve.circl.lu/api/cves/',
'feed_type': 'cve',
'format': 'json',
'api_key_required': False,
'update_frequency': 86400 # 24 hours
}
]
for feed_config in default_feeds:
self.feed_sources[feed_config['source_id']] = feed_config
self._store_feed_source(feed_config)
def _store_feed_source(self, feed_config: Dict):
"""Store feed source in database"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO feed_sources
(source_id, name, url, feed_type, format, api_key_required,
update_frequency, is_active, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
feed_config['source_id'],
feed_config['name'],
feed_config['url'],
feed_config['feed_type'],
feed_config['format'],
feed_config['api_key_required'],
feed_config['update_frequency'],
True,
datetime.now().isoformat()
))
conn.commit()
conn.close()
def _load_api_keys(self):
"""Load API keys from environment or config"""
# In a real implementation, these would be loaded from secure storage
self.api_keys = {
'virustotal': os.getenv('VIRUSTOTAL_API_KEY', ''),
'phishtank': os.getenv('PHISHTANK_API_KEY', ''),
'shodan': os.getenv('SHODAN_API_KEY', ''),
'abuseipdb': os.getenv('ABUSEIPDB_API_KEY', '')
}
def init_analyzers(self):
"""Initialize threat analyzers"""
self.analyzers = {
'ip_analyzer': IPAnalyzer(),
'domain_analyzer': DomainAnalyzer(),
'hash_analyzer': HashAnalyzer(),
'url_analyzer': URLAnalyzer(),
'email_analyzer': EmailAnalyzer(),
'malware_analyzer': MalwareAnalyzer()
}
logger.info("Threat analyzers initialized")
def init_correlation_engine(self):
"""Initialize correlation engine"""
self.correlation_engine = CorrelationEngine()
self.anomaly_detector = AnomalyDetector()
logger.info("Correlation engine initialized")
def load_historical_data(self):
"""Load historical threat data"""
logger.info("Loading historical threat data...")
# Load indicators from database
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT * FROM threat_indicators WHERE is_active = 1')
for row in cursor.fetchall():
indicator = self._row_to_indicator(row)
self.indicators[indicator.indicator_id] = indicator
# Add to appropriate sets
if indicator.indicator_type == 'ip':
self.malicious_ips.add(indicator.value)
elif indicator.indicator_type == 'domain':
self.malicious_domains.add(indicator.value)
elif indicator.indicator_type == 'hash':
self.malicious_hashes.add(indicator.value)
elif indicator.indicator_type == 'url':
self.malicious_urls.add(indicator.value)
elif indicator.indicator_type == 'email':
self.suspicious_emails.add(indicator.value)
conn.close()
logger.info(f"Loaded {len(self.indicators)} historical indicators")
def _row_to_indicator(self, row) -> ThreatIndicator:
"""Convert database row to ThreatIndicator"""
return ThreatIndicator(
indicator_id=row[0],
indicator_type=row[1],
value=row[2],
source=row[3],
confidence=row[4],
severity=row[5],
first_seen=datetime.fromisoformat(row[6]),
last_seen=datetime.fromisoformat(row[7]),
tags=set(json.loads(row[8])),
context=json.loads(row[9]),
malware_families=set(json.loads(row[10])),
actors=set(json.loads(row[11]))
)
def start_threat_monitoring(self):
"""Start threat intelligence monitoring"""
self.monitoring = True
logger.info("Starting threat intelligence monitoring...")
# Start monitoring threads
threading.Thread(target=self._feed_collection_loop, daemon=True).start()
threading.Thread(target=self._threat_analysis_loop, daemon=True).start()
threading.Thread(target=self._correlation_loop, daemon=True).start()
threading.Thread(target=self._alert_generation_loop, daemon=True).start()
threading.Thread(target=self._statistics_loop, daemon=True).start()
logger.info("Threat intelligence monitoring started")
def _feed_collection_loop(self):
"""Collect threat feeds"""
while self.monitoring:
try:
for source_id, feed_config in self.feed_sources.items():
if not feed_config.get('is_active', True):
continue
# Check if feed needs updating
last_updated = feed_config.get('last_updated')
update_frequency = feed_config.get('update_frequency', 3600)
if last_updated:
last_update_time = datetime.fromisoformat(last_updated)
if (datetime.now() - last_update_time).seconds < update_frequency:
continue
# Collect feed data
self._collect_feed(source_id, feed_config)
time.sleep(300) # Check every 5 minutes
except Exception as e:
logger.error(f"Error in feed collection: {e}")
time.sleep(600)
def _collect_feed(self, source_id: str, feed_config: Dict):
"""Collect data from specific feed"""
try:
logger.info(f"Collecting feed: {feed_config['name']}")
feed_type = feed_config['feed_type']
feed_format = feed_config['format']
url = feed_config['url']
if feed_format == 'text':
indicators = self._parse_text_feed(url, feed_type)
elif feed_format == 'json':
indicators = self._parse_json_feed(url, feed_type)
elif feed_format == 'xml':
indicators = self._parse_xml_feed(url, feed_type)
elif feed_format == 'rss':
indicators = self._parse_rss_feed(url, feed_type)
else:
logger.warning(f"Unsupported feed format: {feed_format}")
return
# Store indicators
for indicator_data in indicators:
self._store_indicator(indicator_data, source_id)
# Update feed last_updated
feed_config['last_updated'] = datetime.now().isoformat()
self._update_feed_source(feed_config)
logger.info(f"Collected {len(indicators)} indicators from {feed_config['name']}")
except Exception as e:
logger.error(f"Error collecting feed {source_id}: {e}")
def _parse_text_feed(self, url: str, feed_type: str) -> List[Dict]:
"""Parse text-based threat feed"""
indicators = []
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
lines = response.text.split('\n')
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
# Extract indicators based on feed type
if feed_type == 'domain':
if self._is_valid_domain(line):
indicators.append({
'value': line,
'type': 'domain',
'source': url,
'confidence': 0.7,
'severity': 'medium'
})
elif feed_type == 'url':
if line.startswith('http'):
indicators.append({
'value': line,
'type': 'url',
'source': url,
'confidence': 0.7,
'severity': 'medium'
})
elif feed_type == 'ip':
if self._is_valid_ip(line):
indicators.append({
'value': line,
'type': 'ip',
'source': url,
'confidence': 0.7,
'severity': 'medium'
})
except Exception as e:
logger.error(f"Error parsing text feed {url}: {e}")
return indicators
def _parse_json_feed(self, url: str, feed_type: str) -> List[Dict]:
"""Parse JSON-based threat feed"""
indicators = []
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
data = response.json()
# Parse based on feed structure
if feed_type == 'cve':
for cve in data.get('CVE_Items', []):
cve_id = cve.get('cve', {}).get('CVE_data_meta', {}).get('ID', '')
if cve_id:
indicators.append({
'value': cve_id,
'type': 'cve',
'source': url,
'confidence': 0.9,
'severity': self._get_cve_severity(cve)
})
except Exception as e:
logger.error(f"Error parsing JSON feed {url}: {e}")
return indicators
def _parse_xml_feed(self, url: str, feed_type: str) -> List[Dict]:
"""Parse XML-based threat feed"""
indicators = []
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
# Use feedparser for RSS/Atom feeds
feed = feedparser.parse(response.content)
for entry in feed.entries:
# Extract indicators from feed content
content = entry.get('summary', '') + entry.get('content', '')
extracted_iocs = iocextract.extract_iocs(content)
for ioc_type, ioc_list in extracted_iocs.items():
for ioc in ioc_list:
indicators.append({
'value': ioc,
'type': ioc_type,
'source': url,
'confidence': 0.6,
'severity': 'medium'
})
except Exception as e:
logger.error(f"Error parsing XML feed {url}: {e}")
return indicators
def _parse_rss_feed(self, url: str, feed_type: str) -> List[Dict]:
"""Parse RSS threat feed"""
return self._parse_xml_feed(url, feed_type)
def _is_valid_domain(self, domain: str) -> bool:
"""Check if string is valid domain"""
try:
# Basic domain validation
if len(domain) > 253 or len(domain) < 3:
return False
if domain.startswith('.') or domain.endswith('.'):
return False
return all(c.isalnum() or c in '.-' for c in domain)
except:
return False
def _is_valid_ip(self, ip: str) -> bool:
"""Check if string is valid IP address"""
try:
import ipaddress
ipaddress.ip_address(ip)
return True
except:
return False
def _get_cve_severity(self, cve_data: Dict) -> str:
"""Extract CVE severity"""
try:
impact = cve_data.get('impact', {})
base_metric_v3 = impact.get('baseMetricV3', {})
cvss_v3 = base_metric_v3.get('cvssV3', {})
base_score = cvss_v3.get('baseScore', 0.0)
if base_score >= 9.0:
return 'critical'
elif base_score >= 7.0:
return 'high'
elif base_score >= 4.0:
return 'medium'
else:
return 'low'
except:
return 'medium'
def _store_indicator(self, indicator_data: Dict, source_id: str):
"""Store threat indicator"""
try:
indicator_id = self._generate_indicator_id(indicator_data['value'], indicator_data['type'])
# Check if indicator already exists
if indicator_id in self.indicators:
existing = self.indicators[indicator_id]
existing.last_seen = datetime.now()
existing.confidence = max(existing.confidence, indicator_data['confidence'])
self._update_indicator(existing)
return
# Create new indicator
indicator = ThreatIndicator(
indicator_id=indicator_id,
indicator_type=indicator_data['type'],
value=indicator_data['value'],
source=source_id,
confidence=indicator_data['confidence'],
severity=indicator_data['severity'],
first_seen=datetime.now(),
last_seen=datetime.now(),
tags=set(),
context={},
malware_families=set(),
actors=set()
)
self.indicators[indicator_id] = indicator
self._store_indicator_in_db(indicator)
# Add to appropriate sets
if indicator.indicator_type == 'ip':
self.malicious_ips.add(indicator.value)
elif indicator.indicator_type == 'domain':
self.malicious_domains.add(indicator.value)
elif indicator.indicator_type == 'hash':
self.malicious_hashes.add(indicator.value)
elif indicator.indicator_type == 'url':
self.malicious_urls.add(indicator.value)
elif indicator.indicator_type == 'email':
self.suspicious_emails.add(indicator.value)
except Exception as e:
logger.error(f"Error storing indicator: {e}")
def _generate_indicator_id(self, value: str, indicator_type: str) -> str:
"""Generate unique indicator ID"""
hash_input = f"{indicator_type}:{value}"
return f"indicator_{hashlib.sha256(hash_input.encode()).hexdigest()[:16]}"
def _store_indicator_in_db(self, indicator: ThreatIndicator):
"""Store indicator in database"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO threat_indicators
(indicator_id, indicator_type, value, source, confidence, severity,
first_seen, last_seen, tags, context, malware_families, actors,
is_active, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
indicator.indicator_id,
indicator.indicator_type,
indicator.value,
indicator.source,
indicator.confidence,
indicator.severity,
indicator.first_seen.isoformat(),
indicator.last_seen.isoformat(),
json.dumps(list(indicator.tags)),
json.dumps(indicator.context),
json.dumps(list(indicator.malware_families)),
json.dumps(list(indicator.actors)),
True,
datetime.now().isoformat(),
datetime.now().isoformat()
))
conn.commit()
conn.close()
def _update_indicator(self, indicator: ThreatIndicator):
"""Update existing indicator"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
UPDATE threat_indicators
SET last_seen = ?, confidence = ?, updated_at = ?
WHERE indicator_id = ?
''', (
indicator.last_seen.isoformat(),
indicator.confidence,
datetime.now().isoformat(),
indicator.indicator_id
))
conn.commit()
conn.close()
def _update_feed_source(self, feed_config: Dict):
"""Update feed source in database"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
UPDATE feed_sources
SET last_updated = ?
WHERE source_id = ?
''', (feed_config['last_updated'], feed_config['source_id']))
conn.commit()
conn.close()
def _threat_analysis_loop(self):
"""Analyze collected threat data"""
while self.monitoring:
try:
# Analyze new indicators
new_indicators = [
ind for ind in self.indicators.values()
if (datetime.now() - ind.first_seen).seconds < 3600 # Last hour
]
for indicator in new_indicators:
self._analyze_indicator(indicator)
# Analyze patterns and trends
self._analyze_threat_patterns()
time.sleep(600) # Analyze every 10 minutes
except Exception as e:
logger.error(f"Error in threat analysis: {e}")
time.sleep(1200)
def _analyze_indicator(self, indicator: ThreatIndicator):
"""Analyze individual indicator"""
try:
analyzer = self.analyzers.get(f"{indicator.indicator_type}_analyzer")
if analyzer:
analysis_result = analyzer.analyze(indicator.value)
# Update indicator with analysis results
indicator.context.update(analysis_result.get('context', {}))
indicator.tags.update(analysis_result.get('tags', set()))
indicator.malware_families.update(analysis_result.get('malware_families', set()))
indicator.actors.update(analysis_result.get('actors', set()))
# Update confidence and severity
indicator.confidence = min(1.0, indicator.confidence + analysis_result.get('confidence_boost', 0.0))
if analysis_result.get('severity'):
indicator.severity = analysis_result['severity']
self._update_indicator(indicator)
except Exception as e:
logger.error(f"Error analyzing indicator {indicator.indicator_id}: {e}")
def _analyze_threat_patterns(self):
"""Analyze threat patterns and trends"""
try:
# Analyze temporal patterns
self._analyze_temporal_patterns()
# Analyze geographic patterns
self._analyze_geographic_patterns()
# Analyze malware family trends
self._analyze_malware_trends()
# Detect anomalies
self._detect_threat_anomalies()
except Exception as e:
logger.error(f"Error analyzing threat patterns: {e}")
def _analyze_temporal_patterns(self):
"""Analyze temporal threat patterns"""
try:
# Group indicators by time
time_patterns = defaultdict(list)
for indicator in self.indicators.values():
hour = indicator.first_seen.hour
time_patterns[hour].append(indicator)
# Identify unusual time patterns
avg_indicators_per_hour = len(self.indicators) / 24
for hour, indicators in time_patterns.items():
if len(indicators) > avg_indicators_per_hour * 2:
logger.warning(f"Unusual threat activity at hour {hour}: {len(indicators)} indicators")
except Exception as e:
logger.error(f"Error analyzing temporal patterns: {e}")
def _analyze_geographic_patterns(self):
"""Analyze geographic threat patterns"""
try:
# Analyze IP geolocation patterns
ip_countries = defaultdict(int)
for indicator in self.indicators.values():
if indicator.indicator_type == 'ip':
country = indicator.context.get('country', 'unknown')
ip_countries[country] += 1
# Identify unusual geographic patterns
for country, count in ip_countries.items():
if count > 100: # Threshold for unusual activity
logger.warning(f"High threat activity from {country}: {count} indicators")
except Exception as e:
logger.error(f"Error analyzing geographic patterns: {e}")
def _analyze_malware_trends(self):
"""Analyze malware family trends"""
try:
# Analyze malware family distribution
malware_counts = defaultdict(int)
for indicator in self.indicators.values():
for family in indicator.malware_families:
malware_counts[family] += 1
# Identify trending malware families
top_families = sorted(malware_counts.items(), key=lambda x: x[1], reverse=True)[:10]
for family, count in top_families:
logger.info(f"Trending malware family: {family} ({count} indicators)")
except Exception as e:
logger.error(f"Error analyzing malware trends: {e}")
def _detect_threat_anomalies(self):
"""Detect anomalies in threat data"""
try:
# Use anomaly detector to find unusual patterns
features = self._extract_threat_features()
if len(features) > 10:
anomalies = self.anomaly_detector.detect_anomalies(features)
for anomaly in anomalies:
logger.warning(f"Threat anomaly detected: {anomaly}")
# Create alert for anomaly
self._create_anomaly_alert(anomaly)
except Exception as e:
logger.error(f"Error detecting threat anomalies: {e}")
def _extract_threat_features(self) -> List[List[float]]:
"""Extract features for anomaly detection"""
features = []
# Extract features from recent indicators
recent_indicators = [
ind for ind in self.indicators.values()
if (datetime.now() - ind.first_seen).days < 7 # Last week
]
# Group by hour for feature extraction
hourly_data = defaultdict(lambda: {'ip': 0, 'domain': 0, 'url': 0, 'hash': 0})
for indicator in recent_indicators:
hour = indicator.first_seen.hour
hourly_data[hour][indicator.indicator_type] += 1
for hour in range(24):
data = hourly_data[hour]
features.append([
data['ip'],
data['domain'],
data['url'],
data['hash'],
sum(data.values())
])
return features
def _create_anomaly_alert(self, anomaly: Dict):
"""Create alert for detected anomaly"""
alert_id = f"alert_anomaly_{secrets.token_hex(8)}"
alert = ThreatAlert(
alert_id=alert_id,
timestamp=datetime.now(),
alert_type="anomaly",
severity="medium",
indicator=None, # Anomaly alerts don't have specific indicators
context=anomaly,
correlation_score=anomaly.get('score', 0.5),
recommended_actions=["investigate_pattern", "enhance_monitoring"]
)
self.alerts.append(alert)
self._store_alert(alert)
def _correlation_loop(self):
"""Correlate threat indicators"""
while self.monitoring:
try:
# Find correlations between indicators
correlations = self.correlation_engine.find_correlations(self.indicators)
for correlation in correlations:
self._handle_correlation(correlation)
time.sleep(1800) # Correlate every 30 minutes
except Exception as e:
logger.error(f"Error in threat correlation: {e}")
time.sleep(3600)
def _handle_correlation(self, correlation: Dict):
"""Handle detected correlation"""
try:
correlation_id = f"corr_{secrets.token_hex(8)}"
# Store correlation
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO threat_correlations
(correlation_id, indicator_ids, correlation_type, confidence, context, discovered_at)
VALUES (?, ?, ?, ?, ?, ?)
''', (
correlation_id,
json.dumps(correlation['indicator_ids']),
correlation['type'],
correlation['confidence'],
json.dumps(correlation['context']),
datetime.now().isoformat()
))
conn.commit()
conn.close()
# Create correlation alert if high confidence
if correlation['confidence'] > 0.8:
self._create_correlation_alert(correlation)
except Exception as e:
logger.error(f"Error handling correlation: {e}")
def _create_correlation_alert(self, correlation: Dict):
"""Create alert for high-confidence correlation"""
alert_id = f"alert_corr_{secrets.token_hex(8)}"
# Get one of the correlated indicators