khulnasoft commited on
Commit
7945a0d
1 Parent(s): 1c4000e

Create scripts/data-shippers/Send-AzMonitorCustomLogs.ps1

Browse files
scripts/data-shippers/Send-AzMonitorCustomLogs.ps1 ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function Send-AzMonitorCustomLogs
2
+ {
3
+ <#
4
+ .SYNOPSIS
5
+ Sends custom logs to a specific table in Azure Monitor.
6
+
7
+ .DESCRIPTION
8
+ Script to send data to a data collection endpoint which is a unique connection point for your subscription.
9
+ The payload sent to Azure Monitor must be in JSON format. A data collection rule is needed in your Azure tenant that understands the format of the source data, potentially filters and transforms it for the target table, and then directs it to a specific table in a specific workspace.
10
+ You can modify the target table and workspace by modifying the data collection rule without any change to the REST API call or source data.
11
+
12
+ .PARAMETER LogPath
13
+ Path to the log file or folder to read logs from and send them to Azure Monitor.
14
+
15
+ .PARAMETER appId
16
+ Azure Active Directory application to authenticate against the API to send logs to Azure Monitor data collection endpoint.
17
+ This script supports the Client Credential Grant Flow.
18
+
19
+ .PARAMETER appSecret
20
+ Secret text to use with the Azure Active Directory application to authenticate against the API for the Client Credential Grant Flow.
21
+
22
+ .PARAMETER TenantId
23
+ ID of Tenant
24
+
25
+ .PARAMETER DcrImmutableId
26
+ Immutable ID of the data collection rule used to process events flowing to an Azure Monitor data table.
27
+
28
+ .PARAMETER DceURI
29
+ Uri of the data collection endpoint used to host the data collection rule.
30
+
31
+ .PARAMETER TableName
32
+ Name of built-in Azure monitor table to send data to.
33
+
34
+ .PARAMETER StreamName
35
+ Name of stream to send data to before being procesed and sent to an Azure Monitor data table.
36
+
37
+ .PARAMETER TimestampField
38
+ Specific field available in your custom log to select as the main timestamp. This will be the TimeGenerated field in your table. By default, this script uses a current timestamp.
39
+
40
+ .PARAMETER ShowProgressBar
41
+ Show a PowerShell progress bar. Disabled by default.
42
+
43
+ .EXAMPLE
44
+ PS> . .\Send-AzMonitorCustomLogs.ps1
45
+ PS> Send-AzMonitorCustomLogs -LogPath C:\WinEvents.json -appId 'XXXX' -appSecret 'XXXXXX' -TenantId 'XXXXXX' -DcrImmutableId 'dcr-XXXX' -DceURI 'https://XXXX.westus2-1.ingest.monitor.azure.com' -TableName SecurityEvent -StreamName 'Custom-WindowsEvent' -TimestampField 'TimeCreated'
46
+
47
+ .EXAMPLE
48
+ PS> . .\Send-AzMonitorCustomLogs.ps1
49
+ PS> Send-AzMonitorCustomLogs -LogPath C:\WinEvents.json -appId 'XXXX' -appSecret 'XXXXXX' -TenantId 'XXXXXX' -DcrImmutableId 'dcr-XXXX' -DceURI 'https://XXXX.westus2-1.ingest.monitor.azure.com' -TableName SecurityEvent -StreamName 'Custom-WindowsEvent' -TimestampField 'TimeCreated' -Debug
50
+
51
+ .EXAMPLE
52
+ PS> . .\Send-AzMonitorCustomLogs.ps1
53
+ PS> Send-AzMonitorCustomLogs -LogPath C:\WinEventsFolder\ -appId 'XXXX' -appSecret 'XXXXXX' -TenantId 'XXXXXX' -DcrImmutableId 'dcr-XXXX' -DceURI 'https://XXXX.westus2-1.ingest.monitor.azure.com' -TableName SecurityEvent -StreamName 'Custom-WindowsEvent' -TimestampField 'TimeCreated' -Debug
54
+
55
+ .NOTES
56
+ # Author: Roberto Rodriguez (@Cyb3rWard0g)
57
+ # License: MIT
58
+
59
+ # Reference:
60
+ # https://docs.microsoft.com/en-us/azure/azure-monitor/logs/custom-logs-overview
61
+ # https://docs.microsoft.com/en-us/azure/azure-monitor/logs/tutorial-custom-logs-api#send-sample-data
62
+ # https://securitytidbits.wordpress.com/2017/04/14/powershell-and-gzip-compression/
63
+
64
+ # Custom Logs Limit
65
+ # Maximum size of API call: 1MB for both compressed and uncompressed data
66
+ # Maximum data/minute per DCR: 1 GB for both compressed and uncompressed data. Retry after the duration listed in the Retry-After header in the response.
67
+ # Maximum requests/minute per DCR: 6,000. Retry after the duration listed in the Retry-After header in the response.
68
+
69
+ .LINK
70
+ https://github.com/OTRF/Security-Datasets
71
+ #>
72
+ [CmdletBinding()]
73
+ param (
74
+ [Parameter(Mandatory=$true)]
75
+ [ValidateScript({
76
+ foreach ($f in $_)
77
+ {
78
+ if( -Not ($f | Test-Path) ){
79
+ throw "File or folder does not exist"
80
+ }
81
+ }
82
+ return $true
83
+ })]
84
+ [string[]]$LogPath,
85
+
86
+ [Parameter(Mandatory=$true)]
87
+ [string]$appId,
88
+
89
+ [Parameter(Mandatory=$true)]
90
+ [string]$appSecret,
91
+
92
+ [Parameter(Mandatory=$true)]
93
+ [string]$TenantId,
94
+
95
+ [Parameter(Mandatory=$true)]
96
+ [string]$DcrImmutableId,
97
+
98
+ [Parameter(Mandatory=$true)]
99
+ [string]$DceURI,
100
+
101
+ [Parameter(Mandatory=$true)]
102
+ [ValidateSet("SecurityEvent","WindowsEvent","Syslog")]
103
+ [string]$TableName,
104
+
105
+ [Parameter(Mandatory=$true)]
106
+ [string]$StreamName,
107
+
108
+ [Parameter(Mandatory=$false)]
109
+ [string]$TimestampField,
110
+
111
+ [Parameter(Mandatory=$false)]
112
+ [switch]$ShowProgressBar
113
+ )
114
+
115
+ If ($PSBoundParameters['Debug']) {
116
+ $DebugPreference = 'Continue'
117
+ }
118
+
119
+ @("
120
+ _________ .____________ __ .____ ____
121
+ / _____/ ____ ____ __| _/\_ ___ \ __ __ _______/ |_ ____ _____ | | ____ / ___\ ______
122
+ \_____ \ _/ __ \ / \ / __ | / \ \/ | | \/ ___/\ __\/ _ \ / \ | | / _ \ / /_/ >/ ___/
123
+ / \\ ___/ | | \/ /_/ | \ \____| | /\___ \ | | ( <_> )| Y Y \| |___( <_> )\___ / \___ \
124
+ /_______ / \___ >|___| /\____ | \______ /|____//____ > |__| \____/ |__|_| /|_______ \\____//_____/ /____ >
125
+ \/ \/ \/ \/ \/ \/ \/ \/ \/
126
+ ___________ _____ _____ .__ __
127
+ \__ ___/____ / _ \ ________ __ __ _______ ____ / \ ____ ____ |__|_/ |_ ____ _______
128
+ | | / _ \ / /_\ \ \___ /| | \\_ __ \_/ __ \ / \ / \ / _ \ / \ | |\ __\/ _ \\_ __ \
129
+ | | ( <_> )/ | \ / / | | / | | \/\ ___/ / Y \( <_> )| | \| | | | ( <_> )| | \/
130
+ |____| \____/ \____|__ //_____ \|____/ |__| \___ >\____|__ / \____/ |___| /|__| |__| \____/ |__|
131
+ \/ \/ \/ \/ \/ V0.3
132
+
133
+ Creator: Roberto Rodriguez @Cyb3rWard0g
134
+ License: MIT
135
+ ")
136
+
137
+ $ErrorActionPreference = "Stop"
138
+
139
+ # Aggregate files from input paths
140
+ $all_datasets = @()
141
+ foreach ($file in $LogPath){
142
+ if ((Get-Item $file) -is [system.io.fileinfo]){
143
+ $all_datasets += (Resolve-Path -Path $file)
144
+ }
145
+ elseif ((Get-Item $file) -is [System.IO.DirectoryInfo]){
146
+ $folderfiles = Get-ChildItem -Path $file -Recurse -Include *.json
147
+ $all_datasets += $folderfiles
148
+ }
149
+ }
150
+
151
+ write-Host "*******************************************"
152
+ Write-Host "[+] Obtaining access token.."
153
+ ## Obtain a bearer token used to authenticate against the data collection endpoint
154
+ $scope = [System.Net.WebUtility]::UrlEncode("https://monitor.azure.com//.default")
155
+ $body = "client_id=$appId&scope=$scope&client_secret=$appSecret&grant_type=client_credentials";
156
+ $headers = @{"Content-Type" = "application/x-www-form-urlencoded"};
157
+ $uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
158
+ $bearerToken = (Invoke-RestMethod -Uri $uri -Method "Post" -Body $body -Headers $headers).access_token
159
+ Write-Debug $bearerToken
160
+
161
+ Function Send-DataToDCE($payload, $size){
162
+ write-debug "############ Sending Data ############"
163
+ write-debug "JSON array size: $($size/1mb) MBs"
164
+
165
+ # Initialize Headers and URI for POST request to the Data Collection Endpoint (DCE)
166
+ $headers = @{"Authorization" = "Bearer $bearerToken"; "Content-Type" = "application/json"}
167
+ $uri = "$DceURI/dataCollectionRules/$DcrImmutableId/streams/$StreamName`?api-version=2021-11-01-preview"
168
+
169
+ # Showing payload for troubleshooting purposes
170
+ Write-Debug ($payload | ConvertFrom-Json | ConvertTo-Json)
171
+
172
+ # Sending data to Data Collection Endpoint (DCE) -> Data Collection Rule (DCR) -> Azure Monitor table
173
+ Invoke-RestMethod -Uri $uri -Method "Post" -Body (@($payload | ConvertFrom-Json | ConvertTo-Json)) -Headers $headers | Out-Null
174
+ }
175
+
176
+ # Maximum size of API call: 1MB for both compressed and uncompressed data
177
+ $APILimitBytes = 1mb
178
+
179
+ # Official Azure Monitor Build-Int Table Schemas
180
+ $securityEventProperties=@("AccessMask","Account","AccountDomain","AccountExpires","AccountName","AccountSessionIdentifier","AccountType","Activity","AdditionalInfo","AdditionalInfo2","AllowedToDelegateTo","Attributes","AuditPolicyChanges","AuditsDiscarded","AuthenticationLevel","AuthenticationPackageName","AuthenticationProvider","AuthenticationServer","AuthenticationService","AuthenticationType","AzureDeploymentID","CACertificateHash","CalledStationID","CallerProcessId","CallerProcessName","CallingStationID","CAPublicKeyHash","CategoryId","CertificateDatabaseHash","Channel","ClassId","ClassName","ClientAddress","ClientIPAddress","ClientName","CommandLine","CompatibleIds","Computer","DCDNSName","DeviceDescription","DeviceId","DisplayName","Disposition","DomainBehaviorVersion","DomainName","DomainPolicyChanged","DomainSid","EAPType","ElevatedToken","ErrorCode","EventData","EventID","EventSourceName","ExtendedQuarantineState","FailureReason","FileHash","FilePath","FilePathNoUser","Filter","ForceLogoff","Fqbn","FullyQualifiedSubjectMachineName","FullyQualifiedSubjectUserName","GroupMembership","HandleId","HardwareIds","HomeDirectory","HomePath","InterfaceUuid","IpAddress","IpPort","KeyLength","Level","LmPackageName","LocationInformation","LockoutDuration","LockoutObservationWindow","LockoutThreshold","LoggingResult","LogonGuid","LogonHours","LogonID","LogonProcessName","LogonType","LogonTypeName","MachineAccountQuota","MachineInventory","MachineLogon","ManagementGroupName","MandatoryLabel","MaxPasswordAge","MemberName","MemberSid","MinPasswordAge","MinPasswordLength","MixedDomainMode","NASIdentifier","NASIPv4Address","NASIPv6Address","NASPort","NASPortType","NetworkPolicyName","NewDate","NewMaxUsers","NewProcessId","NewProcessName","NewRemark","NewShareFlags","NewTime","NewUacValue","NewValue","NewValueType","ObjectName","ObjectServer","ObjectType","ObjectValueName","OemInformation","OldMaxUsers","OldRemark","OldShareFlags","OldUacValue","OldValue","OldValueType","OperationType","PackageName","ParentProcessName","PasswordHistoryLength","PasswordLastSet","PasswordProperties","PreviousDate","PreviousTime","PrimaryGroupId","PrivateKeyUsageCount","PrivilegeList","Process","ProcessId","ProcessName","ProfilePath","Properties","ProtocolSequence","ProxyPolicyName","QuarantineHelpURL","QuarantineSessionID","QuarantineSessionIdentifier","QuarantineState","QuarantineSystemHealthResult","RelativeTargetName","RemoteIpAddress","RemotePort","Requester","RequestId","RestrictedAdminMode","RowsDeleted","SamAccountName","ScriptPath","SecurityDescriptor","ServiceAccount","ServiceFileName","ServiceName","ServiceStartType","ServiceType","SessionName","ShareLocalPath","ShareName","SidHistory","SourceComputerId","SourceSystem","Status","StorageAccount","SubcategoryGuid","SubcategoryId","Subject","SubjectAccount","SubjectDomainName","SubjectKeyIdentifier","SubjectLogonId","SubjectMachineName","SubjectMachineSID","SubjectUserName","SubjectUserSid","SubStatus","TableId","TargetAccount","TargetDomainName","TargetInfo","TargetLinkedLogonId","TargetLogonGuid","TargetLogonId","TargetOutboundDomainName","TargetOutboundUserName","TargetServerName","TargetSid","TargetUser","TargetUserName","TargetUserSid","TemplateContent","TemplateDSObjectFQDN","TemplateInternalName","TemplateOID","TemplateSchemaVersion","TemplateVersion","TimeGenerated","TokenElevationType","TransmittedServices","Type","UserAccountControl","UserParameters","UserPrincipalName","UserWorkstations","VendorIds","VirtualAccount","Workstation","WorkstationName")
181
+ $windowsEventProperties=@("Channel","Computer","EventData","EventID","EventLevel","EventLevelName","EventOriginId","ManagementGroupName","Provider","RawEventData","Task","TimeGenerated","Type")
182
+ $syslogProperties=@("Computer","EventTime","Facility","HostIP","HostName","ProcessID","ProcessName","SeverityLevel","SourceSystem","SyslogMessage","TimeGenerated","Type")
183
+
184
+ foreach ($dataset in $all_datasets){
185
+ $total_file_size = (get-item -Path $dataset).Length
186
+ $json_records = @()
187
+ $json_array_current_size = 0
188
+ $event_count = 0
189
+ $total_size = 0
190
+
191
+ # Create ReadLines Iterator and get total number of lines
192
+ $readLineIterator = [System.IO.File]::ReadLines($dataset)
193
+ $numberOfLines = [Linq.Enumerable]::Count($readLineIterator)
194
+
195
+ write-Host "*******************************************"
196
+ Write-Host "[+] Processing $dataset"
197
+ Write-Host "[+] Dataset Size: $($total_file_size/1mb) MBs"
198
+ Write-Host "[+] Number of events to process: $numberOfLines"
199
+
200
+ # Read each JSON object from file
201
+ foreach($line in $readLineIterator){
202
+ # Increase event number
203
+ $event_count += 1
204
+
205
+ # Update progress bar with current event count
206
+ if ($ShowProgressBar){ Write-Progress -Activity "Processing files" -status "Processing $dataset" -percentComplete ($event_count / $numberOfLines * 100) }
207
+
208
+ write-debug "############ Event $event_count ###############"
209
+ if ($TimestampField){
210
+ $TimeGenerated= $line | Convertfrom-json | Select-Object -ExpandProperty $TimestampField
211
+ }
212
+ else {
213
+ $TimeGenerated = Get-Date ([datetime]::UtcNow) -Format O
214
+ }
215
+
216
+ # Processing Log entry as a compressed JSON object
217
+ $pscustomobject = $line | ConvertFrom-Json
218
+ $pscustomobject | Add-Member -MemberType NoteProperty -Name 'TimeGenerated' -Value $TimeGenerated -Force
219
+
220
+ # Current properties of PSCustomObject
221
+ $currentEventProperties=Get-Member -InputObject $pscustomobject -MemberType NoteProperty
222
+
223
+ if ($TableName -eq 'SecurityEvent') {
224
+ # If Hostname is present, rename it to Computer
225
+ if ( $pscustomobject.psobject.properties.match('Hostname').Count ) {
226
+ $pscustomobject | Add-Member -MemberType NoteProperty -Name 'Computer' -Value $pscustomobject.Hostname -Force
227
+ }
228
+ # Validate schema
229
+ $allowedProperties = Compare-Object -ReferenceObject $securityEventProperties -DifferenceObject $currentEventProperties.name -PassThru -ExcludeDifferent -IncludeEqual
230
+ }
231
+ elseif ($TableName -eq 'WindowsEvent') {
232
+ # If Hostname is present, rename it to Computer
233
+ if ( $pscustomobject.psobject.properties.match('Hostname').Count ) {
234
+ $pscustomobject | Add-Member -MemberType NoteProperty -Name 'Computer' -Value $pscustomobject.Hostname -Force
235
+ }
236
+
237
+ # Validate EventData
238
+ if ( -not $pscustomobject.psobject.properties.match('EventData').Count ) {
239
+ $pscustomobject | Add-Member -MemberType NoteProperty -Name 'EventData' -Value $($line | ConvertTo-Json -Compress) -Force
240
+ }
241
+
242
+ # Add Type WindowsEvent
243
+ $pscustomobject | Add-Member -MemberType NoteProperty -Name 'Type' -Value 'WindowsEvent' -Force
244
+
245
+ # Validate schema
246
+ $allowedProperties = Compare-Object -ReferenceObject $windowsEventProperties -DifferenceObject $currentEventProperties.name -PassThru -ExcludeDifferent -IncludeEqual
247
+ }
248
+ else {
249
+ # Validate schema
250
+ $allowedProperties = Compare-Object -ReferenceObject $syslogProperties -DifferenceObject $currentEventProperties.name -PassThru -ExcludeDifferent -IncludeEqual
251
+ }
252
+
253
+ # Select only fields from the allowedProperties variable
254
+ $message = $pscustomobject | Select-Object -Property @($allowedProperties) | ConvertTo-Json -Compress
255
+ Write-Debug "Processing log entry: $($message.Length) bytes"
256
+
257
+ # Getting proposed and current JSON array size
258
+ $json_array_current_size = ([System.Text.Encoding]::UTF8.GetBytes(@($json_records | Convertfrom-json | ConvertTo-Json))).Length
259
+ $json_array_proposed_size = ([System.Text.Encoding]::UTF8.GetBytes(@(($json_records + $message) | Convertfrom-json | ConvertTo-Json))).Length
260
+ Write-Debug "Current size of JSON array: $json_array_current_size bytes"
261
+
262
+ if ($json_array_proposed_size -le $APILimitBytes){
263
+ $json_records += $message
264
+ $json_array_current_size = $json_array_proposed_size
265
+ write-debug "New size of JSON array: $json_array_current_size bytes"
266
+ }
267
+ else {
268
+ write-debug "Sending current JSON array before processing more log entries.."
269
+ Send-DataToDCE -payload $json_records -size $json_array_current_size
270
+ # Keeping track of how much data we are sending over
271
+ $total_size += $json_array_current_size
272
+
273
+ # There are more events to process..
274
+ write-debug "######## Resetting JSON Array ########"
275
+ $json_records = @($message)
276
+ $json_array_current_size = ([System.Text.Encoding]::UTF8.GetBytes(@($json_records | Convertfrom-json | ConvertTo-Json))).Length
277
+ Write-Debug "Starting JSON array with size: $json_array_current_size bytes"
278
+ }
279
+
280
+ if($event_count -eq $numberOfLines){
281
+ write-debug "##### Last log entry in $dataset #######"
282
+ Send-DataToDCE -payload $json_records -size $json_array_current_size
283
+ # Keeping track of how much data we are sending over
284
+ $total_size += $json_array_current_size
285
+ }
286
+ }
287
+ Write-Host "[+] Finished processing dataset"
288
+ Write-Host "[+] Number of events processed: $event_count"
289
+ Write-Host "[+] Total data sent: $($total_size/1mb) MBs"
290
+ write-Host "*******************************************"
291
+ }
292
+ }