forked from T0pCyber/hawk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHawk.psm1
1807 lines (1482 loc) · 70.8 KB
/
Hawk.psm1
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
999
1000
#############################################################################################
# DISCLAIMER: #
# #
# THE SAMPLE SCRIPTS ARE NOT SUPPORTED UNDER ANY MICROSOFT STANDARD SUPPORT #
# PROGRAM OR SERVICE. THE SAMPLE SCRIPTS ARE PROVIDED AS IS WITHOUT WARRANTY #
# OF ANY KIND. MICROSOFT FURTHER DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING, WITHOUT #
# LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR OF FITNESS FOR A PARTICULAR #
# PURPOSE. THE ENTIRE RISK ARISING OUT OF THE USE OR PERFORMANCE OF THE SAMPLE SCRIPTS #
# AND DOCUMENTATION REMAINS WITH YOU. IN NO EVENT SHALL MICROSOFT, ITS AUTHORS, OR #
# ANYONE ELSE INVOLVED IN THE CREATION, PRODUCTION, OR DELIVERY OF THE SCRIPTS BE LIABLE #
# FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS #
# PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) #
# ARISING OUT OF THE USE OF OR INABILITY TO USE THE SAMPLE SCRIPTS OR DOCUMENTATION, #
# EVEN IF MICROSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES #
#############################################################################################
# ============== Utility Functions ==============
# Build a user OauthToken
Function Get-UserGraphAPIToken {
param (
[Parameter(Mandatory = $true)]
[string]$AppIDURL
)
# Make sure we have a connection to msol since we needed it for this
$null = Test-MSOLConnection
[string]$TenantName = (Get-MsolCompanyInformation).initialdomain
# Azure Powershell Client ID
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
# Set redirect URI for Azure PowerShell
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
# Set Resource URI to Azure Service Management API
$resourceAppIdURI = $AppIDURL
# Set Authority to Azure AD Tenant
$authority = "https://login.windows.net/$TenantName"
# TEMP
# Read in the username of the account that can access this
$Username = Read-Host "Please provide the upn of the account with access to read the Azure Audit logs:"
# Create AuthenticationContext tied to Azure AD Tenant
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$userid = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList $Username,"1"
# Acquire token
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri,"Always",$userid)
# Return Token
return $authResult
<#
.SYNOPSIS
Returning an Oauth Token for a given azure resource endpoint
.DESCRIPTION
Using the same authentication modules as msonline will generate an oauth token for a provided endpoint
Will use an existing connection if it is there or prompt from creds if needed
.OUTPUTS
Oauth Token
.EXAMPLE
Get-UserGraphAPIToken -AppIDURL "https://graph.windows.net"
Returns a user based token for graph.windows.net
#>
}
# Get the Location of an IP using the freegeoip.net rest API
Function Get-IPGeolocation {
Param
(
[Parameter(Mandatory = $true)]
$IPAddress
)
# If we don't have a HawkAppData variable then we need to read it in
if (!([bool](get-variable HawkAppData -erroraction silentlycontinue)))
{
Read-HawkAppData
}
# if there is no value of access_key then we need to get it from the user
if ($null -eq $HawkAppData.access_key)
{
Write-Host -ForegroundColor Green "
IpStack.com now requires an API access key to gather GeoIP information from their API.
Please get a Free access key from https://ipstack.com/ and provide it below.
"
# get the access key from the user
$Accesskey = Read-Host "ipstack.com accesskey"
# add the access key to the appdata file
Add-HawkAppData -name access_key -Value $Accesskey
}
else
{
$Accesskey = $HawkAppData.access_key
}
# Check the global IP cache and see if we already have the IP there
if ($IPLocationCache.ip -contains $IPAddress)
{
return ($IPLocationCache | Where-Object {$_.ip -eq $IPAddress } )
}
# If not then we need to look it up and populate it into the cache
else
{
# URI to pull the data from
$resource = "http://api.ipstack.com/" + $ipaddress + "?access_key=" + $Accesskey
# Return Data from web
$Error.Clear()
$geoip = Invoke-RestMethod -Method Get -URI $resource -ErrorAction SilentlyContinue
if (($Error.Count -gt 0) -or ($null -eq $geoip.type))
{
Out-LogFile ("Failed to retreive location for IP " + $IPAddress)
$hash = @{
IP = $IPAddress
CountryName = "Failed to Resolve"
Continent = "Unknown"
ContinentName = "Unknown"
City = "Unknown"
KnownMicrosoftIP = "Unknown"
}
}
else {
# Determine if this IP is known to be owned by Microsoft
[string]$isMSFTIP = Test-MicrosoftIP -IP $IPAddress -type $geoip.type
# Push return into a response object
$hash = @{
IP = $geoip.ip
CountryName = $geoip.country_name
Continent = $geoip.continent_code
ContinentName = $geoip.continent_name
City = $geoip.City
KnownMicrosoftIP = $isMSFTIP
}
$result = New-Object PSObject -Property $hash
}
# Push the result to the global IPLocationCache
[array]$Global:IPlocationCache += $result
# Return the result to the user
return $result
}
}
# Convert output from search-adminauditlog to be more human readable
Function Get-SimpleAdminAuditLog {
Param (
[Parameter(
Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)
]
$SearchResults
)
# Setup to process incomming results
Begin
{
# Make sure the array is null
[array]$ResultSet = $null
}
# Process thru what ever is comming into the script
Process
{
# Deal with each object in the input
$searchresults | ForEach-Object {
# Reset the result object
$Result = New-Object PSObject
# Get the alias of the User that ran the command
[string]$user = $_.caller
if ([string]::IsNullOrEmpty($user)) {$user = "***"}
else {$user = ($_.caller.split("/"))[-1]}
# Build the command that was run
$switches = $_.cmdletparameters
[string]$FullCommand = $_.cmdletname
# Get all of the switchs and add them in "human" form to the output
foreach ($parameter in $switches) {
# Format our values depending on what they are so that they are as close
# a match as possible for what would have been entered
switch -regex ($parameter.value) {
# If we have a multi value array put in then we need to break it out and add quotes as needed
'[;]' {
# Reset the formatted value string
$FormattedValue = $null
# Split it into an array
$valuearray = $switch.current.split(";")
# For each entry in the array add quotes if needed and add it to the formatted value string
$valuearray | ForEach-Object {
if ($_ -match "[ \t]") {$FormattedValue = $FormattedValue + "`"" + $_ + "`";"}
else {$FormattedValue = $FormattedValue + $_ + ";"}
}
# Clean up the trailing ;
$FormattedValue = $FormattedValue.trimend(";")
# Add our switch + cleaned up value to the command string
$FullCommand = $FullCommand + " -" + $parameter.name + " " + $FormattedValue
}
# If we have a value with spaces add quotes
'[ \t]' {$FullCommand = $FullCommand + " -" + $parameter.name + " `"" + $switch.current + "`""}
# If we have a true or false format them with :$ in front ( -allow:$true )
'^True$|^False$' {$FullCommand = $FullCommand + " -" + $parameter.name + ":`$" + $switch.current}
# Otherwise just put the switch and the value
default {$FullCommand = $FullCommand + " -" + $parameter.name + " " + $switch.current}
}
}
# Format our modified object
if ([string]::IsNullOrEmpty($_.objectModified)) {$ObjModified = ""}
else {
$ObjModified = ($_.objectmodified.split("/"))[-1]
$ObjModified = ($ObjModified.split("\"))[-1]
}
# Get just the name of the cmdlet that was run
[string]$cmdlet = $_.CmdletName
# Build the result object to return our values
$Result | Add-Member -MemberType NoteProperty -Value $user -Name Caller
$Result | Add-Member -MemberType NoteProperty -Value $cmdlet -Name Cmdlet
$Result | Add-Member -MemberType NoteProperty -Value $FullCommand -Name FullCommand
$Result | Add-Member -MemberType NoteProperty -Value ($_.rundate).ToUniversalTime() -Name 'RunDate(UTC)'
$Result | Add-Member -MemberType NoteProperty -Value $ObjModified -Name ObjectModified
# Add the object to the array to be returned
$ResultSet = $ResultSet + $Result
}
}
# Final steps
End {
# Return the array set
Return $ResultSet
}
}
# Make sure we get back all of the unified audit log results for the search we are doing
Function Get-AllUnifiedAuditLogEntry {
param
(
[Parameter(Mandatory = $true)]
[string]$UnifiedSearch,
[datetime]$StartDate = $Hawk.StartDate,
[datetime]$EndDate = $Hawk.EndDate
)
# Validate the incoming search command
if (($UnifiedSearch -match "-StartDate") -or ($UnifiedSearch -match "-EndDate") -or ($UnifiedSearch -match "-SessionCommand") -or ($UnifiedSearch -match "-ResultSize") -or ($UnifiedSearch -match "-SessionId")) {
Out-LogFile "Do not include any of the following in the Search Command"
Out-LogFile "-StartDate, -EndDate, -SessionCommand, -ResultSize, -SessionID"
Write-Error -Message "Unable to process search command, switch in UnifiedSearch that is handled by this cmdlet specified" -ErrorAction Stop
}
# Make sure key variables are null
[string]$cmd = $null
# build our search command to execute
$cmd = $UnifiedSearch + " -StartDate `'" + $StartDate + "`' -EndDate `'" + $EndDate + "`' -SessionCommand ReturnLargeSet -resultsize 1000 -sessionid " + (Get-Date -UFormat %H%M%S)
Out-LogFile ("Running Unified Audit Log Search")
Out-Logfile $cmd
# Run the initial command
$Output = $null
# $Output = New-Object System.Collections.ArrayList
# Setup our run variable
$Run = $true
# Since we have more than 1k results we need to keep returning results until we have them all
while ($Run)
{
$Output += (Invoke-Expression $cmd)
# Check for null results if so warn and stop
if ($null -eq $Output)
{
Out-LogFile ("[WARNING] - Unified Audit log returned no results.")
$Run = $false
}
# Else continue
else
{
# Sort our result set to make sure the higest number is in the last position
$Output = $Output | Sort-Object -Property ResultIndex
# if total result count returned is 0 then we should warn and stop
if ($Output[-1].ResultCount -eq 0)
{
Out-LogFile ("[WARNING] - Returned Result count was 0")
$Run = $false
}
# if our resultindex = our resultcount then we have everything and should stop
elseif ($Output[-1].Resultindex -ge $Output[-1].ResultCount)
{
Out-LogFile ("Retrieved all results.")
$Run = $false
}
# Output the current progress
Out-LogFile ("Retrieved:" + $Output[-1].ResultIndex.tostring().PadRight(5, " ") + " Total: " + $Output[-1].ResultCount)
}
}
# Convert our list to an array and return it
[array]$Output = $Output
return $Output
}
# Writes output to a log file with a time date stamp
Function Out-LogFile {
Param
(
[string]$string,
[switch]$action,
[switch]$notice,
[switch]$silentnotice
)
# Make sure we have the Hawk Global Object
if ([string]::IsNullOrEmpty($Hawk.FilePath)) {
Initialize-HawkGlobalObject
}
# Get our log file path
$LogFile = Join-path $Hawk.FilePath "Hawk.log"
$ScreenOutput = $true
$LogOutput = $true
# Get the current date
[string]$date = Get-Date -Format G
# Deal with each switch and what log string it should put out and if any special output
# Action indicates that we are starting to do something
if ($action) {
[string]$logstring = ( "[" + $date + "] - [ACTION] - " + $string)
}
# If notice is true the we should write this to intersting.txt as well
elseif ($notice) {
[string]$logstring = ( "[" + $date + "] - ## INVESTIGATE ## - " + $string)
# Build the file name for Investigate stuff log
[string]$InvestigateFile = Join-Path (Split-Path $LogFile -Parent) "_Investigate.txt"
$logstring | Out-File -FilePath $InvestigateFile -Append
}
# For silent we need to supress the screen output
elseif ($silentnotice) {
[string]$logstring = ( "Addtional Information: " + $string)
# Build the file name for Investigate stuff log
[string]$InvestigateFile = Join-Path (Split-Path $LogFile -Parent) "_Investigate.txt"
$logstring | Out-File -FilePath $InvestigateFile -Append
# Supress screen and normal log output
$ScreenOutput = $false
$LogOutput = $false
}
# Normal output
else {
[string]$logstring = ( "[" + $date + "] - " + $string)
}
# Write everything to our log file
if ($LogOutput) {
$logstring | Out-File -FilePath $LogFile -Append
}
# Output to the screen
if ($ScreenOutput) {
Write-Information -MessageData $logstring -InformationAction Continue
}
}
# Adds the data to an XML report
Function Out-Report {
Param
(
[Parameter(Mandatory=$true)]
[string]$Identity,
[Parameter(Mandatory=$true)]
[string]$Property,
[Parameter(Mandatory=$true)]
[string]$Value,
[string]$Description,
[string]$State,
[string]$Link
)
# Force the case on all our critical values
#$Property = $Property.tolower()
#$Identity = $Identity.tolower()
# Set our output path
# Single report file for all outputs user/tenant/etc.
# This might change in the future???
$reportpath = Join-path $hawk.filepath report.xml
# Switch statement to handle the state to color mapping
switch ($State)
{
Warning {$highlighcolor = "#FF8000"}
Success {$highlighcolor = "Green"}
Error {$highlighcolor = "#8A0808"}
default {$highlighcolor = "Light Grey"}
}
# Check if we have our XSL file in the output directory
$xslpath = Join-path $hawk.filepath Report.xsl
if (Test-Path $xslpath ){}
else
{
# Copy the XSL file into the current output path
$sourcepath = join-path (split-path (Get-Module Hawk).path) report.xsl
if (test-path $sourcepath)
{
Copy-Item -Path $sourcepath -Destination $hawk.filepath
}
# If we couldn't find it throw and error and stop
else
{
Write-Error ("Unable to find transform file " + $sourcepath) -ErrorAction Stop
}
}
# See if we have already created a report file
# If so we need to import it
if (Test-path $reportpath)
{
$reportxml = $null
[xml]$reportxml = get-content $reportpath
}
# Since we have NOTHING we will create a new XML and just add / save / and exit
else
{
Out-LogFile ("Creating new Report file" + $reportpath)
# Create the report xml object
$reportxml = New-Object xml
# Create the xml declaraiton and stylesheet
$reportxml.AppendChild($reportxml.CreateXmlDeclaration("1.0",$null,$null)) | Out-Null
# $xmlstyle = "type=`"text/xsl`" href=`"https://csshawk.azurewebsites.net/report.xsl`""
# $reportxml.AppendChild($reportxml.CreateProcessingInstruction("xml-stylesheet",$xmlstyle)) | Out-Null
# Create all of the needed elements
$newreport = $reportxml.CreateElement("report")
$newentity = $reportxml.CreateElement("entity")
$newentityidentity = $reportxml.CreateElement("identity")
$newentityproperty = $reportxml.CreateElement("property")
$newentitypropertyname = $reportxml.CreateElement("name")
$newentitypropertyvalue = $reportxml.CreateElement("value")
$newentitypropertycolor = $reportxml.CreateElement("color")
$newentitypropertydescription = $reportxml.CreateElement("description")
$newentitypropertylink = $reportxml.CreateElement("link")
### Build the XML from the bottom up ###
# Add the property values to the entity object
$newentityproperty.AppendChild($newentitypropertyname) | Out-Null
$newentityproperty.AppendChild($newentitypropertyvalue) | Out-Null
$newentityproperty.AppendChild($newentitypropertycolor) | Out-Null
$newentityproperty.AppendChild($newentitypropertydescription) | Out-Null
$newentityproperty.AppendChild($newentitypropertylink) | Out-Null
# Set the values for the leaf nodes we just added
$newentityproperty.name = $Property
$newentityproperty.value = $Value
$newentityproperty.color = $highlighcolor
$newentityproperty.description = $Description
$newentityproperty.link = $Link
# Add the identity element to the entity and set its value
$newentity.AppendChild($newentityidentity) | Out-Null
$newentity.identity = $Identity
# Add the property to the entity
$newentity.AppendChild($newentityproperty) | Out-Null
# Add the entity to the report
$newreport.AppendChild($newentity) | Out-Null
# Add the whole thing to the xml root
$reportxml.AppendChild($newreport) | Out-Null
# save the xml
$reportxml.save($reportpath)
}
# We need to check if an entity with the ID $identity already exists
if ($reportxml.report.entity.identity.contains($Identity)){}
# Didn't find and entity so we are going to create the whole thing and once
else
{
# Create all of the needed elements
$newentity = $reportxml.CreateElement("entity")
$newentityidentity = $reportxml.CreateElement("identity")
$newentityproperty = $reportxml.CreateElement("property")
$newentitypropertyname = $reportxml.CreateElement("name")
$newentitypropertyvalue = $reportxml.CreateElement("value")
$newentitypropertycolor = $reportxml.CreateElement("color")
$newentitypropertydescription = $reportxml.CreateElement("description")
$newentitypropertylink = $reportxml.CreateElement("link")
### Build the XML from the bottom up ###
# Add the property values to the entity object
$newentityproperty.AppendChild($newentitypropertyname) | Out-Null
$newentityproperty.AppendChild($newentitypropertyvalue) | Out-Null
$newentityproperty.AppendChild($newentitypropertycolor) | Out-Null
$newentityproperty.AppendChild($newentitypropertydescription) | Out-Null
$newentityproperty.AppendChild($newentitypropertylink) | Out-Null
# Set the values for the leaf nodes we just added
$newentityproperty.name = $Property
$newentityproperty.value = $Value
$newentityproperty.color = $highlighcolor
$newentityproperty.description = $Description
$newentityproperty.link = $Link
# Add them together and set values
$newentity.AppendChild($newentityidentity) | Out-Null
$newentity.identity = $Identity
$newentity.AppendChild($newentityproperty) | Out-Null
# Add the new entity stub back to the XML
$reportxml.report.AppendChild($newentity) | Out-Null
}
# Now we need to check for the property we are looking to add
# The property exists so we need to update it
if (($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).property.name.contains($Property))
{
### Update existing property ###
(($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).property | Where-Object {$_.name -eq $Property}).value = $Value
(($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).property | Where-Object {$_.name -eq $Property}).color = $highlighcolor
(($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).property | Where-Object {$_.name -eq $Property}).description = $Description
(($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).property | Where-Object {$_.name -eq $Property}).link = $Link
}
# We need to add the property to the entity
else
{
### Add new property to existing Entity ###
# Create the elements that we are going to need
$newproperty = $reportxml.CreateElement("property")
$newname = $reportxml.CreateElement("name")
$newvalue = $reportxml.CreateElement("value")
$newcolor = $reportxml.CreateElement("color")
$newdescription = $reportxml.CreateElement("description")
$newlink = $reportxml.CreateElement("link")
# Add on all of the elements
$newproperty.AppendChild($newname) | Out-Null
$newproperty.AppendChild($newvalue) | Out-Null
$newproperty.AppendChild($newcolor) | Out-Null
$newproperty.AppendChild($newdescription) | Out-Null
$newproperty.AppendChild($newlink) | Out-Null
# Set the values
$newproperty.name = $Property
$newproperty.value = $Value
$newproperty.color = $highlighcolor
$newproperty.description = $Description
$newproperty.link = $Link
# Add the newly created property to the entity
($reportxml.report.entity | Where-Object {$_.identity -eq $Identity}).AppendChild($newproperty) | Out-Null
}
# Make sure we save our changes
$reportxml.Save($reportpath)
# Convert it to HTML and Save
Convert-ReportToHTML -Xml $reportpath -Xsl $xslpath
}
# Sends the output of a cmdlet to a txt file and a clixml file
Function Out-MultipleFileType {
param
(
[Parameter (ValueFromPipeLine = $true)]
$Object,
[Parameter (Mandatory = $true)]
[string]$FilePrefix,
[string]$User,
[switch]$Append = $false,
[switch]$xml = $false,
[Switch]$csv = $false,
[Switch]$txt = $false,
[Switch]$Notice
)
begin {
# If no file types were specified then we need to error out here
if (($xml -eq $false) -and ($csv -eq $false) -and ($txt -eq $false)) {
Out-LogFile "[ERROR] - No output type specified on object"
Write-Error -Message "No output type specified on object" -ErrorAction Stop
}
# Null out our array
[array]$AllObject = $null
# Set the output path
if ([string]::IsNullOrEmpty($User)) {
$path = join-path $Hawk.filepath "\Tenant"
# Test the path if it is there do nothing otherwise create it
if (test-path $path) {}
else {
Out-LogFile ("Making output directory for Tenant " + $Path)
$Null = New-Item $Path -ItemType Directory
}
}
else {
$path = join-path $Hawk.filepath $user
# Test the path if it is there do nothing otherwise create it
if (test-path $path) {}
else {
Out-LogFile ("Making output directory for user " + $Path)
$Null = New-Item $Path -ItemType Directory
}
}
}
process {
# Collect up all of the incoming data into a single object for processing and output
[array]$AllObject = $AllObject + $Object
}
end {
if ($null -eq $AllObject) {
Out-LogFile "No Data Found"
}
else {
# Determine what file type or types we need to write this object into and output it
# Output XML File
if ($xml -eq $true) {
# lets put the xml files in a seperate directory to not clutter things up
$xmlpath = Join-path $Path XML
if (Test-path $xmlPath) {}
else {
Out-LogFile ("Making output directory for xml files " + $xmlPath)
$null = New-Item $xmlPath -ItemType Directory
}
# Build the file name and write it out
$filename = Join-Path $xmlPath ($FilePrefix + ".xml")
Out-LogFile ("Writing Data to " + $filename)
# Output our objects to clixml
$AllObject | Export-Clixml $filename
# If notice is set we need to write the file name to _Investigate.txt
if ($Notice) {Out-LogFile -string ($filename) -silentnotice}
}
# Output CSV file
if ($csv -eq $true) {
# Build the file name
$filename = Join-Path $Path ($FilePrefix + ".csv")
# If we have -append then append the data
if ($append) {
Out-LogFile ("Appending Data to " + $filename)
# Write it out to csv making sture to append
$AllObject | Export-Csv $filename -NoTypeInformation -Append
}
# Otherwise overwrite
else {
Out-LogFile ("Writing Data to " + $filename)
$AllObject | Export-Csv $filename -NoTypeInformation
}
# If notice is set we need to write the file name to _Investigate.txt
if ($Notice) {Out-LogFile -string ($filename) -silentnotice}
}
# Output Text files
if ($txt -eq $true) {
# Build the file name
$filename = Join-Path $Path ($FilePrefix + ".txt")
# If we have -append then append the data
if ($Append) {
Out-LogFile ("Appending Data to " + $filename)
$AllObject | Format-List * | Out-File $filename -Append
}
# Otherwise overwrite
else {
Out-LogFile ("Writing Data to " + $filename)
$AllObject | Format-List * | Out-File $filename
}
# If notice is set we need to write the file name to _Investigate.txt
if ($Notice) {Out-LogFile -string ($filename) -silentnotice}
}
}
}
}
# Returns a collection of unique objects filtered by a single property
Function Select-UniqueObject {
param
(
[Parameter(Mandatory = $true)]
[array]$ObjectArray,
[Parameter(Mandatory = $true)]
[string]$Property
)
# Null out our output array
[array]$Output = $null
# Get the ID of the unique objects based ont he sort property
[array]$UniqueObjectID = $ObjectArray | Select-Object -Unique -ExpandProperty $Property
# Select the whole object based on the unique names found
foreach ($Name in $UniqueObjectID) {
[array]$Output = $Output + ($ObjectArray | Where-Object {$_.($Property) -eq $Name} | Select-Object -First 1)
}
return $Output
}
# Test if we are connected to the compliance center online and connect if now
Function Test-CCOConnection {
Write-Output "Not yet implemented"
}
# Test if we are connected to Exchange Online and connect if not
Function Test-EXOConnection {
try
{
$null = Get-OrganizationConfig -erroraction stop
}
catch [System.Management.Automation.CommandNotFoundException] {
Out-LogFile "[ERROR] - Not Connected to Exchange Online"
Write-Output "`nPlease connect to Exchange Online Prior to running"
Write-Output "`nStandard connection method"
Write-Output "https://technet.microsoft.com/en-us/library/jj984289(v=exchg.160).aspx"
Write-Output "`nFor Accounts protected by MFA"
Write-Output "https://technet.microsoft.com/en-us/library/mt775114(v=exchg.160).aspx `n"
break
}
}
# Test if we are connected to MSOL and connect if we are not
Function Test-MSOLConnection {
try {$null = Get-MsolCompanyInformation -ErrorAction Stop}
catch [Microsoft.Online.Administration.Automation.MicrosoftOnlineException] {
# Write to the screen if we don't have a log file path yet
if ([string]::IsNullOrEmpty($Hawk.Logfile)) {
Write-Output "[ERROR] - Please connect to MSOL prior to running this cmdlet"
Write-Output "https://docs.microsoft.com/en-us/powershell/module/msonline/?view=azureadps-1.0#msonline `n"
}
# Otherwise output to the log file
else {
Out-LogFile "[ERROR] - Please connect to MSOL prior to running this cmdlet"
Out-LogFile "https://docs.microsoft.com/en-us/powershell/module/msonline/?view=azureadps-1.0#msonline `n"
}
break
}
}
# Test if we have a connection with the AzureAD Cmdlets
Function Test-AzureADConnection {
$TestModule = Get-Module AzureAD -ListAvailable -ErrorAction SilentlyContinue
$MinimumVersion = New-Object -TypeName Version -ArgumentList "2.0.0.131"
if ($null -eq $TestModule) {
Out-LogFile "Please Install the AzureAD Module with the following command:"
Out-LogFile "Install-Module AzureAD"
break
}
# Since we are not null pull the highest version
else {
$TestModuleVersion = ($TestModule | Sort-Object -Property Version -Descending)[0].version
}
# Test the version we need at least 2.0.0.131
if ($TestModuleVersion -lt $MinimumVersion) {
Out-LogFile ("AzureAD Module Installed Version: " + $TestModuleVersion)
Out-LogFile ("Miniumum Required Version: " + $MinimumVersion)
Out-LogFile "Please update the module with: Update-Module AzureAD"
break
}
# Do nothing
else {}
try
{
$Null = Get-AzureADTenantDetail -ErrorAction Stop
}
catch [Microsoft.Open.Azure.AD.CommonLibrary.AadNeedAuthenticationException] {
Out-LogFile "Please connect to AzureAD prior to running this cmdlet"
Out-LogFile "Connect-AzureAD"
break
}
}
# Check to see if a recipient object was created since our start date
Function Test-RecipientAge {
Param([string]$RecipientID)
$recipient = Get-Recipient -Identity $RecipientID -erroraction SilentlyContinue
# Verify that we got something back
if ($null -eq $recipient) {
Return 2
}
# If the date created is newer than our StartDate return non zero (1)
elseif ($recipient.whencreated -gt $Hawk.StartDate) {
Return 1
}
# If it is older than the start date return 0
else {
Return 0
}
}
# Determine if an IP listed in on the O365 XML list
Function Test-MicrosoftIP {
param
(
[Parameter(Mandatory = $true)]
[string]$IPToTest,
[Parameter(Mandatory=$true)]
[string]$Type
)
# Check if we have imported all of our IP Addresses
if ($null -eq $MSFTIPList) {
Out-Logfile "Building MSFTIPList"
# Load our networking dll pulled from https://github.com/lduchosal/ipnetwork
[string]$dll = join-path (Split-path (((get-module Hawk)[0]).path) -Parent) "System.Net.IPNetwork.dll"
$Error.Clear()
Out-LogFile ("Loading Networking functions from " + $dll)
[Reflection.Assembly]::LoadFile($dll)
if ($Error.Count -gt 0) {
Out-Logfile "[WARNING] - DLL Failed to load can't process IPs"
Return "Unknown"
}
$Error.clear()
# Read in the XML file from the internet
Out-LogFile ("Reading XML for MSFT IP Addresses https://support.content.office.net/en-us/static/O365IPAddresses.xml")
[xml]$msftxml = (Invoke-webRequest -Uri https://support.content.office.net/en-us/static/O365IPAddresses.xml).content
if ($Error.Count -gt 0) {
Out-Logfile "[WARNING] - Unable to retrieve XML file"
Return "Unknown"
}
# Make sure our arrays are null
[array]$ipv6 = $Null
[array]$ipv4 = $Null
# Go thru each product in the XML
foreach ($Product in $msftxml.products.product) {
# For each product look thru the list of ip addresses
foreach ($addresslist in $Product.addresslist) {
# If IPv6 add to that list
if ($addresslist.type -eq "Ipv6") {
$ipv6 += $addresslist.address
}
# if IPv4 add to that list
elseif ($addresslist.type -eq "IPv4") {
$ipv4 += $addresslist.address
}
# if anything else ignore
else {}
}
}
# Now we need to filter out the duplicate addresses in the lists
$ipv6 = $ipv6 | select-object -Unique
$ipv4 = $ipv4 | Select-Object -Unique
Out-LogFile ("Found " + $ipv6.Count + " unique MSFT IPv6 address ranges")
Out-LogFile ("Found " + $ipv4.count + " unique MSFT IPv4 address ranges")
# New up using our networking dll we need to pull these all in as network objects
foreach ($ip in $ipv6) {
[array]$ipv6objects += [System.Net.IPNetwork]::Parse($ip)
}
foreach ($ip in $ipv4) {
[array]$ipv4objects += [System.Net.IPNetwork]::Parse($ip)
}
# Now create our output object
$output = $Null
$output = New-Object -TypeName PSObject
$output | Add-Member -MemberType NoteProperty -Value $ipv6objects -Name IPv6Objects
$output | Add-Member -MemberType NoteProperty -Value $ipv4objects -Name IPv4Objects
# Create a global variable to hold our IP list so we can keep using it
Out-LogFile "Creating global variable `$MSFTIPList"
New-Variable -Name MSFTIPList -Value $output -Scope global
}
# Determine if we have an ipv6 or ipv4 address
if ($Type -like "ipv6")
{
# Compare to the IPv6 list
[int]$i = 0
[int]$count = $MSFTIPList.ipv6objects.count - 1
# Compare each IP to the ip networks to see if it is in that network
# If we get back a True or we are beyond the end of the list then stop
do {
# Test the IP
$parsedip = [System.Net.IPAddress]::Parse($IPToTest)
$test = [System.Net.IPNetwork]::Contains($MSFTIPList.ipv6objects[$i], $parsedip)
$i++
}
until(($test -eq $true) -or ($i -gt $count))
# Return the value of test true = in MSFT network
Return $test
}
else
{
# Compare to the IPv4 list
[int]$i = 0
[int]$count = $MSFTIPList.ipv4objects.count - 1
# Compare each IP to the ip networks to see if it is in that network
# If we get back a True or we are beyond the end of the list then stop
do
{
# Test the IP
$parsedip = [System.Net.IPAddress]::Parse($IPToTest)
$test = [System.Net.IPNetwork]::Contains($MSFTIPList.ipv4objects[$i], $parsedip)
$i++
}
until(($test -eq $true) -or ($i -gt $count))
# Return the value of test true = in MSFT network