O365_Unified_Auditlog_parser.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
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

<#PSScriptInfo
 
.VERSION 1.1
 
.GUID 2082a2b3-155c-42e5-b3f6-c67434a0a3e1
 
.AUTHOR mikko@lavento.com
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS O365 UnifiedAuditlog Auditlog parser
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>
 













<#
 
.DESCRIPTION
  
O365 auditlog (Unified log) parser.
 
Applies to logs downloaded from https://protection.office.com - Search & investigation - Audit log search - Download - .csv
 
Downloaded log has 4 colums:
CreationDate | UserIds | Operations | Auditdata
Problem: the most important one (Auditdata) is string mess where data is delimited with ; , and [] and you can't really import it to excel to filter reasonably for examing.
Also problem: different services log more or less data so no fixed amount of columns
 
This parser will modify the Auditdata column, creates a table and exports the parsered csv file (to be imported to excel).
More comments inside the script.
 
 
#>
 

Param()


# 29.5.2018 M.Lavento
# O365 auditlog (Unified log) parser
# Applies to logs downloaded from https://protection.office.com - Search & investigation - Audit log search - Download .csv
#

# Downloaded log has 4 colums
# CreationDate | UserIds | Operations | Auditdata
# Problem: the most important one (Auditdata) is "string mess" where data is delimited with ; , and [] and you can't really import it to excel to filter reasonably.
# Also problem: different services log more or less data so no fixed amount of columns

# Solution: delimiter to be used while importing to Excel seems to be "," BUT NOT INSIDE brackets [{ }] so we change all "," --> �� as delimiter inside brackets []
# Delimiter char changes atleast for me to �� --> ??, but it doesn't really matter
# Then we can split and construct a table in a format where it is csv exportable


# But first Columns for the result table#
# Bad thing is that cloumns has to be known beforehand.
# Used Microsoft's own info what they might be and I added atleast five extra ones what came up while testing
# https://support.office.com/en-us/article/detailed-properties-in-the-office-365-audit-log-ce004100-9e7f-443e-942b-9b04098fcfc3

# But because it's Microsoft and there might be more in the future or misinterpretations in the code we have to create the headers.

# I created column name Miscellaneous as the last column

