-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathccAnalyzer.ps1
378 lines (327 loc) · 15.2 KB
/
ccAnalyzer.ps1
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
##################################################################################################
# ccPowerShellProject
##################################################################################################
# Analyze PowerShell transcripts and alerting on potentially harmful actions.
#
# Thomas Koscheck
#
# FUNCTION DETAILS
# - <<function 1>>
# - <<function 2>>
# - <<function ...>>
#
# METADATA:
# <<Customer Company>>/<<Customer Contact Person>>, CCVOSSEL GmbH
#
# SYNTAX: ccAnalyzer.ps1
# -eventRecordID The unique record id of the event, that triggered the script
# -eventCreatedTime The creation time of the event, that triggered the script
# [-Output display|file|displayandfile|none]
#
# Output : possible values: display, file, displayandfile, none
# display = output to standard output only
# file = only output in log file at script directory
# displayandfile = output to standard output and log file
# none = no output
#
##################################################################################################
# Sample call:
# ccAnalyzer.ps1 -eventRecordID "878" - eventCreatedTime
##################################################################################################
##################################################################################################
# Parameters
##################################################################################################
Param (
[Parameter(Mandatory=$true)]
[string]$eventRecordID,
$eventCreatedTime,
[string]$Output = "file"
)
##################################################################################################
##################################################################################################
# Initialisation
##################################################################################################
##################################################################################################
# region Include required files
#
try {
. ("modules\mailer.ps1")
. ("modules\splunk.ps1")
}
catch {
Write-Host "Error while loading supporting PowerShell Scripts"
}
#endregion
##################################################################################################
# Parameter check
##################################################################################################
switch($output.trim().tolower())
{
"none"
{
$bolOutputDisplay = $false
$bolOutputFile = $false
}
"display"
{
$bolOutputDisplay = $true
$bolOutputFile = $false
}
"file"
{
$bolOutputDisplay = $false
$bolOutputFile = $true
}
{("fileanddisplay","displayandfile" -contains $_)}
{
$bolOutputDisplay = $true
$bolOutputFile = $true
}
default
{
$bolOutputDisplay = $true
$bolOutputFile = $false
}
}
##################################################################################################
# Script variables
##################################################################################################
$strScriptAuthors = "ThomasKoscheck"
$strScriptFunction = "Analyze PowerShell transcripts and alerting on potentially harmful actions."
##################################################################################################
# Determine script paths
##################################################################################################
$strScriptPath = Split-Path $myInvocation.MyCommand.Path
$strScriptFullPath = $myInvocation.MyCommand.Path
$strScriptName = $myInvocation.MyCommand.Name
$strLogFileSubDir = "Logfiles"
Import-Module (Join-Path $strScriptPath "CCV.Logging\CCV.Logging.psd1") -Force
if ($bolOutputFile)
{
$strLogFileDir = (Join-Path $strScriptPath $strLogFileSubDir)
##################################################################################################
# Create log file
##################################################################################################
New-CCVLog -strLogFolderPath $strLogFileDir -strLogFileName (($strScriptName -replace ".ps1",".") + "-" + $eventRecordID + ".log")
}
##################################################################################################
# Write log file header
##################################################################################################
Write-CCVLogHead -strScriptFileName $strScriptName -strScriptAuthors $strScriptAuthors -strScriptFunction $strScriptFunction
##################################################################################################
# Global Constants
##################################################################################################
$rulesPath = Join-Path $strScriptPath "\configuration\rules.json"
$configPath = Join-Path $strScriptPath "\configuration\config.json"
##################################################################################################
##################################################################################################
##################################################################################################
# Sub routines
##################################################################################################
##################################################################################################
##################################################################################################
function WriteSyntaxError($strErrorMessage)
{
Write-Host ""
Write-Host "SYNTAX ERROR"
Write-Host ""
Write-Host $strErrorMessage
Write-Host ""
Write-Host ("SYNTAX: <Skriptname.ps1>" + `
" -Param1 " + "<<Param1 description>>" + `
" -Param2 " + "<<Param2 description>>" + `
" [-Output display|file|displayandfile|none]")
Write-Host ""
Write-Host "Param1 : <<detailed description of param1>>"
Write-Host ""
Write-Host "Param2 : <<detailed description of param2>>"
Write-Host ""
Write-Host "Output : possible values: display, file, displayandfile, none"
Write-Host " : display = output to standard output only"
Write-Host " : file = only output in log file at script directory"
Write-Host " : displayandfile = output to standard output and log file"
Write-Host " : none = no output"
Write-Host ""
Write-Host "Script created by $strScriptAuthors"
}
function CheckMandatoryParameter($strParamName,$strParamValue)
{
if ($strParamValue -eq "")
{
WriteSyntaxError "Value of parameter '$strParamName' is missing."
return $false
}
else
{
return $true
}
}
function Extract-Metadata {
Param (
[Parameter(Mandatory=$true)]
[string]$EventMessage
)
# Matches the beginning of the line until ): and a new line
# this indicates the first line which is usually smth like 'Creating Scriptblock text (1 of 1):'
#return ($EventMessage -split '^.*\)\:')[1]
$lines = $EventMessage -split '\n'
$command = ""
foreach ( $word in $lines[1 .. ($lines.Count - 4)] ) {
$command += $word + ' '
}
# remove two last lines, because of empty last line
$path = $lines[$lines.Count - 2]
[string[]]$returnArray = $command,$path
return $returnArray
}
function Get-EventExecutionPath {
Param (
[Parameter(Mandatory=$true)]
[string]$EventMessage
)
# Matches the beginning of the path line until 'Path:'
# this indicates the path line which is usually smth like 'Path: C:\Windows\TEMP\SDIAG_141a5465-4c2b-4e13-86e7-9787237a38c1\TS_DiagnosticHistory.ps1'
$path = ($EventMessage -split '\: ')[1]
$pathClean = ($path -split '\n')[0].Trim()
# path is empty, if command is invoked by user
if ($pathClean) {
return $pathClean
} else {
return "Interactively by user"
}
}
function Get-ADUserEmail ($userName) {
$user = Get-ADUser -Identity $userName -Properties EmailAddress
$userMail = $user.EmailAddress
if (IsEmailValid $userMail) {
return $userMail
} else {
# the email we found in the AD seems not to be a valid email, send mail to admin instead
Write-CCVLog "warning" "We found a non valid email: $userMail"
Write-CCVLog "warning" "Sending notification to admin instead"
return $settings.config.notifications.mailTo
}
}
function Convert-SIDToUserName ($sid) {
Try {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
return $objUser.Value
}
Catch {
Write-CCVLog "warning" "Could not convert SID $sid to username"
Write-CCVLog "warning" "Error: $_"
}
}
##################################################################################################
##################################################################################################
##################################################################################################
# Main program
##################################################################################################
##################################################################################################
##################################################################################################
# rules are heavily based on https://github.com/secprentice/PowerShellBlacklist/blob/master/badshell.txt,
# https://gist.github.com/gfoss/2b39d680badd2cad9d82
$rules = [System.IO.File]::ReadAllLines((Resolve-Path $rulesPath)) | ConvertFrom-Json
$settings = [System.IO.File]::ReadAllLines((Resolve-Path $configPath)) | ConvertFrom-Json
$psEvent = Get-WinEvent -FilterHashtable @{LogName='Application';ID=4104;StartTime=$eventCreatedTime} | Where-Object -Property RecordId -eq $eventRecordID
# $psEvent = Get-WinEvent -FilterHashtable @{LogName='Application';ID=4104} | Where-Object -Property RecordId -eq $eventRecordID # for debugging
Write-CCVLog "info" "Trigger forwarded following details: StartTime $eventCreatedTime, EventID $eventRecordID"
# event.Message is Type System.Object[]
$eventMessage = $psEvent.Message | Out-String
# prepare event message and clean unnecessary lines and characters
$eventMetadata = Extract-Metadata $eventMessage
$PSCodeLines = $eventMetadata[0]
$PSCodeLines = $PSCodeLines.Trim()
# extract event meta data
$eventPath = Get-EventExecutionPath $eventMetadata[1]
$eventTime = $psEvent.TimeCreated
$eventMachine = $psEvent.MachineName
$userIdString = "UserId: " + $psEvent.UserId
Write-CCVLog "info" $userIdString
$eventUser = Convert-SIDToUserName $psEvent.UserId
Write-CCVLog "info" "EventId: $eventRecordID"
Write-CCVLog "info" "Command: $PSCodeLines"
Write-CCVLog "info" "Time: $eventTime"
Write-CCVLog "info" "MachineName: $eventMachine"
Write-CCVLog "info" "User: $eventUser"
Write-CCVLog "info" "Path: $eventPath"
# filter for malicious content
$matched = $false
$PSCodeLinesLower = $PSCodeLines.ToLower()
foreach ($rule in $rules.rules) {
if (($PSCodeLinesLower) -match ($rule.rule)) {
$matched = $true
Write-CCVLog "warning" "Detected harmful command: $PSCodeLines"
$badnessLogString = "Badness: " + $rule.badness
Write-CCVLog "warning" $badnessLogString
# send mail only if badness is above threshold in config.json
if ($rule.badness -gt $settings.config.notifications.badnessThresholdAdmin) {
# create and send mail
$Subject = "ccPowerShellProtect - New alert"
$Body = New-MailBody -match $rule.rule `
-matchComment $rule.comment `
-badness $rule.badness `
-eventTime $eventTime `
-eventUser $eventUser `
-eventMachine $eventMachine `
-PSCodeLines $PSCodeLines `
-eventPath $eventPath
# send mail to user/admin depending on config.json
$mailTo = ""
if ($settings.config.notifications.sendNotificationToUser) {
# remove the domain\ prefix of the username
Write-CCVLog "info" "sending mail to user"
$cleanUsername = ($eventUser -split "\\")[1]
$mailTo = Get-ADUserEmail $cleanUsername
} else {
$mailTo = $settings.config.notifications.mailTo
}
Write-CCVLog "info" $settings.config.notifications.mailTo
Send-Mail-Mailjet -from $settings.config.notifications.mailFrom `
-to $mailTo `
-username $settings.config.notifications.username `
-password $settings.config.notifications.passwordAsSecureString
-Body $Body `
-Subject $Subject
Write-CCVLog "info" "Sent mail to $mailTo"
}
# send event to splunk if enabled
if ($settings.config.splunk.enabled) {
$match = $rule.rule
$comment = $rule.comment
$splunkMessage = "Rule: $match, comment: $comment, eventRecordID: $eventRecordID, supiciousCode: $PSCodeLinesLower"
$severity = Get-SplunkSeverity $rule.badness
$splunkEvent = @{message=$splunkMessage;severity=$severity;user=$eventUser}
Send-SplunkEvent -InputObject $splunkEvent -Hostname $eventMachine -DateTime $eventTime
}
break
}
}
if (-not $matched)
{
if ($settings.config.others.logHarmlessCommands) {
Write-CCVLog "info" $PSCodeLinesLower $bolOutputDisplay $true $ColorHighlight
}
# send harmless events to splunk
if ($settings.config.splunk.logHarmlessCommands) {
# send harmlesse events to splunk if event does not equal "prompt"
if ($settings.config.splunk.excludePromptEvents -and (-not ($PSCodeLinesLower -eq "prompt"))) {
$splunkMessage = "Rule: $PSCodeLinesLower, comment: NA, eventRecordID: $eventRecordID"
$severity = Get-SplunkSeverity 0 # because harmless commands have no severity, we wil log this as "debug"
$splunkEvent = @{message=$splunkMessage;severity=$severity;user=$eventUser}
Send-SplunkEvent -InputObject $splunkEvent -Hostname $eventMachine -DateTime $eventTime
}
# also sent "prompt" events
elseIF (-not $settings.config.splunk.excludePromptEvents) {
$splunkMessage = "Rule: $PSCodeLinesLower, comment: NA, eventRecordID: $eventRecordID"
$severity = Get-SplunkSeverity 0 # because harmless commands have no severity, we wil log this as "debug"
$splunkEvent = @{message=$splunkMessage;severity=$severity;user=$eventUser}
Send-SplunkEvent -InputObject $splunkEvent -Hostname $eventMachine -DateTime $eventTime
}
}
}
##################################################################################################
# Write log file bottom
##################################################################################################
Write-CCVLogBottom -strScriptFileName $strScriptName