Azathothas commited on
Commit
125374d
·
verified ·
1 Parent(s): 623fe66

Delete apks/analyze_traffic.ps1

Browse files
Files changed (1) hide show
  1. apks/analyze_traffic.ps1 +0 -735
apks/analyze_traffic.ps1 DELETED
@@ -1,735 +0,0 @@
1
- # =============================================================================
2
- # Daily DoI traffic detection and behavioural analysis
3
- # Requires: ripgrep (rg) in PATH, PowerShell 5.1+
4
- # =============================================================================
5
-
6
- #Requires -Version 5.1
7
- Set-StrictMode -Version Latest
8
- $ErrorActionPreference = "Stop"
9
-
10
- # =============================================================================
11
- # CONFIGURATION — edit these values before deploying
12
- # =============================================================================
13
- $Config = @{
14
- # Folder containing your URL-log CSV files
15
- LogFolder = "$env:USERPROFILE\Downloads\URL_LOG"
16
-
17
- # Where to save .txt reports (created automatically if absent)
18
- ReportFolder = "$env:USERPROFILE\Downloads\URL_LOG\Reports"
19
-
20
- # NSFW wildcard blocklist
21
- #BlocklistUrl = "https://nsfw.oisd.nl/"
22
- BlocklistUrl = "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/nsfw-onlydomains.txt"
23
- #BlocklistUrl = "https://raw.githubusercontent.com/sjhgvr/oisd/refs/heads/main/oisd_nsfw.txt"
24
-
25
-
26
- # Re-download blocklist when cache is older than this many hours (0 = always)
27
- BlocklistCacheHours = 3
28
-
29
- # Cached raw blocklist location
30
- BlocklistCache = "$env:TEMP\domains_doi_cache.txt"
31
-
32
- # Compiled ripgrep pattern file (rebuilt when blocklist refreshes)
33
- PatternFile = "$env:TEMP\domains_doi_patterns.txt"
34
-
35
- # Analyse only CSVs modified within this many days (0 = all files)
36
- CSVMaxAgeDays = 1
37
-
38
- # CSV column indices (0-based). Adjust to match your log format.
39
- ColTime = 0
40
- ColProtocol = 1
41
- ColSrcIP = 2
42
- ColSrcPort = 3
43
- ColDstIP = 4
44
- ColDstPort = 5
45
- ColURL = 6
46
- ColMAC = 7
47
- ColID = 8
48
-
49
- # Maximum rows to show in each ranked table
50
- TopN = 15
51
-
52
- # Minimum unique adult domains for "exploratory behaviour" flag
53
- ExploratoryThreshold = 5
54
-
55
- # Night-time window (inclusive hours, 24h clock)
56
- NightStart = 0
57
- NightEnd = 5
58
-
59
- # Burst-behaviour threshold: hits from a single device in one hour
60
- BurstThreshold = 50
61
- }
62
- # =============================================================================
63
-
64
-
65
- # ---------------------------------------------------------------------------
66
- # Console helpers
67
- # ---------------------------------------------------------------------------
68
- function Write-Header {
69
- param([string]$Text, [string]$Char = "=", [int]$Width = 72)
70
- $line = $Char * $Width
71
- Write-Host ""
72
- Write-Host $line -ForegroundColor Cyan
73
- Write-Host " $Text" -ForegroundColor Cyan
74
- Write-Host $line -ForegroundColor Cyan
75
- }
76
-
77
- function Write-Section {
78
- param([string]$Text)
79
- Write-Host ""
80
- Write-Host " -- $Text --" -ForegroundColor Yellow
81
- Write-Host (" " + ("-" * ($Text.Length + 6))) -ForegroundColor DarkYellow
82
- }
83
-
84
- function Write-Ok { param([string]$m) Write-Host " [OK] $m" -ForegroundColor Green }
85
- function Write-Warn { param([string]$m) Write-Host " [!!] $m" -ForegroundColor Yellow }
86
- function Write-Err { param([string]$m) Write-Host " [ERR] $m" -ForegroundColor Red }
87
- function Write-Info { param([string]$m) Write-Host " [>>] $m" -ForegroundColor Gray }
88
-
89
- # ---------------------------------------------------------------------------
90
- # Report buffer
91
- # ---------------------------------------------------------------------------
92
- $ReportLines = [System.Collections.Generic.List[string]]::new()
93
- function Add-ReportLine { param([string]$line = "") $ReportLines.Add($line) | Out-Null }
94
- # ---------------------------------------------------------------------------
95
- # RFC-4180-aware CSV line parser (handles quoted fields with embedded commas)
96
- # ---------------------------------------------------------------------------
97
- function Split-CsvLine {
98
- param([string]$Line)
99
- $fields = [System.Collections.Generic.List[string]]::new()
100
- $current = [System.Text.StringBuilder]::new()
101
- $inQuote = $false
102
-
103
- for ($i = 0; $i -lt $Line.Length; $i++) {
104
- $ch = $Line[$i]
105
- if ($inQuote) {
106
- if ($ch -eq '"') {
107
- # Peek ahead: escaped double-quote?
108
- if (($i + 1) -lt $Line.Length -and $Line[$i + 1] -eq '"') {
109
- [void]$current.Append('"')
110
- $i++
111
- } else {
112
- $inQuote = $false
113
- }
114
- } else {
115
- [void]$current.Append($ch)
116
- }
117
- } else {
118
- if ($ch -eq '"') { $inQuote = $true }
119
- elseif ($ch -eq ',') { $fields.Add($current.ToString()); [void]$current.Clear() }
120
- else { [void]$current.Append($ch) }
121
- }
122
- }
123
- $fields.Add($current.ToString()) # last field
124
- return ,$fields.ToArray() # unary comma forces array return
125
- }
126
-
127
- # ---------------------------------------------------------------------------
128
- # Extract the registrable domain (eTLD+1)
129
- # e.g. "http://www.example.co.uk/path" → "example.co.uk"
130
- # Falls back gracefully for IPs and bare hostnames.
131
- # ---------------------------------------------------------------------------
132
- function Get-RegisteredDomain {
133
- param([string]$Url)
134
- if ([string]::IsNullOrWhiteSpace($Url)) { return "(empty)" }
135
- # Strip scheme, path, port, query, fragment
136
- $hostname = $Url.Trim() `
137
- -replace '^https?://', '' `
138
- -replace '[/:?#].*$', '' `
139
- -replace '^\s+|\s+$', ''
140
- if ($hostname -eq '') { return $Url.Trim() }
141
- $parts = $hostname -split '\.'
142
- if ($parts.Count -ge 2) {
143
- return (($parts[-2] + '.' + $parts[-1]).ToLower())
144
- }
145
- return $hostname.ToLower()
146
- }
147
-
148
- # ---------------------------------------------------------------------------
149
- # Multi-format datetime parser — returns $null on failure
150
- # (handles logs with varying timestamp formats)
151
- # ---------------------------------------------------------------------------
152
- function Parse-Time {
153
- param([string]$Raw)
154
- if ([string]::IsNullOrWhiteSpace($Raw)) { return $null }
155
- $dt = $null
156
- $formats = @(
157
- "yyyy-MM-dd HH:mm:ss",
158
- "yyyy-MM-ddTHH:mm:ss",
159
- "MM/dd/yyyy HH:mm:ss",
160
- "dd/MM/yyyy HH:mm:ss",
161
- "yyyy-MM-dd HH:mm:ss.fff",
162
- "yyyy-MM-ddTHH:mm:ss.fff"
163
- )
164
- foreach ($fmt in $formats) {
165
- $parsed = [datetime]::new(1, 1, 1)
166
- if ([datetime]::TryParseExact(
167
- $Raw.Trim(),
168
- [string]$fmt,
169
- [System.Globalization.CultureInfo]::InvariantCulture,
170
- [System.Globalization.DateTimeStyles]::None,
171
- [ref]$parsed)) {
172
- return $parsed
173
- }
174
- }
175
- # Last-resort general parse
176
- if ([datetime]::TryParse($Raw.Trim(), [ref]$dt)) { return $dt }
177
- return $null
178
- }
179
-
180
- # ---------------------------------------------------------------------------
181
- # Banner
182
- # ---------------------------------------------------------------------------
183
- $RunTime = Get-Date
184
- $RunStamp = $RunTime.ToString("yyyy-MM-dd HH:mm:ss")
185
-
186
- Write-Header "Domains of Interest (DoI) TRAFFIC ANALYSER | $RunStamp"
187
- Write-Info "Log folder : $($Config.LogFolder)"
188
- Write-Info "Report folder : $($Config.ReportFolder)"
189
- Write-Info "PowerShell : $($PSVersionTable.PSVersion)"
190
-
191
- # ---------------------------------------------------------------------------
192
- # Step 1 — Ensure report folder exists
193
- # ---------------------------------------------------------------------------
194
- if (-not (Test-Path $Config.ReportFolder -PathType Container)) {
195
- try {
196
- New-Item -ItemType Directory -Path $Config.ReportFolder -Force | Out-Null
197
- Write-Ok "Created report folder: $($Config.ReportFolder)"
198
- } catch {
199
- Write-Err "Cannot create report folder: $($_.Exception.Message)"
200
- exit 1
201
- }
202
- }
203
-
204
- # ---------------------------------------------------------------------------
205
- # Step 2 — Validate log folder
206
- # ---------------------------------------------------------------------------
207
- if (-not (Test-Path $Config.LogFolder -PathType Container)) {
208
- Write-Err "Log folder not found: $($Config.LogFolder)"
209
- exit 1
210
- }
211
-
212
- # ---------------------------------------------------------------------------
213
- # Step 3 — Verify ripgrep is available (fail fast before any heavy work)
214
- # ---------------------------------------------------------------------------
215
- Write-Section "Dependency Check"
216
-
217
- if (-not (Get-Command rg -ErrorAction SilentlyContinue)) {
218
- Write-Err "'rg' (ripgrep) not found in PATH."
219
- Write-Info "Install options:"
220
- Write-Info " winget : winget install BurntSushi.ripgrep.MSVC"
221
- Write-Info " choco : choco install ripgrep"
222
- Write-Info " scoop : scoop install ripgrep"
223
- Write-Info " manual : https://github.com/BurntSushi/ripgrep/releases"
224
- exit 1
225
- }
226
- $rgVersion = (& rg --version 2>&1 | Select-Object -First 1)
227
- Write-Ok "ripgrep found — $rgVersion"
228
-
229
- # ---------------------------------------------------------------------------
230
- # Step 4 — Download / cache blocklist
231
- # ---------------------------------------------------------------------------
232
- Write-Section "Blocklist"
233
-
234
- $needDownload = $true
235
- if (Test-Path $Config.BlocklistCache) {
236
- $cacheAge = (Get-Date) - (Get-Item $Config.BlocklistCache).LastWriteTime
237
- if ($Config.BlocklistCacheHours -gt 0 -and $cacheAge.TotalHours -lt $Config.BlocklistCacheHours) {
238
- Write-Ok "Using cached blocklist (age: $([math]::Round($cacheAge.TotalHours,1)) hrs) <== $($Config.BlocklistCache)"
239
- $needDownload = $false
240
- } else {
241
- Write-Info "Cache expired ($([math]::Round($cacheAge.TotalHours,1)) hrs) — re-downloading"
242
- }
243
- }
244
-
245
- if ($needDownload) {
246
- Write-Info "Downloading blocklist from [$($Config.BlocklistUrl)] ..."
247
- $downloaded = $false
248
- $maxRetries = 3
249
- for ($attempt = 1; $attempt -le $maxRetries; $attempt++) {
250
- try {
251
- Invoke-WebRequest -Uri $Config.BlocklistUrl `
252
- -OutFile $Config.BlocklistCache `
253
- -UseBasicParsing `
254
- -TimeoutSec 45 `
255
- -ErrorAction Stop
256
- $downloaded = $true
257
- Write-Ok "Blocklist downloaded successfully (attempt $attempt)"
258
- break
259
- } catch {
260
- Write-Warn "Attempt $attempt/$maxRetries failed: $($_.Exception.Message)"
261
- if ($attempt -lt $maxRetries) { Start-Sleep -Seconds (3 * $attempt) }
262
- }
263
- }
264
-
265
- if (-not $downloaded) {
266
- if (Test-Path $Config.BlocklistCache) {
267
- Write-Warn "Download failed — falling back to stale cache"
268
- } else {
269
- Write-Err "No blocklist available (download failed, no cache). Aborting."
270
- exit 1
271
- }
272
- }
273
- }
274
-
275
- # Validate cache is non-empty
276
- if ((Get-Item $Config.BlocklistCache).Length -eq 0) {
277
- Write-Err "Blocklist cache file is empty (corrupt download?). Delete '$($Config.BlocklistCache)' and retry."
278
- exit 1
279
- }
280
-
281
- # Parse blocklist metadata comments
282
- $rawLines = Get-Content $Config.BlocklistCache -Encoding UTF8
283
- $metaVersion = (($rawLines | Where-Object { $_ -match '^#\s*Version:' }) | Select-Object -First 1) -replace '^#\s*Version:\s*', ''
284
- $metaModified = (($rawLines | Where-Object { $_ -match '^#\s*Last modified:' }) | Select-Object -First 1) -replace '^#\s*Last modified:\s*', ''
285
- $metaCount = (($rawLines | Where-Object { $_ -match '^#\s*Number of entries:' }) | Select-Object -First 1) -replace '^#\s*Number of entries:\s*', ''
286
-
287
- if ([string]::IsNullOrWhiteSpace($metaVersion)) { $metaVersion = "unknown" }
288
- if ([string]::IsNullOrWhiteSpace($metaModified)) { $metaModified = "unknown" }
289
- if ([string]::IsNullOrWhiteSpace($metaCount)) { $metaCount = "unknown" }
290
-
291
- Write-Info "Blocklist version : $metaVersion"
292
- Write-Info "Last modified : $metaModified"
293
- Write-Info "Domain count : $metaCount"
294
-
295
- # Build ripgrep pattern file
296
- # FIX: use a placeholder string instead of PS variable interpolation inside the
297
- # regex template — avoids '$' being swallowed by the PS string expander.
298
- Write-Info "Building regex pattern file..."
299
- $domains = $rawLines |
300
- Where-Object { $_ -notmatch '^\s*#' -and $_ -notmatch '^\s*$' } |
301
- ForEach-Object { $_.Trim() } |
302
- Where-Object { $_ -ne '' }
303
-
304
- if ($domains.Count -eq 0) {
305
- Write-Err "Blocklist parsed 0 domains — file may be corrupt. Delete '$($Config.BlocklistCache)' and retry."
306
- exit 1
307
- }
308
-
309
- # Pattern matches the domain (with optional sub-domain) inside a URL field,
310
- # terminated by /, :, ?, #, or end-of-field.
311
- $patternTemplate = 'https?://(?:[^/,\s]+\.)?DOMAIN_PLACEHOLDER(?:[/:?#,]|$)'
312
- $domains | ForEach-Object {
313
- $escaped = [regex]::Escape($_)
314
- $patternTemplate -replace 'DOMAIN_PLACEHOLDER', $escaped
315
- } | Set-Content $Config.PatternFile -Encoding UTF8
316
-
317
- Write-Ok "Pattern file built ($($domains.Count) patterns → $($Config.PatternFile))"
318
-
319
- # ---------------------------------------------------------------------------
320
- # Step 5 — Find CSV files
321
- # FIX: resolve the Reports subfolder path and exclude it so we never scan
322
- # previously saved reports (prevents double-counting on re-runs).
323
- # ---------------------------------------------------------------------------
324
- Write-Section "CSV Files"
325
-
326
- $resolvedReportFolder = $null
327
- try {
328
- $resolvedReportFolder = (Resolve-Path $Config.ReportFolder -ErrorAction SilentlyContinue)?.Path
329
- } catch { }
330
-
331
- $csvFiles = Get-ChildItem -Path $Config.LogFolder -Filter '*.csv' -File |
332
- Where-Object {
333
- ($null -eq $resolvedReportFolder -or
334
- -not $_.FullName.StartsWith($resolvedReportFolder,
335
- [System.StringComparison]::OrdinalIgnoreCase)) -and
336
- ($Config.CSVMaxAgeDays -eq 0 -or
337
- ((Get-Date) - $_.LastWriteTime).TotalDays -le $Config.CSVMaxAgeDays)
338
- } |
339
- Sort-Object LastWriteTime
340
-
341
- if ($csvFiles.Count -eq 0) {
342
- Write-Warn "No CSV files found in '$($Config.LogFolder)' within the last $($Config.CSVMaxAgeDays) day(s)."
343
- Write-Info "Tip: set CSVMaxAgeDays = 0 in `$Config to scan all files regardless of age."
344
- exit 0
345
- }
346
-
347
- $totalSizeMB = [math]::Round(($csvFiles | Measure-Object -Property Length -Sum).Sum / 1MB, 2)
348
- Write-Ok "$($csvFiles.Count) CSV file(s) found ($totalSizeMB MB total)"
349
- foreach ($f in $csvFiles) {
350
- Write-Info " $($f.Name) [$([math]::Round($f.Length/1MB,2)) MB] modified $($f.LastWriteTime.ToString('yyyy-MM-dd HH:mm'))"
351
- }
352
-
353
- # ---------------------------------------------------------------------------
354
- # Step 6 — Run ripgrep (batched to stay under compiled-regex size limit)
355
- # ---------------------------------------------------------------------------
356
- Write-Section "Scanning"
357
-
358
- $allPatterns = Get-Content $Config.PatternFile -Encoding UTF8
359
- $batchSize = 5000
360
- $batches = [System.Collections.Generic.List[string[]]]::new()
361
-
362
- for ($i = 0; $i -lt $allPatterns.Count; $i += $batchSize) {
363
- $batches.Add($allPatterns[$i .. [math]::Min($i + $batchSize - 1, $allPatterns.Count - 1)])
364
- }
365
-
366
- Write-Info "Running ripgrep in $($batches.Count) batch(es) of up to $batchSize patterns each..."
367
- $sw = [System.Diagnostics.Stopwatch]::StartNew()
368
- $matchLines = [System.Collections.Generic.List[string]]::new()
369
- $batchNum = 0
370
-
371
- foreach ($batch in $batches) {
372
- $batchNum++
373
- $tmpPattern = Join-Path $env:TEMP "domains_batch_$batchNum.txt"
374
- $batch | Set-Content $tmpPattern -Encoding UTF8
375
-
376
- $rgArgs = @(
377
- '--file', $tmpPattern,
378
- '--no-filename',
379
- '--no-line-number',
380
- '--no-heading',
381
- '--ignore-case'
382
- ) + ($csvFiles | ForEach-Object { $_.FullName })
383
-
384
- $savedEAP = $ErrorActionPreference
385
- $ErrorActionPreference = "Continue"
386
- $rawMatches = & rg @rgArgs 2>&1
387
- $rgExitCode = $LASTEXITCODE
388
- $ErrorActionPreference = $savedEAP
389
-
390
- if ($rgExitCode -gt 1) {
391
- $rgErrors = @($rawMatches | Where-Object { $_ -match '^rg:' })
392
- Write-Err "ripgrep batch $batchNum returned error code $rgExitCode"
393
- foreach ($e in $rgErrors) { Write-Err " $e" }
394
- exit 1
395
- }
396
-
397
- $batchMatches = @(
398
- $rawMatches |
399
- Where-Object { $_ -is [string] -and $_ -notmatch '^rg:' -and $_.Trim() -ne '' }
400
- )
401
- #$matchLines.AddRange($batchMatches)
402
- if ($null -ne $batchMatches -and $batchMatches.Count -gt 0) {
403
- $matchLines.AddRange([string[]]@($batchMatches))
404
- }
405
- Write-Info " Batch $batchNum/$($batches.Count) — $($batchMatches.Count) hit(s)"
406
-
407
- Remove-Item $tmpPattern -ErrorAction SilentlyContinue
408
-
409
- }
410
- # Deduplicate across batches (a line matching 2+ patterns would appear twice)
411
- Write-Info "Sorting & DeDupilicating ..."
412
- $matchLines = [System.Collections.Generic.List[string]]($matchLines | Select-Object -Unique)
413
-
414
- $sw.Stop()
415
- Write-Info "Scan completed in $($sw.Elapsed.TotalSeconds.ToString('F1')) seconds"
416
- Write-Ok "Scan complete — $($matchLines.Count) matching log line(s) found"
417
-
418
- # ---------------------------------------------------------------------------
419
- # Step 7 — Parse matches into structured objects
420
- # FIX: use RFC-4180-aware Split-CsvLine (handles quoted fields with commas)
421
- # and Parse-Time (handles multiple timestamp formats).
422
- # ---------------------------------------------------------------------------
423
- Write-Section "Parsing"
424
-
425
- $skipped = 0
426
- $records = [System.Collections.Generic.List[PSCustomObject]]::new()
427
-
428
- foreach ($line in $matchLines) {
429
- $parts = Split-CsvLine -Line $line
430
- $minCols = ([math]::Max($Config.ColURL, $Config.ColMAC)) + 1
431
-
432
- if ($parts.Count -lt $minCols) {
433
- $skipped++
434
- continue
435
- }
436
-
437
- $rawTime = $parts[$Config.ColTime].Trim()
438
- $rawUrl = $parts[$Config.ColURL].Trim()
439
- $rawMAC = $parts[$Config.ColMAC].Trim()
440
-
441
- # Normalise missing MAC so grouping still works
442
- if ([string]::IsNullOrWhiteSpace($rawMAC)) { $rawMAC = "(no-mac)" }
443
-
444
- # Use multi-format parser for robust timestamp handling
445
- $parsedDt = Parse-Time $rawTime
446
- $parsedHour = if ($null -ne $parsedDt) { $parsedDt.Hour } else { -1 }
447
-
448
- $records.Add([PSCustomObject]@{
449
- Time = $rawTime
450
- DateTime = $parsedDt
451
- Hour = $parsedHour
452
- Protocol = $parts[$Config.ColProtocol].Trim()
453
- SrcIP = $parts[$Config.ColSrcIP].Trim()
454
- SrcPort = $parts[$Config.ColSrcPort].Trim()
455
- DstIP = $parts[$Config.ColDstIP].Trim()
456
- DstPort = $parts[$Config.ColDstPort].Trim()
457
- URL = $rawUrl
458
- MAC = $rawMAC
459
- ID = if ($parts.Count -gt $Config.ColID) { $parts[$Config.ColID].Trim() } else { '' }
460
- Domain = Get-RegisteredDomain -Url $rawUrl
461
- })
462
- }
463
-
464
- if ($skipped -gt 0) {
465
- Write-Warn "$skipped line(s) skipped (too few columns / malformed)"
466
- }
467
-
468
- if ($records.Count -eq 0) {
469
- Write-Warn "All matched lines failed to parse — check your column index settings in `$Config."
470
- exit 1
471
- }
472
-
473
- $totalHits = $records.Count
474
- $uniqueMACs = ($records | Select-Object -ExpandProperty MAC -Unique).Count
475
- $uniqueDomains = ($records | Select-Object -ExpandProperty Domain -Unique).Count
476
- $uniqueIPs = ($records | Select-Object -ExpandProperty SrcIP -Unique).Count
477
-
478
- Write-Ok "Parsed $totalHits records | $uniqueMACs device(s) | $uniqueIPs IP(s) | $uniqueDomains domain(s)"
479
-
480
- # Pre-compute grouped data reused across multiple report sections
481
- $deviceGroups = $records | Group-Object MAC | Sort-Object Count -Descending | Select-Object -First $Config.TopN
482
- $domainGroups = $records | Group-Object Domain | Sort-Object Count -Descending | Select-Object -First $Config.TopN
483
-
484
- $hourData = $records | Where-Object { $_.Hour -ge 0 } | Group-Object Hour | Sort-Object { [int]$_.Name }
485
- $maxHits = if ($hourData.Count -gt 0) { ($hourData | Measure-Object -Property Count -Maximum).Maximum } else { 1 }
486
- if ($null -eq $maxHits -or $maxHits -eq 0) { $maxHits = 1 }
487
-
488
- # ---------------------------------------------------------------------------
489
- # Step 8 — Build report
490
- # ---------------------------------------------------------------------------
491
- Write-Section "Building Report"
492
-
493
- $sep = "=" * 72
494
- $sep2 = "-" * 72
495
- $maxBar = 40
496
-
497
- Add-ReportLine $sep
498
- Add-ReportLine " DoI TRAFFIC ANALYSIS REPORT"
499
- Add-ReportLine " Generated : $RunStamp"
500
- Add-ReportLine " Log Folder : $($Config.LogFolder)"
501
- Add-ReportLine " Blocklist : List v$metaVersion ($metaModified)"
502
- Add-ReportLine " Scan time : $($sw.Elapsed.TotalSeconds.ToString('F1'))s | Skipped lines: $skipped"
503
- Add-ReportLine $sep
504
- Add-ReportLine ""
505
-
506
- # ── Summary ────────────────────────────────────────────────────────────────
507
- Add-ReportLine " SUMMARY"
508
- Add-ReportLine $sep2
509
- Add-ReportLine (" Total matching log entries : {0,6}" -f $totalHits)
510
- Add-ReportLine (" Unique devices (MAC) : {0,6}" -f $uniqueMACs)
511
- Add-ReportLine (" Unique source IPs : {0,6}" -f $uniqueIPs)
512
- Add-ReportLine (" Unique adult domains hit : {0,6}" -f $uniqueDomains)
513
- Add-ReportLine (" Files scanned : {0,6}" -f $csvFiles.Count)
514
- Add-ReportLine (" Skipped / malformed rows : {0,6}" -f $skipped)
515
- Add-ReportLine ""
516
-
517
- # ── [A] Top Offending Devices ───────────────────────────────────────────────
518
- Add-ReportLine $sep
519
- Add-ReportLine " [A] TOP OFFENDING DEVICES (top $($Config.TopN))"
520
- Add-ReportLine $sep
521
- Add-ReportLine ""
522
-
523
- foreach ($dg in $deviceGroups) {
524
- $ips = ($dg.Group | Select-Object -ExpandProperty SrcIP -Unique | Sort-Object) -join ", "
525
- $sites = @($dg.Group | Select-Object -ExpandProperty Domain -Unique | Sort-Object)
526
- # Use DateTime-sorted order when available, fall back to raw string sort
527
- $sortedByTime = @($dg.Group | Where-Object { $null -ne $_.DateTime } | Sort-Object DateTime)
528
- if ($sortedByTime.Count -gt 0) {
529
- $first = $sortedByTime[0].Time
530
- $last = $sortedByTime[-1].Time
531
- } else {
532
- $sortedRaw = @($dg.Group | Sort-Object Time)
533
- $first = $sortedRaw[0].Time
534
- $last = $sortedRaw[-1].Time
535
- }
536
-
537
- Add-ReportLine (" MAC : {0}" -f $dg.Name)
538
- Add-ReportLine (" IP(s) : {0}" -f $ips)
539
- Add-ReportLine (" Hits : {0}" -f $dg.Count)
540
- Add-ReportLine (" Window : {0} → {1}" -f $first, $last)
541
- Add-ReportLine (" Sites ({0}):" -f $sites.Count)
542
- foreach ($s in $sites) { Add-ReportLine (" - {0}" -f $s) }
543
- Add-ReportLine $sep2
544
- }
545
- Add-ReportLine ""
546
-
547
- # ── [B] Top Adult Domains ──────────────────────────────────────────────────
548
- Add-ReportLine $sep
549
- Add-ReportLine " [B] TOP ADULT DOMAINS (top $($Config.TopN))"
550
- Add-ReportLine $sep
551
- Add-ReportLine ""
552
- Add-ReportLine (" {0,-45} {1,7} {2}" -f "Domain", "Hits", "Devices (MAC)")
553
- Add-ReportLine (" {0,-45} {1,7} {2}" -f ("-" * 45), ("-" * 7), ("-" * 30))
554
-
555
- foreach ($dg in $domainGroups) {
556
- $devs = ($dg.Group | Select-Object -ExpandProperty MAC -Unique | Sort-Object) -join ", "
557
- if ($devs.Length -gt 60) { $devs = $devs.Substring(0, 57) + "..." }
558
- Add-ReportLine (" {0,-45} {1,7} {2}" -f $dg.Name, $dg.Count, $devs)
559
- }
560
- Add-ReportLine ""
561
-
562
- # ── [C] Activity Timeline ──────────────────────────────────────────────────
563
- Add-ReportLine $sep
564
- Add-ReportLine " [C] ACTIVITY TIMELINE (hits per hour)"
565
- Add-ReportLine $sep
566
- Add-ReportLine ""
567
-
568
- if ($hourData.Count -gt 0) {
569
- foreach ($hg in $hourData) {
570
- $barLen = [math]::Round(([int]$hg.Count / $maxHits) * $maxBar)
571
- $bar = "#" * $barLen
572
- $label = "{0:D2}:00" -f [int]$hg.Name
573
- Add-ReportLine (" {0} {1,-42} {2,5} hits" -f $label, $bar, $hg.Count)
574
- }
575
- } else {
576
- Add-ReportLine " (No parseable timestamps — timeline unavailable)"
577
- }
578
- Add-ReportLine ""
579
-
580
- # ── [D] Protocol Breakdown ─────────────────────────────────────────────────
581
- Add-ReportLine $sep
582
- Add-ReportLine " [D] PROTOCOL BREAKDOWN"
583
- Add-ReportLine $sep
584
- Add-ReportLine ""
585
-
586
- $records | Group-Object Protocol | Sort-Object Count -Descending | ForEach-Object {
587
- $pct = if ($totalHits -gt 0) { $_.Count / $totalHits * 100 } else { 0 }
588
- Add-ReportLine (" {0,-10} {1,6} hits ({2:F1}%)" -f $_.Name, $_.Count, $pct)
589
- }
590
- Add-ReportLine ""
591
-
592
- # ── [E] Top Destination Ports ──────────────────────────────────────────────
593
- Add-ReportLine $sep
594
- Add-ReportLine " [E] TOP DESTINATION PORTS"
595
- Add-ReportLine $sep
596
- Add-ReportLine ""
597
- Add-ReportLine (" {0,-8} {1,8} {2}" -f "Port", "Hits", "% of total")
598
- Add-ReportLine (" {0,-8} {1,8}" -f ("-" * 8), ("-" * 8))
599
-
600
- $records |
601
- Where-Object { -not [string]::IsNullOrWhiteSpace($_.DstPort) } |
602
- Group-Object DstPort | Sort-Object Count -Descending | Select-Object -First 10 |
603
- ForEach-Object {
604
- $pct = if ($totalHits -gt 0) { $_.Count / $totalHits * 100 } else { 0 }
605
- Add-ReportLine (" {0,-8} {1,8} ({2:F1}%)" -f $_.Name, $_.Count, $pct)
606
- }
607
- Add-ReportLine ""
608
-
609
- # ── [F] Behavioural Patterns ───────────────────────────────────────────────
610
- Add-ReportLine $sep
611
- Add-ReportLine " [F] BEHAVIOURAL PATTERNS"
612
- Add-ReportLine $sep
613
- Add-ReportLine ""
614
-
615
- # Peak hour
616
- if ($hourData.Count -gt 0) {
617
- $peakHour = $hourData | Sort-Object Count -Descending | Select-Object -First 1
618
- Add-ReportLine (" Peak activity hour : {0:D2}:00 ({1} hits)" -f [int]$peakHour.Name, $peakHour.Count)
619
- } else {
620
- Add-ReportLine " Peak activity hour : N/A (timestamps unparseable)"
621
- }
622
-
623
- # Night-time hits
624
- $nightHits = ($records |
625
- Where-Object { $_.Hour -ge $Config.NightStart -and $_.Hour -le $Config.NightEnd } |
626
- Measure-Object).Count
627
- $nightPct = if ($totalHits -gt 0) { $nightHits / $totalHits * 100 } else { 0 }
628
- Add-ReportLine (" Night hits ({0:D2}-{1:D2}h) : {2} ({3:F1}% of total)" -f `
629
- $Config.NightStart, $Config.NightEnd, $nightHits, $nightPct)
630
-
631
- # Most active device
632
- if ($deviceGroups.Count -gt 0) {
633
- $topDevice = $deviceGroups | Select-Object -First 1
634
- $topDevSites = ($topDevice.Group | Select-Object -ExpandProperty Domain -Unique).Count
635
- Add-ReportLine (" Most active device : {0} ({1} hits, {2} unique sites)" -f `
636
- $topDevice.Name, $topDevice.Count, $topDevSites)
637
- }
638
- Add-ReportLine ""
639
-
640
- # Exploratory behaviour — devices hitting many unique domains
641
- Add-ReportLine (" Devices with {0}+ unique adult domains (exploratory behaviour):" -f $Config.ExploratoryThreshold)
642
- $foundExploratory = $false
643
- $deviceGroups | ForEach-Object {
644
- $uniq = @($_.Group | Select-Object -ExpandProperty Domain -Unique).Count
645
- if ($uniq -ge $Config.ExploratoryThreshold) {
646
- $foundExploratory = $true
647
- $ip = ($_.Group | Select-Object -ExpandProperty SrcIP -Unique | Sort-Object) -join ", "
648
- Add-ReportLine (" {0} ({1}) — {2} unique domains, {3} total hits" -f $_.Name, $ip, $uniq, $_.Count)
649
- }
650
- }
651
- if (-not $foundExploratory) { Add-ReportLine " None" }
652
- Add-ReportLine ""
653
-
654
- # Sustained sessions — device active across multiple hours
655
- Add-ReportLine " Devices with sessions spanning multiple hours:"
656
- $foundMultiHour = $false
657
- $deviceGroups | ForEach-Object {
658
- $hours = @($_.Group |
659
- Where-Object { $_.Hour -ge 0 } |
660
- Select-Object -ExpandProperty Hour -Unique | Sort-Object)
661
- if ($hours.Count -gt 1) {
662
- $foundMultiHour = $true
663
- $ip = ($_.Group | Select-Object -ExpandProperty SrcIP -Unique | Sort-Object) -join ", "
664
- $span = "{0:D2}:00 — {1:D2}:59" -f [int]$hours[0], [int]$hours[-1]
665
- Add-ReportLine (" {0} ({1}) — active {2} ({3} distinct hours)" -f $_.Name, $ip, $span, $hours.Count)
666
- }
667
- }
668
- if (-not $foundMultiHour) { Add-ReportLine " None" }
669
- Add-ReportLine ""
670
-
671
- # Burst behaviour — devices with >BurstThreshold hits in a single hour
672
- Add-ReportLine (" Devices with >{0} hits in a single hour (burst/automated behaviour):" -f $Config.BurstThreshold)
673
- $foundBurst = $false
674
- $deviceGroups | ForEach-Object {
675
- $mac = $_.Name
676
- $burstHrs = $_.Group |
677
- Where-Object { $_.Hour -ge 0 } |
678
- Group-Object Hour |
679
- Where-Object { $_.Count -gt $Config.BurstThreshold }
680
- foreach ($bh in $burstHrs) {
681
- $foundBurst = $true
682
- $ip = ($_.Group | Select-Object -ExpandProperty SrcIP -Unique | Sort-Object) -join ", "
683
- Add-ReportLine (" {0} ({1}) — {2} hits at {3:D2}:00" -f $mac, $ip, $bh.Count, [int]$bh.Name)
684
- }
685
- }
686
- if (-not $foundBurst) { Add-ReportLine " None" }
687
- Add-ReportLine ""
688
-
689
- # ── Footer ─────────────────────────────────────────────────────────────────
690
- Add-ReportLine $sep
691
- Add-ReportLine (" End of report | $RunStamp")
692
- Add-ReportLine $sep
693
-
694
- # ---------------------------------------------------------------------------
695
- # Step 9 — Print report to terminal with colour coding
696
- # ---------------------------------------------------------------------------
697
- Write-Header "ANALYSIS REPORT"
698
- foreach ($line in $ReportLines) {
699
- if ($line -match '^\s*MAC\s*:') { Write-Host $line -ForegroundColor Cyan }
700
- elseif ($line -match '^\s*Hits\s*:') { Write-Host $line -ForegroundColor Red }
701
- elseif ($line -match '^\s*-\s+\S') { Write-Host $line -ForegroundColor DarkRed }
702
- elseif ($line -match '^\s*\[') { Write-Host $line -ForegroundColor Yellow }
703
- elseif ($line -match '^=+$') { Write-Host $line -ForegroundColor DarkCyan }
704
- elseif ($line -match '^-+$') { Write-Host $line -ForegroundColor DarkGray }
705
- elseif ($line -match '#') { Write-Host $line -ForegroundColor DarkYellow }
706
- elseif ($line -match 'RESULT:.*No DoI') { Write-Host $line -ForegroundColor Green }
707
- elseif ($line -match 'Peak|Night|Most active|burst') { Write-Host $line -ForegroundColor Magenta }
708
- else { Write-Host $line }
709
- }
710
-
711
- # ---------------------------------------------------------------------------
712
- # Step 10 — Save report to disk (with fallback to %TEMP% on failure)
713
- # ---------------------------------------------------------------------------
714
- $reportName = "DoI_Report_" + $RunTime.ToString("yyyy-MM-dd_HHmm") + ".txt"
715
- $reportPath = Join-Path $Config.ReportFolder $reportName
716
-
717
- try {
718
- $ReportLines | Set-Content -Path $reportPath -Encoding UTF8 -ErrorAction Stop
719
- Write-Host ""
720
- Write-Ok "Report saved → $reportPath"
721
- } catch {
722
- Write-Err "Failed to save report to '$reportPath': $($_.Exception.Message)"
723
- $fallback = Join-Path $env:TEMP $reportName
724
- try {
725
- $ReportLines | Set-Content -Path $fallback -Encoding UTF8
726
- Write-Warn "Saved to fallback location: $fallback"
727
- } catch {
728
- Write-Err "Fallback save also failed: $($_.Exception.Message)"
729
- }
730
- }
731
-
732
- Write-Host ""
733
- Write-Info "Done. Total runtime: $($sw.Elapsed.ToString('mm\:ss\.ff'))"
734
- Write-Host ""
735
- Write-Header "DONE"