-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmergingThreatsRulesService.cs
More file actions
3265 lines (2774 loc) · 137 KB
/
Copy pathEmergingThreatsRulesService.cs
File metadata and controls
3265 lines (2774 loc) · 137 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
#if !BUILD_WITHOUT_FIDDLER
using Fiddler;
#endif
namespace DomainReputationInspector
{
/// <summary>
/// Service for managing Emerging Threats (ET) rules and domain lookups
/// Supports both ET Open (free) and ET Pro (commercial) rule sets
/// </summary>
public class EmergingThreatsRulesService : IDisposable
{
#region Private Fields
private readonly HttpClient _httpClient;
private SQLiteConnection _database;
private Timer _updateTimer;
private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1);
private readonly ConcurrentDictionary<string, ETDomainInfo> _etCache =
new ConcurrentDictionary<string, ETDomainInfo>();
private readonly DomainExtractor _domainExtractor = new DomainExtractor();
// ET Pro API key (optional - falls back to ET Open if not provided)
private string _etProApiKey;
// Update schedule - daily at 2 AM
private DateTime _lastUpdateTime = DateTime.MinValue;
private readonly TimeSpan _updateInterval = TimeSpan.FromDays(1); // Daily updates
private readonly TimeSpan _updateCheckInterval = TimeSpan.FromHours(1); // Check every hour for daily update time
private bool _disposed = false;
private bool _initializationComplete = false;
private bool _didInitialUpdate = false;
// Official ET rule archive URLs (as per documentation)
private const string ET_OPEN_ARCHIVE_URL = "https://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz";
private const string ET_PRO_ARCHIVE_URL = "https://rules.emergingthreatspro.com/{KEY}/snort-2.9.0/etpro.rules.tar.gz";
#endregion
#region Helper Classes
// Helper class for post-extraction decisions (avoiding C# 7.0 tuples for .NET Framework 4.6.1 compatibility)
private class PostExtractionDecision
{
public bool ShouldInclude { get; set; }
public string Reason { get; set; }
public string ModifiedDomain { get; set; }
public PostExtractionDecision(bool shouldInclude, string reason = null, string modifiedDomain = null)
{
ShouldInclude = shouldInclude;
Reason = reason;
ModifiedDomain = modifiedDomain;
}
}
#endregion
#region Constructor and Disposal
public EmergingThreatsRulesService()
{
// IMMEDIATE logging to test if constructor starts
try
{
#if !BUILD_WITHOUT_FIDDLER
FiddlerApplication.Log.LogString("[ET-RULES-CONSTRUCTOR] EmergingThreatsRulesService constructor STARTING");
#endif
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromMinutes(5);
LogMessage("ET RULES: Starting service initialization...");
InitializeDatabase();
LoadSettings();
// Mark initialization as complete
_initializationComplete = true;
LogMessage("ET RULES: Service initialized - Daily updates enabled");
// Initial download only when DB is empty or LastUpdateTime is stale
Task.Run(async () =>
{
try
{
if (!_didInitialUpdate)
{
_didInitialUpdate = true;
if (NeedsInitialDownload())
{
LogMessage("ET RULES: Starting initial rules download after initialization");
await DownloadAndParseAllRulesAsync();
}
else
{
LogMessage("ET RULES: Recent rules present - skipping initial download");
WarmMemoryCacheFromDatabase();
}
}
else
{
LogMessage("ET RULES: Skipping duplicate initial update");
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Initial update failed: {ex.Message}");
}
finally
{
// Start background update timer ONLY after initial download/cache warm completes
_updateTimer = new Timer(CheckForDailyUpdate, null, _updateCheckInterval, _updateCheckInterval);
LogMessage("ET RULES: Background update timer started");
}
});
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Service initialization failed: {ex.Message}");
LogMessage($"ET RULES ERROR: Stack trace: {ex.StackTrace}");
LogMessage($"ET RULES ERROR: Exception type: {ex.GetType().Name}");
if (ex.InnerException != null)
{
LogMessage($"ET RULES ERROR: Inner exception: {ex.InnerException.Message}");
}
throw; // Re-throw to ensure the service is marked as failed
}
}
private string BuildEtProUrl(string baseUrl)
{
try
{
if (string.IsNullOrEmpty(_etProApiKey)) return baseUrl;
// Replace {KEY} placeholder with actual API key
return baseUrl.Replace("{KEY}", Uri.EscapeDataString(_etProApiKey));
}
catch
{
return baseUrl;
}
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
try
{
_updateTimer?.Dispose();
_updateSemaphore?.Dispose();
_httpClient?.Dispose();
_domainExtractor?.Dispose();
_database?.Close();
_database?.Dispose();
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Disposal error: {ex.Message}");
}
}
#endregion
#region Public Methods
/// <summary>
/// Sets the ET Pro API key and saves it to settings
/// </summary>
/// <param name="apiKey">The ET Pro API key (can be null/empty for ET Open only)</param>
public void SetETProApiKey(string apiKey)
{
_etProApiKey = apiKey?.Trim();
SaveSettings();
if (string.IsNullOrEmpty(_etProApiKey))
{
LogMessage("ET RULES: Using ET Open rule set (free)");
}
else
{
LogMessage($"ET RULES: ET Pro key configured (length: {_etProApiKey.Length}) - will attempt to use ET Pro rules");
LogMessage($"ET RULES: Current statistics: {GetStatistics()}");
}
}
/// <summary>
/// Gets the current ET Pro API key
/// </summary>
/// <returns>The ET Pro API key or empty string if not set</returns>
public string GetETProApiKey()
{
return _etProApiKey ?? string.Empty;
}
/// <summary>
/// Checks if a domain is in the ET rules database
/// </summary>
/// <param name="domain">The domain to check</param>
/// <returns>ET domain information if found, null otherwise</returns>
public ETDomainInfo CheckDomain(string domain)
{
if (string.IsNullOrEmpty(domain) || _disposed)
return null;
try
{
// Check memory cache first (fastest - ~0.1ms)
if (_etCache.TryGetValue(domain, out ETDomainInfo cachedInfo))
{
return cachedInfo;
}
// Check database with EXACT domain matching only
// This ensures phishing domains like "linkedin-phish.com" don't flag "linkedin.com"
using (var command = new SQLiteCommand(@"
SELECT RuleId, Description, Classification, Severity, RuleSource, LastUpdated, Domain
FROM ET_Domain_Indicators
WHERE Domain = @domain AND IsActive = 1
ORDER BY
CASE Severity
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
WHEN 'low' THEN 3
ELSE 4
END,
RuleId DESC
LIMIT 1", _database))
{
command.Parameters.AddWithValue("@domain", domain);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
int ordRuleId = reader.GetOrdinal("RuleId");
int ordDesc = reader.GetOrdinal("Description");
int ordClass = reader.GetOrdinal("Classification");
int ordSev = reader.GetOrdinal("Severity");
int ordSrc = reader.GetOrdinal("RuleSource");
int ordLU = reader.GetOrdinal("LastUpdated");
int ordDomain = reader.GetOrdinal("Domain");
var originalDomain = reader.IsDBNull(ordDomain) ? domain : reader.GetString(ordDomain);
var etInfo = new ETDomainInfo
{
Domain = domain, // Use the exact queried domain
RuleId = reader.IsDBNull(ordRuleId) ? 0 : reader.GetInt32(ordRuleId),
Description = reader.IsDBNull(ordDesc) ? null : reader.GetString(ordDesc),
Classification = reader.IsDBNull(ordClass) ? null : reader.GetString(ordClass),
Severity = reader.IsDBNull(ordSev) ? null : reader.GetString(ordSev),
Source = reader.IsDBNull(ordSrc) ? null : reader.GetString(ordSrc),
LastUpdated = reader.IsDBNull(ordLU) ? DateTime.MinValue : reader.GetDateTime(ordLU)
};
// Cache for future lookups
_etCache.TryAdd(domain, etInfo);
return etInfo;
}
}
}
// Cache negative result to avoid repeated DB queries
_etCache.TryAdd(domain, null);
return null;
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Lookup failed for {domain}: {ex.Message}");
return null;
}
}
/// <summary>
/// Forces an immediate update of ET rules
/// </summary>
/// <returns>True if update was successful</returns>
public async Task<bool> ForceUpdateAsync()
{
try
{
LogMessage("ET RULES: Force update requested");
// Use semaphore to prevent concurrent updates
await _updateSemaphore.WaitAsync();
try
{
await DownloadAndParseAllRulesAsync();
return true;
}
finally
{
_updateSemaphore.Release();
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Force update failed: {ex.Message}");
return false;
}
}
/// <summary>
/// Gets statistics about the ET rules database
/// </summary>
/// <returns>Statistics string</returns>
public string GetStatistics()
{
try
{
// Check if database and table are ready
if (_database == null)
{
return "ET Rules: Database not initialized";
}
// Check if table exists before querying
using (var tableCheckCommand = new SQLiteCommand("SELECT name FROM sqlite_master WHERE type='table' AND name='ET_Domain_Indicators'", _database))
{
var tableExists = tableCheckCommand.ExecuteScalar();
if (tableExists == null)
{
return "ET Rules: No rules data available";
}
}
using (var command = new SQLiteCommand(@"
SELECT
COUNT(*) as TotalRules,
COUNT(CASE WHEN Severity = 'high' THEN 1 END) as HighSeverity,
COUNT(CASE WHEN Severity = 'medium' THEN 1 END) as MediumSeverity,
COUNT(CASE WHEN Severity = 'low' THEN 1 END) as LowSeverity,
MAX(LastUpdated) as LastUpdate
FROM ET_Domain_Indicators
WHERE IsActive = 1", _database))
{
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
int ordTotal = reader.GetOrdinal("TotalRules");
int ordHigh = reader.GetOrdinal("HighSeverity");
int ordMed = reader.GetOrdinal("MediumSeverity");
int ordLow = reader.GetOrdinal("LowSeverity");
int ordLU = reader.GetOrdinal("LastUpdate");
var total = reader.IsDBNull(ordTotal) ? 0 : reader.GetInt32(ordTotal);
var high = reader.IsDBNull(ordHigh) ? 0 : reader.GetInt32(ordHigh);
var medium = reader.IsDBNull(ordMed) ? 0 : reader.GetInt32(ordMed);
var low = reader.IsDBNull(ordLow) ? 0 : reader.GetInt32(ordLow);
var lastUpdate = reader.IsDBNull(ordLU) ? "Never" : reader.GetDateTime(ordLU).ToString("yyyy-MM-dd HH:mm");
// Determine actual rule source based on database content
var ruleSource = "ET Open";
if (!string.IsNullOrEmpty(_etProApiKey))
{
try
{
using (var sourceCheck = new SQLiteCommand("SELECT COUNT(*) FROM ET_Domain_Indicators WHERE RuleSource LIKE '%ET Pro%' AND IsActive = 1", _database))
{
var etProCount = Convert.ToInt32(sourceCheck.ExecuteScalar());
ruleSource = etProCount > 0 ? "ET Pro" : "ET Open (ET Pro configured)";
}
}
catch
{
ruleSource = "ET Open";
}
}
return $"ET Rules: {total} domains ({high} high, {medium} medium, {low} low) | Source: {ruleSource} | Last Update: {lastUpdate}";
}
}
}
return "ET Rules: No data available";
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Statistics failed: {ex.Message}");
return "ET Rules: Error retrieving statistics";
}
}
#endregion
#region Private Methods
private void MigrateDatabaseSchema()
{
try
{
LogMessage("ET RULES: MigrateDatabaseSchema() - Starting");
// First check if table exists
LogMessage("ET RULES: Checking if ET_Domain_Indicators table exists");
using (var tableCheckCommand = new SQLiteCommand("SELECT name FROM sqlite_master WHERE type='table' AND name='ET_Domain_Indicators'", _database))
{
var tableExists = tableCheckCommand.ExecuteScalar();
LogMessage($"ET RULES: Table check result: {tableExists}");
if (tableExists == null)
{
LogMessage("ET RULES: ET_Domain_Indicators table does not exist - no migration needed");
return;
}
LogMessage("ET RULES: ET_Domain_Indicators table exists, proceeding with column check");
}
// Check if MainDomain column exists
LogMessage("ET RULES: About to execute PRAGMA table_info");
bool hasMainDomain = false;
using (var command = new SQLiteCommand("PRAGMA table_info(ET_Domain_Indicators)", _database))
{
LogMessage("ET RULES: PRAGMA command created, about to execute");
using (var reader = command.ExecuteReader())
{
LogMessage("ET RULES: PRAGMA executed, reading results");
while (reader.Read())
{
// PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk
var columnName = reader.GetString(1); // name is at index 1
LogMessage($"ET RULES: Found column: {columnName}");
if (columnName.Equals("MainDomain", StringComparison.OrdinalIgnoreCase))
{
hasMainDomain = true;
LogMessage("ET RULES: MainDomain column already exists");
break;
}
}
LogMessage("ET RULES: Finished reading PRAGMA results");
}
}
if (!hasMainDomain)
{
LogMessage("ET RULES: MainDomain column not found - starting migration");
// Perform migration in a single transaction for consistency
using (var transaction = _database.BeginTransaction())
{
try
{
// Add MainDomain column
LogMessage("ET RULES: Adding MainDomain column...");
using (var alterCommand = new SQLiteCommand("ALTER TABLE ET_Domain_Indicators ADD COLUMN MainDomain TEXT", _database, transaction))
{
alterCommand.ExecuteNonQuery();
}
LogMessage("ET RULES: MainDomain column added successfully");
// Create index for MainDomain (now that column exists)
LogMessage("ET RULES: Creating MainDomain index...");
using (var indexCommand = new SQLiteCommand("CREATE INDEX IF NOT EXISTS idx_main_domain ON ET_Domain_Indicators(MainDomain)", _database, transaction))
{
indexCommand.ExecuteNonQuery();
}
LogMessage("ET RULES: MainDomain index created successfully");
// Update existing records to populate MainDomain within the same transaction
LogMessage("ET RULES: Updating existing records...");
UpdateExistingMainDomainsInTransaction(transaction);
// Commit the transaction
transaction.Commit();
LogMessage("ET RULES: Database migration completed successfully");
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
else
{
LogMessage("ET RULES: No migration needed - schema is up to date");
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Database migration failed: {ex.Message}");
LogMessage($"ET RULES ERROR: Stack trace: {ex.StackTrace}");
throw; // Re-throw to ensure initialization fails if migration fails
}
}
private void UpdateExistingMainDomains()
{
try
{
// Update existing records to set MainDomain = Domain (exact match only)
// This ensures no normalization of malicious domains
// NOTE: MainDomain column was just added, so query all existing records
using (var selectCommand = new SQLiteCommand("SELECT Id, Domain FROM ET_Domain_Indicators", _database))
using (var reader = selectCommand.ExecuteReader())
{
var updates = new List<DomainUpdate>();
while (reader.Read())
{
var id = reader.GetInt32(0); // Id is first column
var domain = reader.GetString(1); // Domain is second column
// CRITICAL: Set MainDomain = Domain (no normalization)
// This preserves exact malicious domains like "linkedin-phish.com"
updates.Add(new DomainUpdate { Id = id, Domain = domain });
}
reader.Close();
// Apply updates - set MainDomain = Domain for all existing records
foreach (var update in updates)
{
using (var updateCommand = new SQLiteCommand("UPDATE ET_Domain_Indicators SET MainDomain = @domain WHERE Id = @id", _database))
{
updateCommand.Parameters.AddWithValue("@domain", update.Domain);
updateCommand.Parameters.AddWithValue("@id", update.Id);
updateCommand.ExecuteNonQuery();
}
}
if (updates.Count > 0)
{
LogMessage($"ET RULES: Updated {updates.Count} existing records with exact domain preservation");
}
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Failed to update existing domains: {ex.Message}");
}
}
private void UpdateExistingMainDomainsInTransaction(SQLiteTransaction transaction)
{
try
{
// Update existing records to set MainDomain = Domain within the migration transaction
using (var selectCommand = new SQLiteCommand("SELECT Id, Domain FROM ET_Domain_Indicators", _database, transaction))
using (var reader = selectCommand.ExecuteReader())
{
var updates = new List<DomainUpdate>();
while (reader.Read())
{
var id = reader.GetInt32(0); // Id is first column
var domain = reader.GetString(1); // Domain is second column
// CRITICAL: Set MainDomain = Domain (no normalization)
// This preserves exact malicious domains like "linkedin-phish.com"
updates.Add(new DomainUpdate { Id = id, Domain = domain });
}
reader.Close();
// Apply updates within the same transaction
foreach (var update in updates)
{
using (var updateCommand = new SQLiteCommand("UPDATE ET_Domain_Indicators SET MainDomain = @domain WHERE Id = @id", _database, transaction))
{
updateCommand.Parameters.AddWithValue("@domain", update.Domain);
updateCommand.Parameters.AddWithValue("@id", update.Id);
updateCommand.ExecuteNonQuery();
}
}
if (updates.Count > 0)
{
LogMessage($"ET RULES: Updated {updates.Count} existing records with exact domain preservation");
}
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Failed to update existing domains in transaction: {ex.Message}");
throw; // Re-throw to trigger transaction rollback
}
}
private void InitializeDatabase()
{
try
{
LogMessage("ET RULES: InitializeDatabase() - Starting");
var dbPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"DomainReputationInspector",
"et_rules.db"
);
LogMessage($"ET RULES: Database path: {dbPath}");
Directory.CreateDirectory(Path.GetDirectoryName(dbPath));
LogMessage("ET RULES: Directory created");
_database = new SQLiteConnection($"Data Source={dbPath}");
LogMessage("ET RULES: SQLite connection created");
_database.Open();
LogMessage("ET RULES: Database opened successfully");
// Create tables without MainDomain initially (for backward compatibility)
var createTablesCommand = @"
CREATE TABLE IF NOT EXISTS ET_Domain_Indicators (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Domain TEXT NOT NULL,
RuleId INTEGER,
Description TEXT,
Classification TEXT,
Severity TEXT,
RuleSource TEXT,
FirstSeen DATETIME,
LastUpdated DATETIME,
IsActive BOOLEAN DEFAULT 1
);
CREATE INDEX IF NOT EXISTS idx_domain ON ET_Domain_Indicators(Domain);
CREATE INDEX IF NOT EXISTS idx_severity ON ET_Domain_Indicators(Severity);
CREATE INDEX IF NOT EXISTS idx_classification ON ET_Domain_Indicators(Classification);
CREATE INDEX IF NOT EXISTS idx_rule_source ON ET_Domain_Indicators(RuleSource);
CREATE TABLE IF NOT EXISTS ET_Update_Log (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
UpdateTime DATETIME,
RuleSource TEXT,
RulesCount INTEGER,
Success BOOLEAN,
ErrorMessage TEXT
);
CREATE TABLE IF NOT EXISTS ET_Settings (
Key TEXT PRIMARY KEY,
Value TEXT
);
";
LogMessage("ET RULES: About to execute CREATE TABLE statements");
using (var command = new SQLiteCommand(createTablesCommand, _database))
{
command.ExecuteNonQuery();
}
LogMessage("ET RULES: CREATE TABLE statements executed successfully");
LogMessage("ET RULES: Starting database migration check");
// Migrate existing database to add MainDomain column if it doesn't exist
MigrateDatabaseSchema();
LogMessage("ET RULES: MigrateDatabaseSchema() completed");
// Purge soft-deleted history / exact dupes, then enforce unique Domain+RuleId
PurgeDuplicateAndInactiveIndicators();
EnsureUniqueDomainRuleIndex();
LogMessage("ET RULES: Database initialized and migration completed");
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Database initialization failed: {ex.Message}");
throw;
}
}
private int GetActiveIndicatorCount()
{
try
{
if (_database == null)
return 0;
using (var command = new SQLiteCommand(
"SELECT COUNT(*) FROM ET_Domain_Indicators WHERE IsActive = 1", _database))
{
return Convert.ToInt32(command.ExecuteScalar());
}
}
catch
{
return 0;
}
}
private bool NeedsInitialDownload()
{
if (GetActiveIndicatorCount() <= 0)
return true;
if (_lastUpdateTime == DateTime.MinValue)
return true;
if (DateTime.Now - _lastUpdateTime >= _updateInterval)
return true;
return false;
}
private void PurgeDuplicateAndInactiveIndicators()
{
try
{
int totalBefore;
int inactiveBefore;
using (var totalCmd = new SQLiteCommand("SELECT COUNT(*) FROM ET_Domain_Indicators", _database))
{
totalBefore = Convert.ToInt32(totalCmd.ExecuteScalar());
}
using (var inactiveCmd = new SQLiteCommand(
"SELECT COUNT(*) FROM ET_Domain_Indicators WHERE IsActive = 0", _database))
{
inactiveBefore = Convert.ToInt32(inactiveCmd.ExecuteScalar());
}
if (totalBefore == 0)
{
LogMessage("ET RULES: No indicators to purge");
return;
}
int deletedInactive = 0;
int deletedDupes = 0;
using (var transaction = _database.BeginTransaction())
{
using (var deleteInactive = new SQLiteCommand(
"DELETE FROM ET_Domain_Indicators WHERE IsActive = 0", _database, transaction))
{
deletedInactive = deleteInactive.ExecuteNonQuery();
}
// Keep one row per Domain+RuleId after inactive purge
using (var deleteDupes = new SQLiteCommand(@"
DELETE FROM ET_Domain_Indicators
WHERE Id NOT IN (
SELECT MAX(Id) FROM ET_Domain_Indicators GROUP BY Domain, RuleId
)", _database, transaction))
{
deletedDupes = deleteDupes.ExecuteNonQuery();
}
transaction.Commit();
}
int totalAfter;
using (var totalCmd = new SQLiteCommand("SELECT COUNT(*) FROM ET_Domain_Indicators", _database))
{
totalAfter = Convert.ToInt32(totalCmd.ExecuteScalar());
}
LogMessage($"ET RULES: Purge complete - before={totalBefore}, inactive={inactiveBefore}, deletedInactive={deletedInactive}, deletedDupes={deletedDupes}, after={totalAfter}");
// One-shot VACUUM only when a large purge freed significant space
if (deletedInactive + deletedDupes >= 1000)
{
LogMessage("ET RULES: Running one-shot VACUUM after large purge");
using (var vacuum = new SQLiteCommand("VACUUM", _database))
{
vacuum.ExecuteNonQuery();
}
LogMessage("ET RULES: VACUUM completed");
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Purge of duplicate/inactive indicators failed: {ex.Message}");
}
}
private void EnsureUniqueDomainRuleIndex()
{
try
{
using (var command = new SQLiteCommand(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_domain_ruleid ON ET_Domain_Indicators(Domain, RuleId)",
_database))
{
command.ExecuteNonQuery();
}
LogMessage("ET RULES: Unique index idx_domain_ruleid ready");
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Failed to create unique Domain+RuleId index: {ex.Message}");
}
}
private void LoadSettings()
{
try
{
LogMessage("ET RULES: LoadSettings() - Starting");
using (var command = new SQLiteCommand("SELECT Value FROM ET_Settings WHERE Key = 'ETProApiKey'", _database))
{
var result = command.ExecuteScalar();
_etProApiKey = result?.ToString() ?? string.Empty;
}
// Load last update time
using (var updateCommand = new SQLiteCommand("SELECT Value FROM ET_Settings WHERE Key = 'LastUpdateTime'", _database))
{
var updateResult = updateCommand.ExecuteScalar();
if (updateResult != null && DateTime.TryParse(updateResult.ToString(), out DateTime lastUpdate))
{
_lastUpdateTime = lastUpdate;
}
}
LogMessage($"ET RULES: Settings loaded - API key: {(string.IsNullOrEmpty(_etProApiKey) ? "Not set (using ET Open)" : "Set (using ET Pro)")}");
LogMessage("ET RULES: LoadSettings() - Completed successfully");
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Settings load failed: {ex.Message}");
}
}
private void SaveSettings()
{
try
{
using (var command = new SQLiteCommand(@"
INSERT OR REPLACE INTO ET_Settings (Key, Value)
VALUES ('ETProApiKey', @apiKey)", _database))
{
command.Parameters.AddWithValue("@apiKey", _etProApiKey ?? string.Empty);
command.ExecuteNonQuery();
}
using (var updateCommand = new SQLiteCommand(@"
INSERT OR REPLACE INTO ET_Settings (Key, Value)
VALUES ('LastUpdateTime', @lastUpdate)", _database))
{
updateCommand.Parameters.AddWithValue("@lastUpdate", _lastUpdateTime.ToString("O"));
updateCommand.ExecuteNonQuery();
}
LogMessage("ET RULES: Settings saved");
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Settings save failed: {ex.Message}");
}
}
private async void CheckForDailyUpdate(object state)
{
if (_disposed)
return;
try
{
await _updateSemaphore.WaitAsync();
var now = DateTime.Now;
var shouldUpdate = false;
// Check if initial load is needed
if (_lastUpdateTime == DateTime.MinValue)
{
LogMessage("ET RULES: Initial rules download required");
shouldUpdate = true;
}
else
{
var timeSinceLastUpdate = now - _lastUpdateTime;
// Check if it's been more than 24 hours since last update
if (timeSinceLastUpdate >= _updateInterval)
{
// Prefer to update between 2-3 AM, but don't wait indefinitely
if ((now.Hour >= 2 && now.Hour < 3) || timeSinceLastUpdate.TotalHours > 25)
{
LogMessage($"ET RULES: Daily update time reached (last update: {timeSinceLastUpdate.TotalHours:F1}h ago)");
shouldUpdate = true;
}
}
}
if (shouldUpdate)
{
await DownloadAndParseAllRulesAsync();
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Daily update check failed: {ex.Message}");
}
finally
{
_updateSemaphore.Release();
}
}
private async Task DownloadAndParseAllRulesAsync()
{
try
{
var ruleSource = string.IsNullOrEmpty(_etProApiKey) ? "ET Open" : "ET Pro";
LogMessage($"ET RULES: Starting daily rules update from {ruleSource}");
var allIndicators = new List<ETDomainIndicator>();
// Use official tar.gz archives as per ET documentation
if (string.IsNullOrEmpty(_etProApiKey))
{
// Download ET Open archive
var success = await DownloadAndExtractArchive(ET_OPEN_ARCHIVE_URL, "ET Open", allIndicators);
if (!success)
{
LogMessage("ET RULES ERROR: Failed to download ET Open archive");
}
}
else
{
// Try ET Pro archive first
var etProUrl = BuildEtProUrl(ET_PRO_ARCHIVE_URL);
var success = await DownloadAndExtractArchive(etProUrl, "ET Pro", allIndicators);
if (!success)
{
LogMessage("ET RULES: ET Pro archive failed, falling back to ET Open");
ruleSource = "ET Open (ET Pro fallback)";
await DownloadAndExtractArchive(ET_OPEN_ARCHIVE_URL, ruleSource, allIndicators);
}
}
if (allIndicators.Count > 0)
{
await StoreDomainIndicatorsAsync(allIndicators, ruleSource);
UpdateMemoryCache(allIndicators);
_lastUpdateTime = DateTime.Now;
SaveSettings();
LogMessage($"ET RULES: Daily update completed successfully - {allIndicators.Count} total indicators from {ruleSource}");
}
else
{
LogMessage("ET RULES ERROR: No indicators found in any rule set");
}
}
catch (Exception ex)
{
LogMessage($"ET RULES ERROR: Daily update failed: {ex.Message}");
// Log the failure
await LogUpdateResult(0, false, ex.Message);
}
}
private async Task<bool> DownloadAndExtractArchive(string archiveUrl, string source, List<ETDomainIndicator> allIndicators)
{
try
{
LogMessage($"ET RULES: Downloading {source} archive from {archiveUrl}");
var response = await _httpClient.GetAsync(archiveUrl);
if (!response.IsSuccessStatusCode)
{
LogMessage($"ET RULES ERROR: Failed to download {source} archive - Status: {response.StatusCode}");
return false;
}
var archiveData = await response.Content.ReadAsByteArrayAsync();
LogMessage($"ET RULES: Downloaded {archiveData.Length} bytes of {source} archive");
// Extract and parse the tar.gz content
var extractedIndicators = await ExtractAndParseArchive(archiveData, source);
if (extractedIndicators.Count > 0)
{
allIndicators.AddRange(extractedIndicators);
LogMessage($"ET RULES: Successfully extracted {extractedIndicators.Count} indicators from {source} archive");
return true;
}
else
{
LogMessage($"ET RULES: No indicators found in {source} archive");
return false;
}