$columnheaders = `
"CreationDate",`
"UserIds",`
"Operations",`
"Actor",`
"ActorContextId",`
"ActorIpAddress",`
"AddOnName",`
"AddOnType",`
"ApplicationDisplayName",`
"ApplicationId",`
"AzureActiveDirectoryEventType",`
"ChannelGuid",`
"ChannelName",`
"Client",`
"ClientInfoString",`
"ClientIP",`
"ClientIPAddress",`
"CorrelationId",`
"CreationTime",`
"CustomUniqueId",`
"DestinationFileExtension",`
"DestinationFileName",`
"DestinationRelativeUrl",`
"EventData",`
"EventSource",`
"ExternalAccess",`
"ExtendedProperties",`
"ID",`
"InternalLogonType",`
"InterSystemsId",`
"IntraSystemId",`
"ItemType",`
"ListId",`
"ListItemUniqueId",`
"LoginStatus",`
"LogonError",`
"LogonType",`
"MailboxGuid",`
"MailboxOwnerUPN",`
"Members",`
"ModifiedProperties (Name, NewValue, OldValue)",`
"ObjectID",`
"Operation",`
"OrganizationID",`
"OrganizationName",`
"OriginatingServer",`
"Path",`
"Parameters",`
"RecordType",`
"ResultStatus",`
"SecurityComplianceCenterEventType",`
"SharingType",`
"Site",`
"SiteUrl",`
"SourceFileExtension",`
"SourceFileName",`
"SourceRelativeUrl",`
"Subject",`
"TabType",`
"Target",`
"TargetContextId",`
"TeamGuid",`
"TeamName",`
"UserAgent",`
"UserDomain",`
"UserID",`
"UserKey",`
"UserSharedWith",`
"UserType",`
"Version",`
"WebId",`
"Workload",`
"Miscellaneous"





############# Main script

#Open dialog by Dan Stolts
$openFileDialog = New-Object windows.forms.openfiledialog   
$openFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()   
$openFileDialog.title = "Select Log File to be parsered"   
$openFileDialog.filter = "CSV Files|*.csv|All Files|*.*" 
$openFileDialog.ShowHelp = $True   
Write-Host "Select Downloaded Settings File... (see FileOpen Dialog)" -ForegroundColor Green  
$result = $openFileDialog.ShowDialog()   # Display the Dialog / Wait for user response
# in ISE you may have to alt-tab or minimize ISE to see dialog box
$result 
if($result -eq "OK")    {    
    Write-Host "Selected Downloaded Settings File:"  -ForegroundColor Green  
    $OpenFileDialog.filename   
} 
else { Write-Host "File Selection Cancelled!" -ForegroundColor Yellow; exit} 

$logsource = $openFileDialog.FileName
$logdirectory = Split-Path -Parent $logsource
$exported_log = $logsource -replace ".csv","_parsered.csv"

#Progressbar Start time
$PBStartTime = Get-Date

$log = Import-Csv -Path $logsource

#Choose �� for chars replacing the , inside certain Auditdata's values, namely between: [{ }]
#check if there is already �� in original log to be sure

$ErotinCount = [regex]::matches($log,����).count
if ($ErotinCount -eq 0)
{
$ErotinChar = "��"
}
else
{
$ErotinChar = "�M�"   
}

#total amount of rows in the log
$rivienmaara = $log.count
$rivilaskuri = 0

#create table to be populated, if exists then remove
$tabName = "O365LogTable"

if (Get-Variable -Name table -ErrorAction SilentlyContinue)
{
Remove-Variable table
}
$table = New-Object system.Data.DataTable �$tabName�


# Build table columns
$columnloop = 0
$cols = @()
$colheaders = @()
do
{
$cols += $columnheaders[$columnloop]
$colheaders += New-Object system.Data.DataColumn $cols[$columnloop],([string])

#Add the Columns
$table.columns.add($colheaders[$columnloop])

$columnloop++
}
until ($columnloop -gt ($columnheaders.count)-1)



# Begin to parser line by line

do
{
$string = $log[$rivilaskuri]

$parseredstring = $string

#trimming brackets
$parseredstring.Auditdata = $parseredstring.Auditdata.Trim("{","}")

$parseredstringaudit = $parseredstring.AuditData
    
    #NonGreedy, fecth only [{ }] and all of them to regex-groups
    $AllMatches = $parseredstringaudit | Select-String -Pattern "\[{.*?\}]" -AllMatches | foreach {$_.Matches}
   
    $matchcount = $AllMatches.Count
   
    if($AllMatches.Success)            
    {            
            
        #if only one hit, then don't iterate by items

        if($matchcount -eq 1){

            $old = $AllMatches.Value
            $New = $old -replace ",",$ErotinChar
   
            $parseredstringaudit = $parseredstringaudit.Replace($old,$new)
            $parsered = $parseredstringaudit

        }
        else
        {
            $matchloop = 0

           
            #loop line with regex-hits and replace comma (,) --> �� ONLY inside [{ }]
            do
            {
            
            $old = $AllMatches[$matchloop].Value
            $New = $old -replace ",",$ErotinChar
   
            $parseredstringaudit = $parseredstringaudit.Replace($old,$new)
            $parsered = $parseredstringaudit

            $matchloop++
            }
            until ($matchloop -gt $matchcount-1)
         }
     }

 
    ######## Done replacing between [{ }]

    #after that we still have to look if there is ", " (<= ,<empty>) in the line
    
    #NonGreedy, fecth only ", " and all of them to regex-groups
    $AllMatches = $parseredstringaudit | Select-String -Pattern "\, " -AllMatches | foreach {$_.Matches}
    $matchcount = $AllMatches.Count

    if($AllMatches.Success)            
    {                    
        #if only one hit, then don't iterate by items

        if($matchcount -eq 1){

            $old = $AllMatches.Value
            $New = $old -replace ",",$ErotinChar
   
            $parseredstringaudit = $parseredstringaudit.Replace($old,$new)
            $parsered = $parseredstringaudit

        }
        else
        {
            $matchloop = 0

           
            #loop line with regex-hits and replace comma (,) --> �� ONLY inside [{ }]
            do
            {
            
            $old = $AllMatches[$matchloop].Value
            $New = $old -replace ",",$ErotinChar
   
            $parseredstringaudit = $parseredstringaudit.Replace($old,$new)
            $parsered = $parseredstringaudit

            $matchloop++
            }
            until ($matchloop -gt $matchcount-1)
         }
     }

 
        ######## Done ", " -replacements
        
        # and now we are able to split

        $parseredsplitted = $parsered.Split(",")
        $parseredsplitcount = $parseredsplitted.Count

        $splitloop = 0

        #Create a row to table
        $row = $table.NewRow()
        
        #loop and get headers and values
        do
        {
    
        #header (left-part) and value (right part)
        $pos = $parseredsplitted[$splitloop].IndexOf(":")
        
        $leftPart = $parseredsplitted[$splitloop].Substring(0, $pos)
        $rightpart = $parseredsplitted[$splitloop].Substring($pos+1)

        #trim "

        $leftPart = $leftPart.Trim('"','"')
        $rightpart = $rightpart.Trim('"','"')


        ##### populate the values based on headers
        ##### best part of this that you can populate table by pointing to header names.
        ##### we don't have to worry about missing column values in the log row

        #find matching header "number"
        $colnumber = $table.Columns.IndexOf($leftPart)
        #If there is no match then use Miscellaneous-column
        if ($colnumber -eq "-1")
        {
        $colnumber = $table.Columns.IndexOf("Miscellaneous")
        Write-Host "No column, using misc, linenumber: $rivilaskuri"
        }

        #Enter data in the row
        $row.($cols[$colnumber]) = $rightpart

        $splitloop++
        }
        until ($splitloop -gt $parseredsplitcount-1)
  

        #Let's add three first columns to row from the original log
        $row.($cols[0]) = $log[$rivilaskuri].CreationDate
        $row.($cols[1]) = $log[$rivilaskuri].UserIds
        $row.($cols[2]) = $log[$rivilaskuri].Operations

        #Add the populated row to the table
        $table.Rows.Add($row)

        #skip to next line in log
        $rivilaskuri++   
        
        #Show some progresinfo to user
         
        ## -- Calculate The Percentage Completed
        [Int]$Percentage = ($rivilaskuri/$rivienmaara)*100
        #$PB.Value = $Percentage

        #calculate seconds
        $SecondsElapsed = ((Get-Date) - $PBStartTime).TotalSeconds
        $SecondsRemaining = ($SecondsElapsed / ($rivilaskuri/$rivienmaara)) - $SecondsElapsed

        #transform to more readable format
        $kulsek =  [timespan]::fromseconds($SecondsElapsed)
        $sekunnitkulunut = $kulsek.ToString("hh\:mm\:ss")

        $jalsek =  [timespan]::fromseconds($SecondsRemaining)
        $sekunnitjaljella = $jalsek.ToString("hh\:mm\:ss")

        Write-Progress -Activity "Prosessing" -Status "Processing: $rivilaskuri / $rivienmaara Elapsed Time: $sekunnitkulunut, Estimated time left: $sekunnitjaljella" -PercentComplete $Percentage
      
}
until ($rivilaskuri -gt $rivienmaara-1)

#close the bar
Write-Progress -Activity "Prosessing" -Status "Ready" -Completed

#Display the table
#$table | Format-Table


$table | Export-Csv -Path $exported_log -NoTypeInformation
Write-Host "`nOriginal log: $logsource" -ForegroundColor Yellow 
Write-Host "Parsered log: $exported_log`n" -ForegroundColor Yellow 


