-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-ThreatIntelCheck.ps1
More file actions
998 lines (838 loc) · 35.4 KB
/
Invoke-ThreatIntelCheck.ps1
File metadata and controls
998 lines (838 loc) · 35.4 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
#Requires -Version 5.1
<#
.SYNOPSIS
Multi-Source Threat Intelligence Checker
.DESCRIPTION
Checks IP addresses, domains, URLs, and SHA256 file hashes against
multiple free threat intelligence sources.
Output is Splunk-friendly key=value pairs written to stdout, one event
per line, suitable for SIEM ingestion or file redirection.
All prompts and diagnostic messages are written to the host (stderr) so
the two streams never mix. Redirect stdout to a log file while status
messages continue to display in your terminal.
Supported sources:
VirusTotal v3 - IP, domain, URL, SHA256 (API key required)
AbuseIPDB v2 - IP (API key required)
URLScan.io - URL, domain (API key required)
Shodan InternetDB - IP (no key)
IPinfo.io - IP (no key, basic data)
GreyNoise Community - IP (no key)
CIRCL hashlookup - SHA256 (no key)
OS: dig / nslookup - Domain, URL (no key)
OS: whois - IP, domain (no key)
.PARAMETER Indicators
One or more indicators to check (IP, domain, URL, or SHA256 hash).
When calling from a Unix shell, use spaces only to separate indicators.
Example: pwsh script.ps1 -Indicators 1.2.3.4 evil.com
.PARAMETER File
Path to a file containing indicators, one per line.
Lines starting with '#' are treated as comments and skipped.
.PARAMETER Config
Path to the INI config file containing API keys.
Default: threat_intel.conf in the same directory as this script.
.PARAMETER Menu
Launch interactive menu-driven mode (default when no parameters are given).
.EXAMPLE
# Windows PowerShell / PowerShell 7
.\Invoke-ThreatIntelCheck.ps1 -Indicators 203.0.113.5
.\Invoke-ThreatIntelCheck.ps1 -Indicators 203.0.113.5 evil.example.com
.\Invoke-ThreatIntelCheck.ps1 -File .\iocs.txt
.\Invoke-ThreatIntelCheck.ps1 -File .\iocs.txt | Out-File events.log
.\Invoke-ThreatIntelCheck.ps1 -Menu
# Linux / FreeBSD (pwsh)
pwsh Invoke-ThreatIntelCheck.ps1 -Indicators 203.0.113.5
pwsh Invoke-ThreatIntelCheck.ps1 -Indicators 203.0.113.5 evil.example.com
pwsh Invoke-ThreatIntelCheck.ps1 -File iocs.txt
.NOTES
Author : Geoffrey Edmund Moraes
Version : 1.1.0
License : MIT
Requires: PowerShell 5.1+ (Windows PowerShell or PowerShell 7+)
Platform: Windows, Linux, FreeBSD (any platform running PowerShell 5.1+)
#>
[CmdletBinding(DefaultParameterSetName = 'Menu')]
param(
[Parameter(ParameterSetName = 'Direct', ValueFromRemainingArguments = $true)]
[string[]] $Indicators,
[Parameter(ParameterSetName = 'FromFile')]
[string] $File,
[Parameter(ParameterSetName = 'Menu')]
[switch] $Menu,
[string] $Config = (Join-Path $PSScriptRoot 'threat_intel.conf')
)
# StrictMode is intentionally limited to Version 1 here.
# Version Latest / Version 2 throws on any missing PSCustomObject property,
# which breaks every API response handler when optional fields are absent.
# Version 1 catches real issues (uninitialised variables, bad syntax) without
# the false positives that come from variable JSON response shapes.
Set-StrictMode -Version 1
$ErrorActionPreference = 'Continue'
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
$SCRIPT_VERSION = '1.1.0'
$SCRIPT_NAME = 'ThreatIntelChecker'
$HOSTNAME = [System.Net.Dns]::GetHostName()
$TIMEOUT_SEC = 15
$USER_AGENT = "ThreatIntelChecker/$SCRIPT_VERSION (SOC Automation Tool)"
# ---------------------------------------------------------------------------
# Core helpers
# ---------------------------------------------------------------------------
function Get-SafeProp {
<#
.SYNOPSIS
Safely retrieve a property value from any object without throwing.
Uses PSObject.Properties so it never touches a property that does not
exist, which would throw under StrictMode with PSCustomObjects.
#>
param(
$Object,
[string] $Property,
$Default = ''
)
if ($null -eq $Object) { return $Default }
$entry = $Object.PSObject.Properties[$Property]
if ($null -eq $entry) { return $Default }
$val = $entry.Value
if ($null -eq $val -or "$val" -eq '') { return $Default }
return $val
}
function Get-SafeInt {
<#
.SYNOPSIS
Safely retrieve an integer property, returning 0 when absent or null.
#>
param($Object, [string] $Property)
if ($null -eq $Object) { return 0 }
$entry = $Object.PSObject.Properties[$Property]
if ($null -eq $entry -or $null -eq $entry.Value) { return 0 }
return [int]$entry.Value
}
function Get-UtcTimestamp {
# Get-Date -AsUTC is PS 7+ only. [DateTime]::UtcNow works on PS 5.1+.
return [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
}
# ---------------------------------------------------------------------------
# Config loader
# ---------------------------------------------------------------------------
function Get-ThreatIntelConfig {
param([string] $ConfigPath)
$keys = @{
VT_API_KEY = ''
ABUSEIPDB_API_KEY = ''
URLSCAN_API_KEY = ''
}
if (Test-Path $ConfigPath) {
$inSection = $false
foreach ($line in (Get-Content $ConfigPath -ErrorAction SilentlyContinue)) {
$trimmed = $line.Trim()
if ($trimmed -eq '[API_KEYS]') { $inSection = $true; continue }
if ($trimmed -match '^\[') { $inSection = $false; continue }
if ($inSection -and $trimmed -match '^([^#=]+?)\s*=\s*(.*)$') {
$k = $Matches[1].Trim().ToUpper()
$v = $Matches[2].Trim()
if ($keys.ContainsKey($k)) { $keys[$k] = $v }
}
}
} else {
Write-Host "INFO: Config file '$ConfigPath' not found. Falling back to environment variables only." -ForegroundColor Yellow
}
foreach ($k in @($keys.Keys)) {
$envVal = [System.Environment]::GetEnvironmentVariable($k)
if ($envVal) { $keys[$k] = $envVal.Trim() }
}
return $keys
}
# ---------------------------------------------------------------------------
# Input validation
# ---------------------------------------------------------------------------
function Get-IndicatorType {
param([string] $Raw)
$value = $Raw.Trim().Trim(',')
if (-not $value) { return $null }
# SHA256 - check before domain to avoid misclassifying 64-char hex strings
if ($value -match '^[a-fA-F0-9]{64}$') {
return @{ Type = 'sha256'; Value = $value.ToLower() }
}
# URL
if ($value -match '^https?://\S+') {
try {
$uri = New-Object System.Uri($value)
if ($uri.Host) { return @{ Type = 'url'; Value = $value } }
} catch {}
return $null
}
# IPv4
if ($value -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') {
try {
$ip = [System.Net.IPAddress]::Parse($value)
$bytes = $ip.GetAddressBytes()
$priv = (
($bytes[0] -eq 10) -or
($bytes[0] -eq 127) -or
($bytes[0] -eq 169 -and $bytes[1] -eq 254) -or
($bytes[0] -eq 172 -and $bytes[1] -ge 16 -and $bytes[1] -le 31) -or
($bytes[0] -eq 192 -and $bytes[1] -eq 168) -or
($bytes[0] -eq 0) -or
($bytes[0] -eq 255)
)
if ($priv) { return @{ Type = 'ip_private'; Value = $value } }
return @{ Type = 'ip'; Value = $value }
} catch { return $null }
}
# IPv6
try {
$ip6 = [System.Net.IPAddress]::Parse($value)
if ($ip6.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
$s = $ip6.ToString()
$priv = ($s -match '^::1$' -or $s -match '^fe80:' -or
$s -match '^fc' -or $s -match '^fd')
if ($priv) { return @{ Type = 'ip_private'; Value = $value } }
return @{ Type = 'ip'; Value = $value }
}
} catch {}
# Domain
if ($value -match '^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$' `
-and $value -notmatch '\.\.') {
return @{ Type = 'domain'; Value = $value.ToLower() }
}
return $null
}
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
function Format-KVEvent {
param([System.Collections.Specialized.OrderedDictionary] $Fields)
$parts = foreach ($k in $Fields.Keys) {
$v = [string]$Fields[$k]
if ($v -match '[ =",'']') {
$v = '"' + $v.Replace('\', '\\').Replace('"', '\"') + '"'
}
if ($v -eq '') { $v = '""' }
"$k=$v"
}
return ($parts -join ' ')
}
function Emit-Event {
param(
[string] $IndicatorType,
[string] $Indicator,
[string] $Source,
[hashtable] $Fields,
[string] $Verdict = 'unknown'
)
$base = [ordered]@{
timestamp = (Get-UtcTimestamp)
host = $HOSTNAME
app = $SCRIPT_NAME
version = $SCRIPT_VERSION
indicator_type = $IndicatorType
indicator = $Indicator
source = $Source
verdict = $Verdict
}
foreach ($k in $Fields.Keys) { $base[$k] = $Fields[$k] }
[Console]::Out.WriteLine((Format-KVEvent -Fields $base))
}
function Emit-Error {
param([string] $IndicatorType, [string] $Indicator, [string] $Source, [string] $ErrorMsg)
Emit-Event -IndicatorType $IndicatorType -Indicator $Indicator -Source $Source `
-Fields @{ error = $ErrorMsg } -Verdict 'error'
}
# ---------------------------------------------------------------------------
# HTTP helper
# ---------------------------------------------------------------------------
function Invoke-TIRequest {
param(
[string] $Uri,
[string] $Method = 'GET',
[hashtable] $Headers = @{},
[hashtable] $Body = @{},
[hashtable] $Query = @{},
[bool] $FormBody = $false
)
if ($Query.Count -gt 0) {
$qs = ($Query.Keys | ForEach-Object { "$_=$([Uri]::EscapeDataString($Query[$_]))" }) -join '&'
$Uri = "${Uri}?${qs}"
}
$Headers['User-Agent'] = $USER_AGENT
$irm = @{
Uri = $Uri
Method = $Method
Headers = $Headers
TimeoutSec = $TIMEOUT_SEC
ErrorAction = 'Stop'
}
if ($Method -in 'POST', 'PUT') {
if ($FormBody) {
$irm.Body = $Body
$irm.ContentType = 'application/x-www-form-urlencoded'
} else {
$irm.Body = ($Body | ConvertTo-Json -Compress)
$irm.ContentType = 'application/json'
}
}
try {
return Invoke-RestMethod @irm
} catch {
return $null
}
}
# ---------------------------------------------------------------------------
# OS-level enrichment (no API key required)
# ---------------------------------------------------------------------------
function Invoke-OsDnsLookup {
param([string] $Target)
$fields = @{}
if (Get-Command dig -ErrorAction SilentlyContinue) {
$out = & dig +short $Target A 2>$null
if (-not $out) { $out = & dig +short -x $Target 2>$null }
if ($out) {
$resolved = ($out -split "`n" | Where-Object { $_.Trim() } | Select-Object -First 10)
$fields['dns_resolved'] = ($resolved -join ',')
return $fields
}
}
if (Get-Command nslookup -ErrorAction SilentlyContinue) {
$out = (& nslookup $Target 2>$null) | Out-String
$m = [regex]::Match($out, 'Address(?:es)?:\s*(.+)')
if ($m.Success) { $fields['dns_resolved'] = $m.Groups[1].Value.Trim() }
}
return $fields
}
function Invoke-OsWhois {
param([string] $Indicator)
$fields = @{}
if (-not (Get-Command whois -ErrorAction SilentlyContinue)) { return $fields }
try { $out = (& whois $Indicator 2>$null) | Out-String }
catch { return $fields }
$patterns = @{
whois_registrar = 'Registrar:\s*(.+)'
whois_created = '(?:Creation Date|Created(?:\s+On)?|Registered):\s*(.+)'
whois_expires = '(?:Registry Expiry Date|Expir(?:ation|es|y) Date?):\s*(.+)'
whois_country = '(?m)^country:\s*(.+)'
whois_org = '(?:org-name|OrgName|Organisation|Organization):\s*(.+)'
whois_netname = '(?m)^netname:\s*(.+)'
whois_cidr = '(?:CIDR|inetnum|NetRange):\s*(.+)'
}
foreach ($field in $patterns.Keys) {
$m = [regex]::Match($out, $patterns[$field],
[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($m.Success) {
$v = $m.Groups[1].Value.Trim()
if ($v.Length -gt 120) { $v = $v.Substring(0, 120) }
$fields[$field] = $v
}
}
return $fields
}
# ---------------------------------------------------------------------------
# API: VirusTotal v3
# ---------------------------------------------------------------------------
function Get-VTVerdict {
param([int] $Malicious, [int] $Suspicious, [int] $Harmless, [int] $Undetected)
if ($Malicious -gt 0) { return 'malicious' }
if ($Suspicious -gt 0) { return 'suspicious' }
if (($Harmless + $Undetected) -gt 0) { return 'clean' }
return 'unknown'
}
function Invoke-VTIpCheck {
param([string] $Ip, [string] $ApiKey)
if (-not $ApiKey) { return }
$resp = Invoke-TIRequest -Uri "https://www.virustotal.com/api/v3/ip_addresses/$Ip" `
-Headers @{ 'x-apikey' = $ApiKey }
if (-not $resp) { Emit-Error 'ip' $Ip 'virustotal' 'request_failed'; return }
$attrs = Get-SafeProp $resp.data 'attributes'
$las = Get-SafeProp $attrs 'last_analysis_stats'
$mal = Get-SafeInt $las 'malicious'
$sus = Get-SafeInt $las 'suspicious'
$har = Get-SafeInt $las 'harmless'
$und = Get-SafeInt $las 'undetected'
Emit-Event 'ip' $Ip 'virustotal' @{
vt_malicious = $mal
vt_suspicious = $sus
vt_harmless = $har
vt_undetected = $und
vt_country = (Get-SafeProp $attrs 'country')
vt_asn = (Get-SafeProp $attrs 'asn')
vt_as_owner = (Get-SafeProp $attrs 'as_owner')
vt_reputation = (Get-SafeProp $attrs 'reputation')
} (Get-VTVerdict $mal $sus $har $und)
}
function Invoke-VTDomainCheck {
param([string] $Domain, [string] $ApiKey)
if (-not $ApiKey) { return }
$resp = Invoke-TIRequest -Uri "https://www.virustotal.com/api/v3/domains/$Domain" `
-Headers @{ 'x-apikey' = $ApiKey }
if (-not $resp) { Emit-Error 'domain' $Domain 'virustotal' 'request_failed'; return }
$attrs = Get-SafeProp $resp.data 'attributes'
$las = Get-SafeProp $attrs 'last_analysis_stats'
$mal = Get-SafeInt $las 'malicious'
$sus = Get-SafeInt $las 'suspicious'
$har = Get-SafeInt $las 'harmless'
$und = Get-SafeInt $las 'undetected'
# categories is a nested object whose values are the category strings
$cats = ''
$catsObj = Get-SafeProp $attrs 'categories'
if ($null -ne $catsObj -and $catsObj -is [PSCustomObject]) {
$catVals = $catsObj.PSObject.Properties | Select-Object -First 5 | ForEach-Object { $_.Value }
$cats = ($catVals -join ',')
}
Emit-Event 'domain' $Domain 'virustotal' @{
vt_malicious = $mal
vt_suspicious = $sus
vt_harmless = $har
vt_undetected = $und
vt_reputation = (Get-SafeProp $attrs 'reputation')
vt_categories = $cats
vt_registrar = (Get-SafeProp $attrs 'registrar')
vt_creation_date = (Get-SafeProp $attrs 'creation_date')
} (Get-VTVerdict $mal $sus $har $und)
}
function Invoke-VTUrlCheck {
param([string] $Url, [string] $ApiKey)
if (-not $ApiKey) { return }
$bytes = [System.Text.Encoding]::UTF8.GetBytes($Url)
$urlId = [System.Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=')
$resp = Invoke-TIRequest -Uri "https://www.virustotal.com/api/v3/urls/$urlId" `
-Headers @{ 'x-apikey' = $ApiKey }
if (-not $resp) { Emit-Error 'url' $Url 'virustotal' 'request_failed'; return }
$attrs = Get-SafeProp $resp.data 'attributes'
$las = Get-SafeProp $attrs 'last_analysis_stats'
$mal = Get-SafeInt $las 'malicious'
$sus = Get-SafeInt $las 'suspicious'
$har = Get-SafeInt $las 'harmless'
$und = Get-SafeInt $las 'undetected'
$finalUrl = [string](Get-SafeProp $attrs 'last_final_url')
$title = [string](Get-SafeProp $attrs 'title')
if ($finalUrl.Length -gt 200) { $finalUrl = $finalUrl.Substring(0, 200) }
if ($title.Length -gt 100) { $title = $title.Substring(0, 100) }
Emit-Event 'url' $Url 'virustotal' @{
vt_malicious = $mal
vt_suspicious = $sus
vt_harmless = $har
vt_undetected = $und
vt_final_url = $finalUrl
vt_title = $title
} (Get-VTVerdict $mal $sus $har $und)
}
function Invoke-VTHashCheck {
param([string] $Hash, [string] $ApiKey)
if (-not $ApiKey) { return }
$resp = Invoke-TIRequest -Uri "https://www.virustotal.com/api/v3/files/$Hash" `
-Headers @{ 'x-apikey' = $ApiKey }
if (-not $resp) { Emit-Error 'sha256' $Hash 'virustotal' 'request_failed'; return }
$attrs = Get-SafeProp $resp.data 'attributes'
$las = Get-SafeProp $attrs 'last_analysis_stats'
$mal = Get-SafeInt $las 'malicious'
$sus = Get-SafeInt $las 'suspicious'
$har = Get-SafeInt $las 'harmless'
$und = Get-SafeInt $las 'undetected'
$names = ''
$namesVal = Get-SafeProp $attrs 'names'
if ($null -ne $namesVal) { $names = ($namesVal | Select-Object -First 3) -join ',' }
Emit-Event 'sha256' $Hash 'virustotal' @{
vt_malicious = $mal
vt_suspicious = $sus
vt_harmless = $har
vt_undetected = $und
vt_file_type = (Get-SafeProp $attrs 'type_description')
vt_file_name = $names
vt_file_size = (Get-SafeProp $attrs 'size')
vt_meaningful_name = (Get-SafeProp $attrs 'meaningful_name')
vt_first_seen = (Get-SafeProp $attrs 'first_submission_date')
vt_last_seen = (Get-SafeProp $attrs 'last_analysis_date')
} (Get-VTVerdict $mal $sus $har $und)
}
# ---------------------------------------------------------------------------
# API: AbuseIPDB v2
# ---------------------------------------------------------------------------
function Invoke-AbuseIPDBCheck {
param([string] $Ip, [string] $ApiKey)
if (-not $ApiKey) { return }
$resp = Invoke-TIRequest `
-Uri 'https://api.abuseipdb.com/api/v2/check' `
-Headers @{ 'Key' = $ApiKey; 'Accept' = 'application/json' } `
-Query @{ ipAddress = $Ip; maxAgeInDays = '90' }
if (-not $resp) { Emit-Error 'ip' $Ip 'abuseipdb' 'request_failed'; return }
$d = Get-SafeProp $resp 'data'
$score = Get-SafeInt $d 'abuseConfidenceScore'
$verdict = 'clean'
if ($score -ge 75) { $verdict = 'malicious' }
elseif ($score -ge 25) { $verdict = 'suspicious' }
$isp = [string](Get-SafeProp $d 'isp')
if ($isp.Length -gt 100) { $isp = $isp.Substring(0, 100) }
Emit-Event 'ip' $Ip 'abuseipdb' @{
abuseipdb_score = $score
abuseipdb_total_reports = (Get-SafeInt $d 'totalReports')
abuseipdb_num_distinct_users = (Get-SafeInt $d 'numDistinctUsers')
abuseipdb_country = (Get-SafeProp $d 'countryCode')
abuseipdb_isp = $isp
abuseipdb_usage_type = (Get-SafeProp $d 'usageType')
abuseipdb_domain = (Get-SafeProp $d 'domain')
abuseipdb_is_tor = (Get-SafeProp $d 'isTor' $false)
abuseipdb_last_reported = (Get-SafeProp $d 'lastReportedAt')
} $verdict
}
# ---------------------------------------------------------------------------
# API: Shodan InternetDB (no key)
# ---------------------------------------------------------------------------
function Invoke-ShodanInternetDBCheck {
param([string] $Ip)
$resp = Invoke-TIRequest -Uri "https://internetdb.shodan.io/$Ip"
if (-not $resp) { Emit-Error 'ip' $Ip 'shodan_internetdb' 'request_failed'; return }
# 404 responses include a 'detail' field; use Get-SafeProp so strict mode
# does not throw when 'detail' is absent on a normal 200 response
$detail = Get-SafeProp $resp 'detail'
if ($detail) {
Emit-Event 'ip' $Ip 'shodan_internetdb' @{ result = 'not_found' } 'unknown'
return
}
$vulns = @()
$ports = @()
$hosts = @()
$cpes = @()
$tags = @()
$vulnsVal = Get-SafeProp $resp 'vulns'
$portsVal = Get-SafeProp $resp 'ports'
$hostsVal = Get-SafeProp $resp 'hostnames'
$cpesVal = Get-SafeProp $resp 'cpes'
$tagsVal = Get-SafeProp $resp 'tags'
if ($null -ne $vulnsVal) { $vulns = @($vulnsVal) }
if ($null -ne $portsVal) { $ports = @($portsVal) }
if ($null -ne $hostsVal) { $hosts = @($hostsVal) }
if ($null -ne $cpesVal) { $cpes = @($cpesVal) }
if ($null -ne $tagsVal) { $tags = @($tagsVal) }
$verdict = 'clean'
if ($vulns.Count -gt 0) { $verdict = 'suspicious' }
Emit-Event 'ip' $Ip 'shodan_internetdb' @{
shodan_open_ports = (($ports | Select-Object -First 20) -join ',')
shodan_hostnames = (($hosts | Select-Object -First 5) -join ',')
shodan_vulns = (($vulns | Select-Object -First 10) -join ',')
shodan_cpes = (($cpes | Select-Object -First 5) -join ',')
shodan_tags = ($tags -join ',')
} $verdict
}
# ---------------------------------------------------------------------------
# API: IPinfo.io (no key for basic data)
# ---------------------------------------------------------------------------
function Invoke-IPinfoCheck {
param([string] $Ip)
$resp = Invoke-TIRequest -Uri "https://ipinfo.io/$Ip/json"
if (-not $resp) { Emit-Error 'ip' $Ip 'ipinfo' 'request_failed'; return }
$org = [string](Get-SafeProp $resp 'org')
if ($org.Length -gt 100) { $org = $org.Substring(0, 100) }
Emit-Event 'ip' $Ip 'ipinfo' @{
ipinfo_org = $org
ipinfo_country = (Get-SafeProp $resp 'country')
ipinfo_region = (Get-SafeProp $resp 'region')
ipinfo_city = (Get-SafeProp $resp 'city')
ipinfo_timezone = (Get-SafeProp $resp 'timezone')
ipinfo_hostname = (Get-SafeProp $resp 'hostname')
ipinfo_bogon = (Get-SafeProp $resp 'bogon' $false)
} 'unknown'
}
# ---------------------------------------------------------------------------
# API: GreyNoise Community (no key)
# ---------------------------------------------------------------------------
function Invoke-GreyNoiseCheck {
param([string] $Ip)
$resp = Invoke-TIRequest -Uri "https://api.greynoise.io/v3/community/$Ip"
if (-not $resp) { Emit-Error 'ip' $Ip 'greynoise' 'request_failed'; return }
$classification = [string](Get-SafeProp $resp 'classification' 'unknown')
$noise = (Get-SafeProp $resp 'noise' $false)
$riot = (Get-SafeProp $resp 'riot' $false)
$name = [string](Get-SafeProp $resp 'name')
$lastSeen = [string](Get-SafeProp $resp 'last_seen')
$message = [string](Get-SafeProp $resp 'message')
if ($name.Length -gt 100) { $name = $name.Substring(0, 100) }
if ($message.Length -gt 200) { $message = $message.Substring(0, 200) }
# IP not observed by GreyNoise: response has only a message field
if ($classification -eq 'unknown' -and -not $noise -and -not $riot -and $message) {
Emit-Event 'ip' $Ip 'greynoise' @{
result = 'not_observed'
gn_message = $message
} 'unknown'
return
}
$verdict = 'unknown'
if ($classification -eq 'malicious') { $verdict = 'malicious' }
elseif ($classification -eq 'benign') { $verdict = 'clean' }
elseif ($noise -and -not $riot) { $verdict = 'suspicious' }
Emit-Event 'ip' $Ip 'greynoise' @{
gn_noise = $noise
gn_riot = $riot
gn_classification = $classification
gn_name = $name
gn_last_seen = $lastSeen
gn_message = $message
} $verdict
}
# ---------------------------------------------------------------------------
# API: CIRCL hashlookup (no key) - NIST NSRL-backed clean-file database
# ---------------------------------------------------------------------------
function Invoke-CIRCLHashlookupCheck {
param([string] $Hash)
$resp = Invoke-TIRequest -Uri "https://hashlookup.circl.lu/lookup/sha256/$Hash"
if (-not $resp) {
# Invoke-RestMethod returns $null on 404; this is expected for unknown hashes
Emit-Event 'sha256' $Hash 'circl_hashlookup' @{
result = 'not_in_known_clean_db'
note = 'not_catalogued_as_clean_software'
} 'unknown'
return
}
$fileName = [string](Get-SafeProp $resp 'FileName')
if ($fileName.Length -gt 200) { $fileName = $fileName.Substring(0, 200) }
Emit-Event 'sha256' $Hash 'circl_hashlookup' @{
circl_file_name = $fileName
circl_file_size = (Get-SafeProp $resp 'FileSize')
circl_product = (Get-SafeProp $resp 'ProductCode')
circl_os = (Get-SafeProp $resp 'OpSystemCode')
circl_known_clean = 'true'
} 'clean'
}
# ---------------------------------------------------------------------------
# API: URLScan.io (key required)
# ---------------------------------------------------------------------------
function Invoke-URLScanCheck {
param([string] $Indicator, [string] $IocType, [string] $ApiKey)
if (-not $ApiKey) { return }
$query = 'page.url:' + $Indicator
if ($IocType -eq 'domain') { $query = 'domain:' + $Indicator }
$resp = Invoke-TIRequest `
-Uri 'https://urlscan.io/api/v1/search/' `
-Headers @{ 'API-Key' = $ApiKey } `
-Query @{ q = $query; size = '1' }
if (-not $resp) { Emit-Error $IocType $Indicator 'urlscan' 'request_failed'; return }
$resultsVal = Get-SafeProp $resp 'results'
$results = @()
if ($null -ne $resultsVal) { $results = @($resultsVal) }
if ($results.Count -eq 0) {
Emit-Event $IocType $Indicator 'urlscan' @{ result = 'not_found' } 'unknown'
return
}
$entry = $results[0]
$page = Get-SafeProp $entry 'page'
$verdObj = Get-SafeProp $entry 'verdicts'
$overall = $null
if ($null -ne $verdObj) { $overall = Get-SafeProp $verdObj 'overall' }
$score = Get-SafeInt $overall 'score'
$malicious = $false
$cats = @()
if ($null -ne $overall) {
$malBool = Get-SafeProp $overall 'malicious' $false
if ($malBool) { $malicious = $true }
$catsVal = Get-SafeProp $overall 'categories'
if ($null -ne $catsVal) { $cats = @($catsVal) }
}
$verdict = 'clean'
if ($malicious) { $verdict = 'malicious' }
elseif ($score -gt 50) { $verdict = 'suspicious' }
$pageCountry = ''
$pageServer = ''
$pageIp = ''
$pageTitle = ''
if ($null -ne $page) {
$pageCountry = [string](Get-SafeProp $page 'country')
$pageServer = [string](Get-SafeProp $page 'server')
$pageIp = [string](Get-SafeProp $page 'ip')
$pageTitle = [string](Get-SafeProp $page 'title')
}
if ($pageServer.Length -gt 100) { $pageServer = $pageServer.Substring(0, 100) }
if ($pageTitle.Length -gt 100) { $pageTitle = $pageTitle.Substring(0, 100) }
Emit-Event $IocType $Indicator 'urlscan' @{
urlscan_score = $score
urlscan_malicious = $malicious
urlscan_categories = ($cats -join ',')
urlscan_country = $pageCountry
urlscan_server = $pageServer
urlscan_ip = $pageIp
urlscan_title = $pageTitle
urlscan_scan_id = (Get-SafeProp $entry '_id')
} $verdict
}
# ---------------------------------------------------------------------------
# Orchestration
# ---------------------------------------------------------------------------
function Invoke-IndicatorCheck {
param(
[string] $Indicator,
[string] $IocType,
[hashtable] $ApiKeys
)
$vtKey = $ApiKeys.VT_API_KEY
$abuseKey = $ApiKeys.ABUSEIPDB_API_KEY
$urlscanKey = $ApiKeys.URLSCAN_API_KEY
switch ($IocType) {
'ip' {
$dns = Invoke-OsDnsLookup $Indicator
if ($dns.Count -gt 0) { Emit-Event 'ip' $Indicator 'os_dns' $dns 'unknown' }
$wh = Invoke-OsWhois $Indicator
if ($wh.Count -gt 0) { Emit-Event 'ip' $Indicator 'os_whois' $wh 'unknown' }
Invoke-VTIpCheck $Indicator $vtKey
Invoke-AbuseIPDBCheck $Indicator $abuseKey
Invoke-ShodanInternetDBCheck $Indicator
Invoke-IPinfoCheck $Indicator
Invoke-GreyNoiseCheck $Indicator
}
'domain' {
$dns = Invoke-OsDnsLookup $Indicator
if ($dns.Count -gt 0) { Emit-Event 'domain' $Indicator 'os_dns' $dns 'unknown' }
$wh = Invoke-OsWhois $Indicator
if ($wh.Count -gt 0) { Emit-Event 'domain' $Indicator 'os_whois' $wh 'unknown' }
Invoke-VTDomainCheck $Indicator $vtKey
Invoke-URLScanCheck $Indicator 'domain' $urlscanKey
}
'url' {
try {
$uri = New-Object System.Uri($Indicator)
$domain = $uri.Host
if ($domain) {
$dns = Invoke-OsDnsLookup $domain
if ($dns.Count -gt 0) { Emit-Event 'url' $Indicator 'os_dns' $dns 'unknown' }
}
} catch {}
Invoke-VTUrlCheck $Indicator $vtKey
Invoke-URLScanCheck $Indicator 'url' $urlscanKey
}
'sha256' {
Invoke-VTHashCheck $Indicator $vtKey
Invoke-CIRCLHashlookupCheck $Indicator
}
}
}
function Invoke-CheckBatch {
param(
[string[]] $RawIndicators,
[hashtable] $ApiKeys
)
$tasks = [System.Collections.Generic.List[hashtable]]::new()
foreach ($raw in $RawIndicators) {
# Strip stray commas that appear when calling from a Unix shell with
# comma-separated arguments: pwsh script.ps1 -Indicators a, b
# The shell passes 'a,' as one token and 'b' as another.
$cleaned = $raw.Trim().Trim(',')
if (-not $cleaned) { continue }
$result = Get-IndicatorType $cleaned
if (-not $result) {
Emit-Event 'unknown' $cleaned 'validation' @{ error = 'unrecognized_or_malformed_indicator' } 'error'
continue
}
if ($result.Type -eq 'ip_private') {
Emit-Event 'ip_private' $cleaned 'validation' @{ note = 'private_reserved_or_loopback_address_skipped' } 'skip'
continue
}
$tasks.Add(@{ Indicator = $result.Value; IocType = $result.Type })
}
foreach ($task in $tasks) {
try {
Invoke-IndicatorCheck -Indicator $task.Indicator -IocType $task.IocType -ApiKeys $ApiKeys
} catch {
Write-Host "ERROR processing $($task.Indicator): $_" -ForegroundColor Red
}
}
}
# ---------------------------------------------------------------------------
# Interactive menu
# ---------------------------------------------------------------------------
function Show-ApiKeyStatus {
param([hashtable] $ApiKeys)
Write-Host "`nAPI Key Status:" -ForegroundColor Cyan
foreach ($k in $ApiKeys.Keys) {
if ($ApiKeys[$k]) {
Write-Host " ${k}: loaded" -ForegroundColor Green
} else {
Write-Host " ${k}: MISSING (checks using this key will be skipped)" -ForegroundColor Yellow
}
}
}
function Start-InteractiveMenu {
param([hashtable] $ApiKeys)
Write-Host @"
============================================================
$SCRIPT_NAME v$SCRIPT_VERSION
Multi-Source Threat Intelligence Checker
Output: Splunk key=value (stdout)
============================================================
"@ -ForegroundColor Cyan
while ($true) {
Write-Host @"
Options:
[1] Check a single indicator
[2] Check multiple indicators (space or comma separated)
[3] Check indicators from a file (one per line)
[4] Show API key status
[0] Exit
"@ -ForegroundColor White
$choice = Read-Host "`nSelect option"
switch ($choice.Trim()) {
'0' {
Write-Host "Exiting." -ForegroundColor Cyan
return
}
'1' {
$raw = Read-Host "Enter indicator (IP, domain, URL, or SHA256 hash)"
if ($raw.Trim()) {
Invoke-CheckBatch -RawIndicators @($raw.Trim()) -ApiKeys $ApiKeys
}
}
'2' {
$raw = Read-Host "Enter indicators (space or comma separated)"
$indicators = ($raw -split '[,\s]+') |
Where-Object { $_.Trim() } |
ForEach-Object { $_.Trim() }
if ($indicators) {
Invoke-CheckBatch -RawIndicators $indicators -ApiKeys $ApiKeys
}
}
'3' {
$path = (Read-Host "Enter path to indicator file").Trim()
if (Test-Path $path) {
$lines = Get-Content $path |
Where-Object { $_.Trim() -and -not $_.TrimStart().StartsWith('#') } |
ForEach-Object { $_.Trim() }
if ($lines) {
Invoke-CheckBatch -RawIndicators $lines -ApiKeys $ApiKeys
}
} else {
Write-Host "ERROR: File not found: $path" -ForegroundColor Red
}
}
'4' {
Show-ApiKeyStatus $ApiKeys
}
default {
Write-Host "Invalid option. Please enter 0, 1, 2, 3, or 4." -ForegroundColor Yellow
}
}
}
}
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
$apiKeys = Get-ThreatIntelConfig -ConfigPath $Config
switch ($PSCmdlet.ParameterSetName) {
'Direct' {
if ($Indicators -and $Indicators.Count -gt 0) {
Invoke-CheckBatch -RawIndicators $Indicators -ApiKeys $apiKeys
} else {
Start-InteractiveMenu -ApiKeys $apiKeys
}
}
'FromFile' {
if (-not (Test-Path $File)) {
Write-Host "ERROR: File not found: $File" -ForegroundColor Red
exit 1
}
$lines = Get-Content $File |
Where-Object { $_.Trim() -and -not $_.TrimStart().StartsWith('#') } |
ForEach-Object { $_.Trim() }
if ($lines) {
Invoke-CheckBatch -RawIndicators $lines -ApiKeys $apiKeys
}
}
'Menu' {
Start-InteractiveMenu -ApiKeys $apiKeys
}
}