Skip to content

Commit 70937b1

Browse files
authored
Merge branch 'KelvinTegelaar:master' into master
2 parents 14af20e + 905b3cb commit 70937b1

File tree

163 files changed

+15415
-4726
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

163 files changed

+15415
-4726
lines changed

ConversionTable.csv

Lines changed: 4146 additions & 938 deletions
Large diffs are not rendered by default.

DomainAnalyser_All/run.ps1

Lines changed: 30 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ try {
1010
$ValidResolvers = @('Google', 'CloudFlare', 'Quad9')
1111
if ($ValidResolvers -contains $Config.Resolver) {
1212
$Resolver = $Config.Resolver
13-
}
14-
else {
13+
} else {
1514
$Resolver = 'Google'
1615
$Config = @{
1716
PartitionKey = 'Domains'
@@ -20,8 +19,7 @@ try {
2019
}
2120
Add-CIPPAzDataTableEntity @ConfigTable -Entity $Config -Force
2221
}
23-
}
24-
catch {
22+
} catch {
2523
$Resolver = 'Google'
2624
}
2725
Set-DnsResolver -Resolver $Resolver
@@ -30,8 +28,7 @@ $Domain = $DomainObject.rowKey
3028

3129
try {
3230
$Tenant = $DomainObject.TenantDetails | ConvertFrom-Json -ErrorAction Stop
33-
}
34-
catch {
31+
} catch {
3532
$Tenant = @{Tenant = 'None' }
3633
}
3734

@@ -45,6 +42,7 @@ $Result = [PSCustomObject]@{
4542
ExpectedSPFRecord = ''
4643
ActualSPFRecord = ''
4744
SPFPassAll = ''
45+
ActualMXRecords = ''
4846
MXPassTest = ''
4947
DMARCPresent = ''
5048
DMARCFullPolicy = ''
@@ -82,6 +80,7 @@ $MXRecord = Read-MXRecord -Domain $Domain -ErrorAction Stop
8280

8381
$Result.ExpectedSPFRecord = $MXRecord.ExpectedInclude
8482
$Result.MXPassTest = $false
83+
$Result.ActualMXRecords = $MXRecord.Records
8584

8685
# Check fail counts to ensure all tests pass
8786
#$MXWarnCount = $MXRecord.ValidationWarns | Measure-Object | Select-Object -ExpandProperty Count
@@ -90,15 +89,13 @@ $MXFailCount = $MXRecord.ValidationFails | Measure-Object | Select-Object -Expan
9089
if ($MXFailCount -eq 0) {
9190
$Result.MXPassTest = $true
9291
$ScoreDomain += $Scores.MXRecommended
93-
}
94-
else {
92+
} else {
9593
$ScoreExplanation.Add('MX record did not pass validation') | Out-Null
9694
}
9795

9896
if ([string]::IsNullOrEmpty($MXRecord.MailProvider)) {
9997
$Result.MailProvider = 'Unknown'
100-
}
101-
else {
98+
} else {
10299
$Result.MailProvider = $MXRecord.MailProvider.Name
103100
}
104101

@@ -109,22 +106,19 @@ try {
109106
$Result.ActualSPFRecord = $SPFRecord.Record
110107
if ($SPFRecord.RecordCount -eq 1) {
111108
$ScoreDomain += $Scores.SPFPresent
112-
}
113-
else {
109+
} else {
114110
$ScoreExplanation.Add('Multiple SPF records detected') | Out-Null
115111
}
116-
}
117-
else {
112+
} else {
118113
$Result.ActualSPFRecord = 'No SPF Record'
119114
$ScoreExplanation.Add('No SPF Record Found') | Out-Null
120115
}
121-
}
122-
catch {
116+
} catch {
123117
$Message = 'SPF Exception: {0} line {1} - {2}' -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.Exception.Message
124118
Write-LogMessage -API 'DomainAnalyser' -tenant $tenant.tenant -message $Message -sev Error
125119
throw $Message
126120
}
127-
121+
128122
# Check SPF Record
129123
$Result.SPFPassAll = $false
130124

@@ -135,8 +129,7 @@ $SPFFailCount = $SPFRecord.ValidationFails | Measure-Object | Select-Object -Exp
135129
if ($SPFFailCount -eq 0) {
136130
$ScoreDomain += $Scores.SPFCorrectAll
137131
$Result.SPFPassAll = $true
138-
}
139-
else {
132+
} else {
140133
$ScoreExplanation.Add('SPF record did not pass validation') | Out-Null
141134
}
142135

@@ -147,19 +140,18 @@ try {
147140
If ([string]::IsNullOrEmpty($DMARCPolicy.Record)) {
148141
$Result.DMARCPresent = $false
149142
$ScoreExplanation.Add('No DMARC Records Found') | Out-Null
150-
}
151-
else {
143+
} else {
152144
$Result.DMARCPresent = $true
153145
$ScoreDomain += $Scores.DMARCPresent
154146

155-
$Result.DMARCFullPolicy = $DMARCResults.Record
156-
if ($DMARCPolicy.Policy -eq 'reject' -and $DMARCPolicy.SubdomainPolicy -eq 'reject') {
147+
$Result.DMARCFullPolicy = $DMARCPolicy.Record
148+
if ($DMARCPolicy.Policy -eq 'reject' -and $DMARCPolicy.SubdomainPolicy -eq 'reject') {
157149
$Result.DMARCActionPolicy = 'Reject'
158150
$ScoreDomain += $Scores.DMARCSetReject
159151
}
160-
if ($DMARCPolicy.Policy -eq 'none') {
152+
if ($DMARCPolicy.Policy -eq 'none') {
161153
$Result.DMARCActionPolicy = 'None'
162-
$ScoreExplanation.Add('DMARC is not being enforced') | Out-Null
154+
$ScoreExplanation.Add('DMARC is not being enforced') | Out-Null
163155
}
164156
if ($DMARCPolicy.Policy -eq 'quarantine') {
165157
$Result.DMARCActionPolicy = 'Quarantine'
@@ -171,23 +163,20 @@ try {
171163
if ($ReportEmailCount -gt 0) {
172164
$Result.DMARCReportingActive = $true
173165
$ScoreDomain += $Scores.DMARCReportingActive
174-
}
175-
else {
166+
} else {
176167
$Result.DMARCReportingActive = $False
177168
$ScoreExplanation.Add('DMARC Reporting not Configured') | Out-Null
178169
}
179170

180171
if ($DMARCPolicy.Percent -eq 100) {
181172
$Result.DMARCPercentagePass = $true
182173
$ScoreDomain += $Scores.DMARCPercentageGood
183-
}
184-
else {
174+
} else {
185175
$Result.DMARCPercentagePass = $false
186-
$ScoreExplanation.Add('DMARC Not Checking All Messages') | Out-Null
176+
$ScoreExplanation.Add('DMARC Not Checking All Messages') | Out-Null
187177
}
188178
}
189-
}
190-
catch {
179+
} catch {
191180
$Message = 'DMARC Exception: {0} line {1} - {2}' -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.Exception.Message
192181
Write-LogMessage -API 'DomainAnalyser' -tenant $tenant.tenant -message $Message -sev Error
193182
throw $Message
@@ -201,13 +190,11 @@ try {
201190
if (($DNSSECFailCount + $DNSSECWarnCount) -eq 0) {
202191
$Result.DNSSECPresent = $true
203192
$ScoreDomain += $Scores.DNSSECPresent
204-
}
205-
else {
193+
} else {
206194
$Result.DNSSECPresent = $false
207-
$ScoreExplanation.Add('DNSSEC Not Configured or Enabled') | Out-Null
195+
$ScoreExplanation.Add('DNSSEC Not Configured or Enabled') | Out-Null
208196
}
209-
}
210-
catch {
197+
} catch {
211198
$Message = 'DNSSEC Exception: {0} line {1} - {2}' -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.Exception.Message
212199
Write-LogMessage -API 'DomainAnalyser' -tenant $tenant.tenant -message $Message -sev Error
213200
throw $Message
@@ -216,27 +203,26 @@ catch {
216203
# DKIM Check
217204
try {
218205
$DkimParams = @{
219-
Domain = $Domain
206+
Domain = $Domain
207+
FallbackToMicrosoftSelectors = $true
220208
}
221209
if (![string]::IsNullOrEmpty($DomainObject.DkimSelectors)) {
222210
$DkimParams.Selectors = $DomainObject.DkimSelectors | ConvertFrom-Json
223211
}
224212

225213
$DkimRecord = Read-DkimRecord @DkimParams -ErrorAction Stop
226-
214+
227215
$DkimRecordCount = $DkimRecord.Records | Measure-Object | Select-Object -ExpandProperty Count
228216
$DkimFailCount = $DkimRecord.ValidationFails | Measure-Object | Select-Object -ExpandProperty Count
229217
#$DkimWarnCount = $DkimRecord.ValidationWarns | Measure-Object | Select-Object -ExpandProperty Count
230218
if ($DkimRecordCount -gt 0 -and $DkimFailCount -eq 0) {
231219
$Result.DKIMEnabled = $true
232220
$ScoreDomain += $Scores.DKIMActiveAndWorking
233-
}
234-
else {
221+
} else {
235222
$Result.DKIMEnabled = $false
236-
$ScoreExplanation.Add('DKIM Not Configured') | Out-Null
223+
$ScoreExplanation.Add('DKIM Not Configured') | Out-Null
237224
}
238-
}
239-
catch {
225+
} catch {
240226
$Message = 'DKIM Exception: {0} line {1} - {2}' -f $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.Exception.Message
241227
Write-LogMessage -API 'DomainAnalyser' -tenant $tenant.tenant -message $Message -sev Error
242228
throw $Message

Durable_BECRun/run.ps1

Lines changed: 37 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,45 @@ param($Context)
22
#$Context does not allow itself to be cast to a pscustomobject for some reason, so we convert
33
$context = $Context | ConvertTo-Json | ConvertFrom-Json
44
$APIName = $TriggerMetadata.FunctionName
5-
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"
5+
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
66
$TenantFilter = $Context.input.tenantfilter
77
$SuspectUser = $Context.input.userid
88
$UserName = $Context.input.username
99
Write-Host "Working on $UserName"
1010
try {
1111
$startDate = (Get-Date).AddDays(-7)
1212
$endDate = (Get-Date)
13-
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet "Get-AdminAuditLogConfig").UnifiedAuditLogIngestionEnabled
13+
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-AdminAuditLogConfig').UnifiedAuditLogIngestionEnabled
1414
$7dayslog = if ($auditLog -eq $false) {
15-
$ExtractResult = "AuditLog is disabled. Cannot perform full analysis"
16-
}
17-
else {
15+
$ExtractResult = 'AuditLog is disabled. Cannot perform full analysis'
16+
} else {
1817
$sessionid = Get-Random -Minimum 10000 -Maximum 99999
1918
$operations = @(
20-
"New-InboxRule",
21-
"Set-InboxRule",
22-
"UpdateInboxRules",
23-
"Remove-MailboxPermission",
24-
"Add-MailboxPermission",
25-
"UpdateCalendarDelegation",
26-
"AddFolderPermissions",
27-
"MailboxLogin",
28-
"UserLoggedIn"
19+
'New-InboxRule',
20+
'Set-InboxRule',
21+
'UpdateInboxRules',
22+
'Remove-MailboxPermission',
23+
'Add-MailboxPermission',
24+
'UpdateCalendarDelegation',
25+
'AddFolderPermissions',
26+
'MailboxLogin',
27+
'UserLoggedIn'
2928
)
3029
$startDate = (Get-Date).AddDays(-7)
3130
$endDate = (Get-Date)
3231
$SearchParam = @{
33-
SessionCommand = "ReturnLargeSet"
32+
SessionCommand = 'ReturnLargeSet'
3433
Operations = $operations
3534
sessionid = $sessionid
3635
startDate = $startDate
3736
endDate = $endDate
3837
}
3938
do {
40-
New-ExoRequest -tenantid $Tenantfilter -cmdlet "Search-unifiedAuditLog" -cmdParams $SearchParam -Anchor $Username
39+
New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Search-unifiedAuditLog' -cmdParams $SearchParam -Anchor $Username
4140
Write-Host "Retrieved $($logsTenant.count) logs" -ForegroundColor Yellow
4241
$logsTenant
4342
} while ($LogsTenant.count % 5000 -eq 0 -and $LogsTenant.count -ne 0)
44-
$ExtractResult = "Succesfully extracted logs from auditlog"
43+
$ExtractResult = 'Succesfully extracted logs from auditlog'
4544
}
4645
Try {
4746
$URI = "https://graph.microsoft.com/beta/auditLogs/signIns?`$filter=(userId eq '$SuspectUser')&`$top=1&`$orderby=createdDateTime desc"
@@ -50,29 +49,26 @@ try {
5049
@{ Name = 'AppDisplayName'; Expression = { $_.resourceDisplayName } },
5150
@{ Name = 'Status'; Expression = { if (($_.conditionalAccessStatus -eq 'Success' -or 'Not Applied') -and $_.status.errorCode -eq 0) { 'Success' } else { 'Failed' } } },
5251
@{ Name = 'IPAddress'; Expression = { $_.ipAddress } }
53-
}
54-
catch {
52+
} catch {
5553
$LastSignIn = [PSCustomObject]@{
56-
AppDisplayName = "Unknown - could not retrieve information. No access to sign-in logs"
57-
CreatedDateTime = "Unknown"
58-
Id = "0"
59-
Status = "Could not retrieve additional details"
54+
AppDisplayName = 'Unknown - could not retrieve information. No access to sign-in logs'
55+
CreatedDateTime = 'Unknown'
56+
Id = '0'
57+
Status = 'Could not retrieve additional details'
6058
}
6159
}
6260
#List all users devices
6361
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($SuspectUser)
6462
$base64IdentityParam = [Convert]::ToBase64String($Bytes)
6563
Try {
6664
$Devices = New-GraphGetRequest -uri "https://outlook.office365.com:443/adminapi/beta/$($TenantFilter)/mailbox('$($base64IdentityParam)')/MobileDevice/Exchange.GetMobileDeviceStatistics()/?IsEncoded=True" -Tenantid $tenantfilter -scope ExchangeOnline
67-
}
68-
catch {
65+
} catch {
6966
$Devices = $null
7067
}
71-
$PermissionsLog = ($7dayslog | Where-Object -Property Operations -In "Remove-MailboxPermission", "Add-MailboxPermission", "UpdateCalendarDelegation", "AddFolderPermissions" ).AuditData | ConvertFrom-Json -Depth 100 | ForEach-Object {
68+
$PermissionsLog = ($7dayslog | Where-Object -Property Operations -In 'Remove-MailboxPermission', 'Add-MailboxPermission', 'UpdateCalendarDelegation', 'AddFolderPermissions' ).AuditData | ConvertFrom-Json -Depth 100 | ForEach-Object {
7269
$perms = if ($_.Parameters) {
73-
$_.Parameters | ForEach-Object { if ($_.Name -eq "AccessRights") { $_.Value } }
74-
}
75-
else
70+
$_.Parameters | ForEach-Object { if ($_.Name -eq 'AccessRights') { $_.Value } }
71+
} else
7672
{ $_.item.ParentFolder.MemberRights }
7773
$objectID = if ($_.ObjectID) { $_.ObjectID } else { $($_.MailboxOwnerUPN) + $_.item.ParentFolder.Path }
7874
[pscustomobject]@{
@@ -83,43 +79,42 @@ try {
8379
}
8480
}
8581

86-
$RulesLog = @(($7dayslog | Where-Object -Property Operations -In "New-InboxRule", "Set-InboxRule", "UpdateInboxRules").AuditData | ConvertFrom-Json) | ForEach-Object {
82+
$RulesLog = @(($7dayslog | Where-Object -Property Operations -In 'New-InboxRule', 'Set-InboxRule', 'UpdateInboxRules').AuditData | ConvertFrom-Json) | ForEach-Object {
8783
Write-Host ($_ | ConvertTo-Json)
8884
[pscustomobject]@{
8985
ClientIP = $_.ClientIP
9086
CreationTime = $_.CreationTime
9187
UserId = $_.UserId
92-
RuleName = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq "RuleName") { $_.Value } })
93-
RuleCondition = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq "RuleCondition") { $_.Value } })
88+
RuleName = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq 'RuleName') { $_.Value } })
89+
RuleCondition = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq 'RuleCondition') { $_.Value } })
9490
}
9591
}
9692
$PasswordChanges = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users?`select=lastPasswordChangeDateTime,displayname,UserPrincipalName" -Tenantid $tenantfilter | Where-Object { $_.lastPasswordChangeDateTime -gt $startDate }
97-
$NewUsers = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users?`$select=displayname,UserPrincipalName,CreatedDateTime" -Tenantid $tenantfilter | Where-Object { $_.CreatedDateTime -gt $startDate }
93+
$NewUsers = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users?`$select=displayname,UserPrincipalName,CreatedDateTime" -Tenantid $tenantfilter | Where-Object { $_.CreatedDateTime -gt $startDate }
9894
$MFADevices = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($SuspectUser)/authentication/methods" -Tenantid $tenantfilter
9995
$NewSPs = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$select=displayName,createdDateTime,id,AppDisplayName&`$filter=createdDateTime ge $($startDate.ToString('yyyy-MM-ddTHH:mm:ssZ'))" -Tenantid $tenantfilter
100-
$Last50Logons = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?`$top=50&`$orderby=createdDateTime desc" -tenantid $TenantFilter -noPagination $true -verbose | Select-Object @{ Name = 'CreatedDateTime'; Expression = { $(($_.createdDateTime | Out-String) -replace '\r\n') } },
96+
$Last50Logons = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?`$top=50&`$orderby=createdDateTime desc" -tenantid $TenantFilter -noPagination $true -verbose | Select-Object @{ Name = 'CreatedDateTime'; Expression = { $(($_.createdDateTime | Out-String) -replace '\r\n') } },
10197
id,
10298
@{ Name = 'AppDisplayName'; Expression = { $_.resourceDisplayName } },
10399
@{ Name = 'Status'; Expression = { if (($_.conditionalAccessStatus -eq 'Success' -or 'Not Applied') -and $_.status.errorCode -eq 0) { 'Success' } else { 'Failed' } } },
104100
@{ Name = 'IPAddress'; Expression = { $_.ipAddress } }, UserPrincipalName
105101
$Results = [PSCustomObject]@{
106-
AddedApps = $NewSPs
107-
SuspectUserMailboxLogons = $Last50Logons
102+
AddedApps = @($NewSPs)
103+
SuspectUserMailboxLogons = @($Last50Logons)
108104
LastSuspectUserLogon = @($LastSignIn)
109105
SuspectUserDevices = @($Devices)
110106
NewRules = @($RulesLog)
111107
MailboxPermissionChanges = @($PermissionsLog)
112108
NewUsers = @($NewUsers)
113-
MFADevices = $MFADevices
114-
ChangedPasswords = $PasswordChanges
109+
MFADevices = @($MFADevices)
110+
ChangedPasswords = @($PasswordChanges)
115111
ExtractedAt = (Get-Date).ToString('s')
116112
ExtractResult = $ExtractResult
117113
}
118114

119-
}
120-
catch {
115+
} catch {
121116
$errMessage = Get-NormalizedError -message $_.Exception.Message
122-
$results = [pscustomobject]@{"Results" = "$errMessage" }
117+
$results = [pscustomobject]@{'Results' = "$errMessage" }
123118
}
124119

125120
$Table = Get-CippTable -tablename 'cachebec'
@@ -128,5 +123,5 @@ Add-CIPPAzDataTableEntity @Table -Entity @{
128123
UserId = $Context.input.userid
129124
Results = "$($results | ConvertTo-Json -Depth 10)"
130125
RowKey = $Context.input.userid
131-
PartitionKey = "bec"
126+
PartitionKey = 'bec'
132127
}

0 commit comments

Comments
 (0)