# Ask user if wants to open web-page where O365 detailed log is

Write-host "Would you like to open in browser detailed O365-log properties webpage (Microsoft's)?" -ForegroundColor Yellow 
    $Readhost = Read-Host " ( y / n ) " 
    Switch ($ReadHost) 
     { 
       Y {Write-host "Yes,opening"; Start-Process "https://support.office.com/en-us/article/detailed-properties-in-the-office-365-audit-log-ce004100-9e7f-443e-942b-9b04098fcfc3"} 
       N {Write-Host "No"; $PublishSettings=$false} 
       Default {Write-Host "Default, opening"; Start-Process "https://support.office.com/en-us/article/detailed-properties-in-the-office-365-audit-log-ce004100-9e7f-443e-942b-9b04098fcfc3"} 
     } 


# Ask user if wants to open Folder of Parsered-csv

Write-host "Would you like to open Folder of End-Product ie. Parsered-csv?" -ForegroundColor Yellow 
    $Readhost = Read-Host " ( y / n ) " 
    Switch ($ReadHost) 
     { 
       Y {Write-host "Yes,opening"; Invoke-Item $logdirectory} 
       N {Write-Host "No"; $PublishSettings=$false} 
       Default {Write-Host "Default, opening"; Invoke-Item $logdirectory} 
     }