forked from ArtezzaIT/Sharkphin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHarborSec.ps1
More file actions
538 lines (499 loc) · 23.9 KB
/
Copy pathHarborSec.ps1
File metadata and controls
538 lines (499 loc) · 23.9 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
# Aretzza Sharkphin - Phishing Response Tool
# Copyright (C) 2026 Benjamin Jaros
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#Function definitions
# Function to validate email address format
function Test-EmailAddress {
param (
[string]$Email
)
try {
$null = [System.Net.Mail.MailAddress]::new($Email)
return $true
}
catch {
return $false
}
}
# Function to validate DNS names
function Test-IsValidDnsName {
param([string]$name)
# Use the DnsName type to validate the syntax
$isValidSyntax = [System.Uri]::CheckHostName($name)
if ($isValidSyntax -in @('Dns', 'FullyQualified', 'Simple') -and $name -like '*.*') {
return $true
} else {
return $false
}
}
#Create new search in 365
function New-CustomSearch {
param (
[string]$ContentSearchName,
[string]$InputPhishSenderName,
[string]$InputPhishSubject
)
#make "" into '' because KQL is weird
$InputPhishSubject = $InputPhishSubject.Replace('"', "'")
#Escape quotes for KQL query string
$InputPhishSubject = $InputPhishSubject.Replace("'","''")
#If a subject was provided, use it in the search query. If not, search for any subject.
if ($InputPhishSubject) {
$InputMatchQuery="(From:"+$InputPhishSenderName+") AND (Subject:`""+$InputPhishSubject+"`")"
} else {
$InputMatchQuery="(From:"+$InputPhishSenderName+")"
}
Write-Host "Building search $ContentSearchName..."
#Create a Content Search to find the message
try{
$Search=New-ComplianceSearch -Name $ContentSearchName -ExchangeLocation All -ContentMatchQuery $InputMatchQuery
} catch {
#If the search fails, cut back to the main menu.
Write-Host "There was an error creating the content search in 365. The search query generated was:"
Write-Host $InputMatchQuery
Write-Host "Please consider reporting an issue at https://github.com/ArtezzaIT/Sharkphin/issues"
return "There was an error creating the content search in 365. The search query generated was: $InputMatchQuery"
}
#Start Content Search
Start-ComplianceSearch -Identity $Search.Identity
#ADD running search message
Write-Host "Content Search is running. Please check the Sharkphin or Purview portal for status."
return "The content search ##SEARCHNAME## was successfully submitted as ##UPN##. Please check the Sharkphin or Purview portal for status."
}
# Function to parse query string into a hashtable
function Parse-QueryString {
param (
[string]$queryString
)
$queryParams = @{}
if ($queryString) {
$queryString -split "&" | ForEach-Object {
$paramParts = $_ -split "="
$queryParams[$paramParts[0]] = [System.Web.HttpUtility]::UrlDecode($paramParts[1])
}
}
return $queryParams
}
#Program initialization
$version = "0.7.0"
$channel = "stable"
write-host " ______ ______ ______ ______ ______ ______ ______ "
write-host " /\ __ \ /\ == \ /\__ _\ /\ ___\ /\___ \ /\___ \ /\ __ \ "
write-host " \ \ __ \ \ \ __< \/_/\ \/ \ \ __\ \/_/ /__ \/_/ /__ \ \ __ \ "
write-host " \ \_\ \_\ \ \_\ \_\ \ \_\ \ \_____\ /\_____\ /\_____\ \ \_\ \_\ "
write-host " \/_/\/_/ \/_/ /_/ \/_/ \/_____/ \/_____/ \/_____/ \/_/\/_/ "
write-host " "
write-host " ______ __ __ ______ ______ __ __ ______ __ __ __ __ __ "
write-host "/\ ___\ /\ \_\ \ /\ __ \ /\ == \ /\ \/ / /\ == \ /\ \_\ \ /\ \ /\ `"-.\ \ "
write-host "\ \___ \ \ \ __ \ \ \ __ \ \ \ __< \ \ _`"-. \ \ _-/ \ \ __ \ \ \ \ \ \ \-. \ "
write-host " \/\_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\ \ \_\ \_\ \ \_\ \ \_\\`"\_\ "
write-host " \/_____/ \/_/\/_/ \/_/\/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/\/_/ \/_/ \/_/ \/_/ "
write-host " "
Write-Host "Version $version, $channel channel"
#Check platform. These are built-in variables in PS 6+. Below PS6 we assume Windows only.
if ($PSVersionTable.PSVersion.Major -lt 6) {
# Code to run if PowerShell version is below 6
Write-Host "Running on PowerShell version below 6"
$IsWindows = $true
$IsMacOS = $false
$IsLinux = $false
}
#Check if running the latest/recommended version
try {
$availableonline = (Invoke-WebRequest -uri https://sharkphin.artezza.io/latest.json -usebasicparsing).content | ConvertFrom-Json
if ($availableonline.$channel[0] -ne $version){
Write-host "You are not running the recommended version for the $channel channel!"
$updatechoice = Read-Host "Would you like to download the recommended verion? (y/N)"
if ($updatechoice.ToLower() -eq "y"){
$downloadlnk = $availableonline.$channel[1]
if ($IsWindows) {
Start-Process $downloadlnk
} elseif ($IsMacOS) {
Start-Process "open" -ArgumentList $downloadlnk
} elseif ($IsLinux) {
Start-Process "xdg-open" -ArgumentList $downloadlnk
}
exit
}
} else {
Write-Host "This version is up to date! You're running $version, $channel"
}
}
catch {
Write-Host "There was an error checking for updates. You can always check for new versions at https://sharkphin.artezza.io"
}
#Setup dependancies
Write-Host "Setting up modules..."
try {
#Install EXO module if missing
Install-Module -Name ExchangeOnlineManagement
#Update to latest version
Update-Module -Name ExchangeOnlineManagement
}
catch {
Write-Output "An error occurred installing or updating the Exchange Online module. Usually this can be resolved by launching the program as administrator."
Write-Output "Attempting to continue without updating..."
}
#Connect to Security & Compliance PowerShell, then Exchange Online
Write-Host "Connecting to 365..."
try{
Import-Module ExchangeOnlineManagement
Connect-IPPSSession -EnableSearchOnlySession -ShowBanner:$false
$UPN = (Get-ConnectionInformation).UserPrincipalName
Connect-ExchangeOnline -ShowBanner:$false -UserPrincipalName $UPN
}
catch {
Write-Host "There was an error signing into the 365 tenant. Please verify the credentials you are using are correct and that the Exchange Online Module is installed (running as admin may fix this problem)."
Read-Host "Press enter to close."
Disconnect-ExchangeOnline -Confirm:$false
exit
}
#Server setup
Write-Host "Starting server..."
$port = 8080
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $port)
$listener.Start()
$portal = "http://localhost:$port/"
Write-Host "Server running on $portal/"
if ($IsWindows) {
Start-Process $portal
} elseif ($IsMacOS) {
Start-Process "open" -ArgumentList $portal
} elseif ($IsLinux) {
Start-Process "xdg-open" -ArgumentList $portal
}
#Request loop
$activeSession = $true
while ($activeSession) {
#Accept request
$client = $listener.AcceptTcpClient()
$stream = $client.GetStream()
$reader = New-Object System.IO.StreamReader($stream)
$request = $reader.ReadLine()
Write-Host "Received request: $request"
# Parse the request to get the requested page and query parameters
$pageRequest = $request -split " " | Select-Object -Index 1
$pageRequestParts = $pageRequest -split "\?"
$pagePath = $pageRequestParts[0]
$queryString = if ($pageRequestParts.Count -gt 1) { $pageRequestParts[1] } else { "" }
$queryParams = Parse-QueryString -queryString $queryString
Write-Host $queryParams
switch ($pagePath) {
#Sharkphin URLs
"/" {
# Default page, do nothing special
$htmlFilePath = "$PSScriptRoot\app.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$htmlContent = $htmlContent -replace "##UPN##", $UPN
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
"/favicon.ico" {
# Handle favicon request
$faviconPath = "$PSScriptRoot/favicon.ico"
$faviconContent = [System.IO.File]::ReadAllBytes($faviconPath)
$response = "HTTP/1.1 200 OK`r`nContent-Type: image/x-icon`r`n`r`n"
$buffer = [System.Text.Encoding]::ASCII.GetBytes($response) + $faviconContent
}
"/background.jpg" {
# Handle background request
$backgroundPath = "$PSScriptRoot/background.jpg"
$backgroundContent = [System.IO.File]::ReadAllBytes($backgroundPath)
$response = "HTTP/1.1 200 OK`r`nContent-Type: image/jpg`r`n`r`n"
$buffer = [System.Text.Encoding]::ASCII.GetBytes($response) + $backgroundContent
}
"/logout" {
# Handle logout page request
Write-Host "Handling logout request"
$htmlFilePath = "$PSScriptRoot\logout.html"
$activeSession = $false
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
"/search" {
# Handle search page request
Write-Host "Handling search request"
# Extract search query parameters
$searchName = $queryParams["name"]
$phishSenderName = $queryParams["sender"]
$phishSubject = $queryParams["subject"]
# Perform search operation
if ($searchName -and $phishSenderName -and $phishSubject) {
$resultMessage = New-CustomSearch -ContentSearchName $searchName -InputPhishSenderName $phishSenderName -InputPhishSubject $phishSubject
$htmlFilePath = "$PSScriptRoot\search.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$htmlContent = $htmlContent -replace "##RESULTMESSAGE##", $resultMessage
$htmlContent = $htmlContent -replace "##UPN##", $UPN
$htmlContent = $htmlContent -replace "##SEARCHNAME##", $searchName
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} elseif ($searchName -and $phishSenderName) {
$resultMessage = New-CustomSearch -ContentSearchName $searchName -InputPhishSenderName $phishSenderName
$htmlFilePath = "$PSScriptRoot\search.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$htmlContent = $htmlContent -replace "##RESULTMESSAGE##", $resultMessage
$htmlContent = $htmlContent -replace "##UPN##", $UPN
$htmlContent = $htmlContent -replace "##SEARCHNAME##", $searchName
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} else {
$htmlFilePath = "$PSScriptRoot\400.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 400 Bad Request`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
"/searchstatus" {
# Return JSON string of compliance search information
Write-Host "Handling search status request"
$searches = @()
$availableSearches = Get-ComplianceSearch
foreach ($search in $availableSearches){
$searchData = Get-ComplianceSearch -Identity $search.Identity | Select-Object -Property Name, Items, Status
$searches += $searchData
}
if ($searches.Count -eq 0) {
$searches = @{"Message" = "No searches found."}
}
# Convert the search data to JSON
$searchesJson = $searches | ConvertTo-Json
$response = "HTTP/1.1 200 OK`r`nContent-Type: application/json`r`n`r`n$searchesJson"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
"/delete" {
# Delete a compliance search
Write-Host "Handling delete search request"
$searchName = $queryParams["name"]
if ($searchName) {
try {
Remove-ComplianceSearch -Identity $searchName -Confirm:$false
$answer = "Search $searchName deleted successfully"
}
catch {
$answer = "Error deleting search $searchName"
}
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/plain`r`n`r`n$answer"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} else {
$htmlFilePath = "$PSScriptRoot\400.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 400 Bad Request`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
"/purge" {
# Delete a compliance search
Write-Host "Handling purge search request"
$searchName = $queryParams["name"]
if ($searchName) {
try {
New-ComplianceSearchAction -SearchName $searchName -Purge -PurgeType SoftDelete -Confirm:$false
$answer = "Search $searchName purging successfully"
}
catch {
$answer = "Error purging search $searchName"
}
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/plain`r`n`r`n$answer"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} else {
$htmlFilePath = "$PSScriptRoot\400.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 400 Bad Request`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
"/harddelete" {
# Delete a compliance search
Write-Host "Handling HARD DELETE search request"
$searchName = $queryParams["name"]
if ($searchName) {
try {
New-ComplianceSearchAction -SearchName $searchName -Purge -PurgeType HardDelete -Confirm:$false
$answer = "Search $searchName hard delete started successfully"
try {
Write-Host "Trying to start Managed Folder Assistant to immediately remove items..."
Get-Mailbox -ResultSize Unlimited | ForEach-Object { Start-ManagedFolderAssistant -Identity $_.UserPrincipalName -ComplianceJob}
Write-Host "Completed attempt."
}
catch {
Write-Host "Error starting Managed Folder Assistant: $_"
}
}
catch {
$answer = "Error hard deleting search $searchName"
}
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/plain`r`n`r`n$answer"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} else {
$htmlFilePath = "$PSScriptRoot\400.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 400 Bad Request`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
"/restart" {
# Restart a compliance search
Write-Host "Handling restart search request"
$searchName = $queryParams["name"]
if ($searchName) {
try {
Start-ComplianceSearch -Identity $searchName
$answer = "Search $searchName restarted successfully"
}
catch {
$answer = "Error restarting search $searchName"
}
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/plain`r`n`r`n$answer"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
} else {
$htmlFilePath = "$PSScriptRoot\400.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 400 Bad Request`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
"/block" {
# Handle block request
Write-Host "Handling block request"
# Extract search query parameters
$blockItem = $queryParams["blockitem"]
#Check if SHA256 hash or email address
if ($blockItem -match '^[A-Fa-f0-9]{64}$'){
try{
New-TenantAllowBlockListItems -ListType FileHash -Block -Entries $blockItem -NoExpiration
$resultMessage = "File hash $blockItem blocked successfully."
}
catch {
Write-Host "Error blocking file hash: $_"
$resultMessage = "Error blocking file hash $blockItem."
}
} elseif (Test-EmailAddress -Email $blockItem) {
try {
New-TenantAllowBlockListItems -ListType Sender -Block -Entries $blockItem -NoExpiration
$resultMessage = "Email address $blockItem blocked successfully."
}
catch {
Write-Host "Error blocking email address: $_"
$resultMessage = "Error blocking email address $blockItem."
}
} elseif (Test-IsValidDnsName -name $blockItem) {
try {
New-TenantAllowBlockListItems -ListType Sender -Block -Entries $blockItem -NoExpiration -ErrorAction Stop
$resultMessage = "Sending domain $blockItem blocked successfully."
}
catch {
Write-Host "Error blocking sending domain: $_"
$resultMessage = "Error blocking sending domain $blockItem."
}
} else {
$resultMessage = "The provided block item '$blockItem' is not a valid email address, domain, or SHA256 file hash."
}
$htmlFilePath = "$PSScriptRoot\search.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$htmlContent = $htmlContent -replace "##RESULTMESSAGE##", $resultMessage
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
#WAVE URLS
"/wave" {
# WAVE homepage
$htmlFilePath = "$PSScriptRoot\wave.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$htmlContent = $htmlContent -replace "##UPN##", $UPN
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
"/WAVE-background.jpg" {
# Handle background request
$backgroundPath = "$PSScriptRoot/WAVE-background.jpg"
$backgroundContent = [System.IO.File]::ReadAllBytes($backgroundPath)
$response = "HTTP/1.1 200 OK`r`nContent-Type: image/jpg`r`n`r`n"
$buffer = [System.Text.Encoding]::ASCII.GetBytes($response) + $backgroundContent
}
"/auditstatus" {
# Return audit status
Write-Host "Handling audit status request"
if (($null -eq $exportSessionID) -and -not ($auditDays -as [int])) {
$valid = $false
$resultMessage = "The number of days must be a valid integer."
$auditStatus = "error"
} else {
if ($null -eq $exportSessionID) {
#We are creating a new export session
$StartDate = (Get-Date).AddDays(-$auditDays)
$EndDate = Get-Date
Write-Host "Creating search session for for $auditUser from $StartDate to $EndDate..."
$auditData = @()
$exportSessionID = (New-Guid).Guid
$auditEvents = 0
$resultMessage = "An audit session is being started..."
$auditStatus = "ongoing"
}
else {
#We are checking the status of an existing export session
Write-Host "Checking status of search session $exportSessionID..."
#Get next batch
$Batch = Search-UnifiedAuditLog `
-StartDate $StartDate `
-EndDate $EndDate `
-UserIds $auditUser `
-SessionId $exportSessionID `
-SessionCommand ReturnLargeSet `
-ResultSize 5000
if ($Batch) {
$auditData += $Batch
$auditEvents += $Batch.Count
$resultMessage = "Processing $auditEvents events..."
$auditStatus = "ongoing"
} else {
$resultMessage = "Total events found: $auditEvents"
$auditStatus = "completed"
$exportSessionID = $null
}
}
}
}
"/audit" {
# Extract search query parameters
$auditDays = $queryParams["duration"]
$auditUser = $queryParams["user"]
$abuseIPDB = $queryParams["aipdb"]
$htmlFilePath = "$PSScriptRoot\audit.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
#$htmlContent = $htmlContent -replace "##RESULTMESSAGE##", $resultMessage
#$htmlContent = $htmlContent -replace "##STATUS##", $auditStatus
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
#404
default {
# Handle unknown page request
Write-Host "Unknown page request: $pageRequest"
$htmlFilePath = "$PSScriptRoot\404.html"
$htmlContent = Get-Content -Path $htmlFilePath -Raw
$response = "HTTP/1.1 200 OK`r`nContent-Type: text/html`r`n`r`n$htmlContent"
$buffer = [System.Text.Encoding]::UTF8.GetBytes($response)
}
}
$stream.Write($buffer, 0, $buffer.Length)
$stream.Close()
$client.Close()
}
#Cleanup
Write-Host "Logging out and ending processes..."
$listener.Stop()
Disconnect-ExchangeOnline -Confirm:$false
Read-Host "Session disconnected successfully. Hit enter to close"