An activity that provides an attacker access to resources after detection of an account compromise is called persistence. One example of this is automatic forwarding of email. Using leaked credentials, the attacker logs into a mailbox and configures mail to forward (usually to an external address). Even after the account’s password is reset, the forwarding setting remains in effect.
In Office 365, there are numerous methods of achieving persistence. Many take advantage of collaborative features and those that exist to increase user productivity. It is important to be aware of these mechanisms and check for them after you become aware of a compromised account. I wrote a script that not only reports on persistence configuration, but if the configuration occurred during the time that you believe the account was compromised. It reports on these activities:
- Inbox rules that forward, to whom they forward, and if the rules were created/modified within the search window
- Forwarding configured via Outlook on the web Options (aka OWA Forwarding), to whom it forwards, and if it was created/modified within the search window
- Mailbox folder permission changes during the search window
- Anonymous calendar publishing is configured, and if it was enabled within the search window
- All applications that have access via user-based consent (known as OAuth grants), when the grant first occurred, and the last time the application signed in
- Files located in SharePoint Online (and OneDrive for Business) that were shared within the search window, whether they were anonymous links or secure links, and if the latter, with whom they were shared
- Members (internal and guest) added to a Microsoft Team or Office 365 Group within the search window, which Team/Group, and the UPN of the member
- Flows that were edited within the search window, the admin URL of the Flow, and the connectors used
- (Optional) Mobile device partnerships with the user’s mailbox, and the first and last sync time of each (This isn’t technically persistence, but can be included to show partnerships, usually to see if a new one was created)
Most of the information for these activities is available in the unified audit log. (Because the log is stored in a mailbox in Exchange Online, if you want to be sure that you have enabled unified logging, you can run (Get-AdminAuditLogConfig).UnifiedAuditLogIngestionEnabled and check that the output is True.) Some of the information, however, is available only via the Graph API:
- Applications that the user has granted consent (this is available via PowerShell, but not per user, so it is not practical in a production tenant)
- The date of the grant for an application’s consent
- Application sign-ins
- Members added to an Office 365 Group (though members added to a Team are available in the unified audit log…odd, yes)
Leveraging the Graph API requires that you register an application in Azure AD. This is because you have to specify what permissions (access) you want the application to have, as well as how the application will authenticate. (There are multiple ways to authenticate, but I am using a client secret.) I have created a separate post with those instructions. Some admins may not want or have the ability to register an application, so it is not required, but the output will obviously not include the application consent information and Office 365 Group member additions. For those that do, you will need to edit the script and set $useGraphApi to $true , and provide the values for the $appId , $clientSecret , and $tenantDomain variables.
The script requires you to be connected to Exchange Online and have the Azure AD module installed and connected. It will search, by default, for activities in the last seven days, but you can specify a start and/or end dates. Bear in mind that the unified audit log retains entries for 90 days for non-E5 users (and one year for E5-licensed users or those assigned an Advanced Compliance add-on license). Additionally, Azure AD audit and sign-in log entries are retained for 30 days for P1/P2-licensed users (seven days for Free and Basic users) (source).
Handling the output is something I spent a fair amount of time working through. This is because of how PowerShell processes multiple objects in a script that contain different properties. (It assumes the properties of the first object in the output apply to all successive objects, so those successive objects will only show properties that are also in the first object.) I experimented with key/value pairs in generic properties, but it is ugly and requires much more work from you if you want to parse the values for further processing.
My compromise solution is that the default option will display the output to the screen as text and not native objects. If you use the PassThru switch, the objects are not output to the screen, but sent to the pipeline as native objects so you can do whatever you want with them. Generally, this means you would assign the output to a variable and then work with each object in the collection, but you can even just output the variable to the screen and they will be displayed correctly. (It is only when outputting them directly from the script that objects with different properties are displayed incorrectly.)
You can download the script or copy below.
Get-O365PersistenceActions.ps1 (22.0 KiB)
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 |
<# .Parameter UserPrincipalName UPN of the user whose actions to report .Parameter StartDate Beginning of search window in audit logs. Defaults to seven days (and current time) ago. .Parameter EndDate End of search window in audit logs. Defaults to current date/time. .Parameter PassThru Switch to have the output objects sent to the pipeline instead of the screen. .Parameter ShowNonMatches Whether a check that does not return any items should say so in the screen output. Defaults to False .Example .\Get-O365PersistenceActions.ps1 johndoe@contoso.com .Example .\Get-O365PersistenceActions.ps1 johndoe@contoso.com -StartDate (Get-Date).AddDays(-14) .Notes Version: 1.0 Date: 12/21/18 #> [CmdletBinding()] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] [ValidateScript({ForEach-Object{if ((Get-Mailbox -Identity $_) -and (Get-AzureADUser -ObjectId $_)) {$true} else {throw "Either you are not connected to Exchange Online and Azure AD, or $_ is not a valid UPN and mailbox identity."}} })] [Alias("Identity")][string]$UserPrincipalName, [parameter(Mandatory=$false)][datetime]$StartDate = (Get-Date).AddDays(-7), [parameter(Mandatory=$false)][datetime]$EndDate = (Get-Date), [switch]$PassThru, [switch]$ShowNonMatches ) $useGraphApi = $false #Set to true if script is registered in AAD, and appId and clientSecret values are populated $appId = '' #Will be a 36-character string (GUID) $clientSecret = '' #Will be a random-length string $tenantDomain = 'contoso.onmicrosoft.com' #Your tenant's default routing domain, always ends with onmicrosoft.com #requires -Module AzureAD function Write-ProgressHelper ($activity) { Write-Progress -Activity "Checking for persistence by account $UserPrincipalName" -Status 'Overall Progress' ` -CurrentOperation $activity -PercentComplete ((($script:step++)/$totalSteps)*100) -Id 1 } function Get-AccessToken { $resourceUri = 'https://graph.microsoft.com' $body = @{grant_type='client_credentials';resource=$resourceUri;client_id=$appId;client_secret=$clientSecret} Invoke-RestMethod -Method Post -Uri https://login.windows.net/$tenantDomain/oauth2/token?api-version=1.0 -Body $body } function Get-GraphData ($queryType, $filter) { $formattedStart = "{0:s}" -f $StartDate + 'Z' $formattedEnd = "{0:s}" -f $EndDate + 'Z' $baseUri = 'https://graph.microsoft.com/' if ($queryType -eq 'DirAudits') { $path = 'beta/auditLogs/directoryAudits' $dateFilter = " and activityDateTime gt $formattedStart and activityDateTime lt $formattedEnd" } elseif ($queryType -eq 'SignIns') { $path = 'beta/auditLogs/signIns' $queryParameter = '?$top=1' } elseif ($queryType -eq 'AppGrants') { $path = 'beta/oAuth2PermissionGrants' } elseif ($queryType -eq 'AppAssignments') { $path = "beta/users/$UserPrincipalName/appRoleAssignments" } $fullUri = $baseUri + $path + $queryParameter + $filter + $dateFilter $headerParams = @{'Authorization'="$($accessToken.token_type) $($accessToken.access_token)"} #Suppress Invoke-WebRequest's own progress bar $originalProgPref = $ProgressPreference $ProgressPreference = 'SilentlyContinue' $rawResponse = Invoke-WebRequest -UseBasicParsing -Headers $headerParams -Uri $fullUri -Method Get $response = ConvertFrom-Json -InputObject $rawResponse.Content $values = $response.value $moreURL = $values."@odata.nextLink" if ($moreURL -ne $null) { do { $moreRawResponse = Invoke-WebRequest -UseBasicParsing -Headers $headerParams ` -Uri $moreURL.ToString() -Method Get -ErrorAction SilentlyContinue $moreResponse = ConvertFrom-Json -InputObject $moreRawResponse.Content $values += $moreResponse.value $moreURL = $moreResponse."@odata.nextLink" } while ($moreURL -ne $null) } $ProgressPreference = $originalProgPref return $values } #region LM Check Functions function Get-MailboxRules { Write-ProgressHelper -Activity 'Checking Inbox rules for forwarding' #Get all inbox rules that forward or send a text message $rules = Get-InboxRule -Mailbox $UserPrincipalName | Where-Object {(($_.ForwardTo) -or ( $_.ForwardAsAttachmentTo) -or ($_.RedirectTo) -or ($_.SendTextMessageNotificationTo))} if ($rules) { #Search admin audit log for rules that forward that were created/modified during search window $auditLogRules = Search-AdminAuditLog -UserIds $UserPrincipalName -Cmdlets New-InboxRule,Set-InboxRule ` -Parameters ForwardTo,RedirectTo,SendTextMessageNotificationTo -StartDate $StartDate -EndDate $EndDate foreach ($ruleEntry in $rules) { $checkRuleOutput = "" | Select-Object -Property Check,User,RuleName,RuleAction,Enabled,LastModified $checkRuleOutput.Check = 'InboxForward' $checkRuleOutput.User = $UserPrincipalName $checkRuleOutput.RuleName = $ruleEntry.Name $ruleAction = @() if ($ruleEntry.ForwardTo) { $ruleAction += 'ForwardTo:' + $ruleEntry.ForwardTo } if ($ruleEntry.RedirectTo) { $ruleAction += 'RedirectTo:' + $ruleEntry.RedirectTo } if ($ruleEntry.SendTextMessageNotificationTo) { $ruleAction += 'SendTextTo:' + $ruleEntry.SendTextMessageNotificationTo } $checkRuleOutput.RuleAction = $ruleAction $checkRuleOutput.Enabled = $ruleEntry.Enabled if ($auditLogRules) { foreach ($logEntry in $auditLogRules) { #Check if matching rule name exists in audit log $propValue = $logEntry.CmdletParameters | Where-Object {$_.Name -eq 'Name'} | Select-Object -ExpandProperty Value if ($propValue -eq $ruleName) { $runDate = $logEntry.RunDate #Run date is returned in local time break } else { $runDate = 'Unknown' } } } else { $runDate = 'Unknown' } $checkRuleOutput.LastModified = $runDate } $checkRuleOutput } else { if ($ShowNonMatches) {Write-Host 'InboxForward: There are no Inbox rules configured with forwarding.'} } } function Get-OWAForwarding { Write-ProgressHelper -Activity 'Checking OWA-configured forwarding' #Check for mail forwarding via ForwardingSMTPAddress $mb = Get-Mailbox -Identity $UserPrincipalName $checkForwardOutput = "" | Select-Object -Property Check,User,ForwardAddress,LastModified $checkForwardOutput.Check = 'OWAForward' $checkForwardOutput.User = $UserPrincipalName if ($mb.ForwardingSmtpAddress) { $checkForwardOutput.ForwardAddress = $mb.ForwardingAddress #Search admin audit log to see if forwarding was set during search window $auditLogForward = Search-AdminAuditLog -UserIds $UserPrincipalName -Cmdlets Set-Mailbox ` -Parameters ForwardingSmtpAddress -StartDate $StartDate -EndDate $EndDate if ($auditLogForward) { foreach ($logEntry in $auditLogForward) { $propValue = $logEntry.CmdletParameters | Where-Object {$_.Name -eq 'ForwardingSmtpAddress'} | Select-Object -ExpandProperty Value if ($propValue -eq $mb.ForwardingSmtpAddress) { $runDate = $logEntry.RunDate #Run date is returned in local time break } else { $runDate = 'Unknown' } } } else { $runDate = 'Unknown' } $checkForwardOutput.LastModified = $runDate $checkForwardOutput } else { if ($ShowNonMatches) {Write-Host "OWAForward: There is no OWA forwarding configured."} } } function Get-Consents { Write-ProgressHelper -Activity 'Checking user-based application consents' if ($useGraphApi) { $aadUser = Get-AzureADUser -ObjectId $UserPrincipalName #Filter on user's GUID for the assigned principal $consentsGraphFilter = "?`$filter=PrincipalId eq `'$($aadUser.ObjectId)`'" Write-Progress -Activity ' Getting consented applications via Graph' -Status 'Retrieving' -Id 2 -ParentId 1 #Get all applications the user has granted consent to [array]$userGrants = Get-GraphData -queryType AppGrants -filter $consentsGraphFilter Write-Progress -Activity ' Getting consented applications via Graph' -Id 2 -Completed if ($userGrants) { Write-Progress -Activity ' Getting consent dates via Graph' -Status 'Retrieving' -Id 2 -ParentId 1 #Get all applications assigned to the user [array]$userAppAssignments = Get-GraphData -queryType AppAssignments Write-Progress -Activity ' Getting consent dates via Graph' -Id 2 -Completed $consentTable = @{} foreach ($assignment in $userAppAssignments) { #Hash table will contain each application's ID and when its user assignment was created $consentTable.Add($assignment.resourceId,[datetime]$assignment.CreationTimestamp) } for ($i = 0; $i -le $userGrants.Count - 1; $i++) { Write-Progress -Activity ' Processing consented applications' -Status ` "Application $($i + 1) of $($userGrants.Count)" -Id 2 -ParentId 1 $checkGrantsOutput = "" | Select-Object -Property Check,User,Application,ConsentDate,LastAppSignIn $checkGrantsOutput.Check = 'AppGrant' $checkGrantsOutput.User = $UserPrincipalName #Get application's service principal, given the client ID in the grant $consentedApp = Get-AzureADServicePrincipal -ObjectId $userGrants[$i].ClientId $checkGrantsOutput.Application = $consentedApp.DisplayName Write-Progress -Activity ' Getting sign-in logs via Graph' -Status 'Retrieving' -Id 3 -ParentId 2 #Filter on the ID the application from the app's service principal $signInGraphFilter = "&`$filter=appId eq `'$($consentedApp.appId)`'" #Get the most recent sign-in by the application $signInLogs = Get-GraphData -queryType 'SignIns' -filter $signInGraphFilter Write-Progress -Activity ' Getting sign-in logs via Graph' -Id 3 -Completed if ($signInLogs) { $checkGrantsOutput.LastAppSignIn = [datetime]($signInLogs.CreatedDateTime) } else { $checkGrantsOutput.LastAppSignIn = 'Unknown' } #Cross reference the app's ID with the hash table of application assignments #to determine when the consent was granted $consentDate = $consentTable[$consentedApp.objectId] if ($consentDate) { $checkGrantsOutput.ConsentDate = $consentDate } else { $checkGrantsOutput.ConsentDate = 'Unknown' } $checkGrantsOutput } Write-Progress -Activity ' Processing consented applications' -Id 2 -Completed } else { if ($ShowNonMatches) {Write-Host 'AppGrant: There are no applications that have permission via user-based consent.'} } } } function Get-FolderPermissionAdditions { Write-ProgressHelper -Activity 'Checking mailbox folder permissions' $mailbox = Get-Mailbox -Identity $UserPrincipalName #Verify mailbox auditing requirements have been met $orgAuditState = (Get-OrganizationConfig).AuditDisabled $mailboxAuditState = $mailbox.AuditEnabled $mailboxOwnerAudit = $mailbox.AuditOwner -contains 'UpdateFolderPermissions' $userAuditBypass = (Get-MailboxAuditBypassAssociation -Identity $UserPrincipalName).AuditBypassEnabled Write-Verbose -Message "Org-level mailbox auditing disabled: $orgAuditState; Mailbox auditing disabled: $mailboxAuditState; ` Owner auditing includes UpdateFolderPermissions: $mailboxOwnerAudit; User audit bypass enabled: $mailboxAuditBypass" if ($orgAuditState -eq $false -and $mailboxAuditState -and $mailboxOwnerAudit -and $userAuditBypass -eq $false) { #Checking folder permission additions covers calendar delegate additions, #so there is no need to check for UpdateCalendarDelegation operation $folderAuditLogs = Search-MailboxAuditLog -Identity $UserPrincipalName -LogonTypes Owner ` -Operations AddFolderPermissions -StartDate $StartDate -EndDate $EndDate -ShowDetails if ($folderAuditLogs) { foreach ($logEntry in $folderAuditLogs) { $checkFolderPermOutput = "" | Select-Object -Property Check,User,FolderName,Assignee,Permission,Modified $checkFolderPermOutput.Check = 'MbxFolderPermAdd' $checkFolderPermOutput.User = $UserPrincipalName $checkFolderPermOutput.FolderName = $logEntry.FolderName $checkFolderPermOutput.Assignee = $logEntry.MemberUpn $checkFolderPermOutput.Permission = $logEntry.MemberRights $checkFolderPermOutput.Modified = $logEntry.LastAccessed #LastAccessed is returned in local time $checkFolderPermOutput } } else { if ($ShowNonMatches) {Write-Host 'MbxFolderPerm: There are no folders with permission added within the search window.'} } } else { Write-Warning -Message 'Changes to mailbox folder permissions was skipped because the necessary mailbox auditing settings are not configured.' } } function Get-CalendarPublishing { Write-ProgressHelper -Activity 'Checking anonymous calendar publishing' #Get localized folder name $primaryCalendarPath = Get-MailboxFolderStatistics -Identity $UserPrincipalName -FolderScope Calendar | Where-Object {$_.FolderType -eq 'Calendar'} | Select-Object -ExpandProperty FolderPath $calendarPublishing = Get-MailboxCalendarFolder -Identity "$($UserPrincipalName):\$($primaryCalendarPath.Substring(1))" $checkCalPubOutput = "" | Select-Object -Property Check,User,PublishEnabled,WhenEnabled $checkCalPubOutput.Check = 'MbxCalPublish' $checkCalPubOutput.User = $UserPrincipalName if ($calendarPublishing.PublishEnabled) { $checkCalPubOutput.PublishEnabled = $true #Search admin audit log for publishing being enabled by owner $auditLogPublish = Search-AdminAuditLog -UserIds $UserPrincipalName -Cmdlets Set-MailboxCalendarFolder ` -Parameters PublishEnabled -StartDate $StartDate -EndDate $EndDate if ($auditLogPublish) { foreach ($logEntry in $auditLogPublish) { $propValue = $logEntry.CmdletParameters | Where-Object {$_.Name -eq 'PublishEnabled'} | Select-Object -ExpandProperty Value if ($propValue) { $checkCalPubOutput.WhenEnabled = $logEntry.RunDate #RunDate is returned in local time break } else { $checkCalPubOutput.WhenEnabled = 'Unknown' } } } else { $checkCalPubOutput.WhenEnabled = 'Unknown' } $checkCalPubOutput } else { if ($ShowNonMatches) {Write-Host 'MbxCalPublish: Calendar publishing is not enabled.'} } } function Get-MobileDevices { Write-ProgressHelper -Activity 'Checking mobile device partnerships' $mobileDevices = Get-MobileDeviceStatistics -Mailbox $UserPrincipalName if ($mobileDevices) { foreach ($device in $mobileDevices) { $checkMobileDevOutput = "" | Select-Object -Property Check,User,DeviceName,DeviceAgent,FirstSync,LastSync $checkMobileDevOutput.Check = 'MbxMobileDevice' $checkMobileDevOutput.User = $UserPrincipalName $checkMobileDevOutput.DeviceName = $device.DeviceFriendlyName $checkMobileDevOutput.DeviceAgent = $device.DeviceUserAgent $checkMobileDevOutput.FirstSync = $device.FirstSyncTime $checkMobileDevOutput.LastSync = $device.LastSyncTime $checkMobileDevOutput } } else { if ($ShowNonMatches) {Write-Host 'MbxMobileDevice: There are no mobile device partnerships.'} } } function Get-FileSharing { Write-ProgressHelper -Activity 'Checking file sharing' $operations = @('AnonymousLinkCreated','SecureLinkCreated','AddedToSecureLink') $auditLinks = Search-UnifiedAuditLog -UserIds $UserPrincipalName -StartDate $StartDate -EndDate $EndDate ` -Operations $operations if ($auditLinks) { foreach ($link in $auditLinks) { $checkFileSharingOutput = "" | Select-Object -Property Check,User,Operation,FilePath,Recipient,Created $checkFileSharingOutput.Check = 'FileSharing' $checkFileSharingOutput.User = $UserPrincipalName $checkFileSharingOutput.Operation = $link.Operation $checkFileSharingOutput.FilePath = $link.ObjectId if ($link.Operation -eq 'AddedToSecureLink') { $checkFileSharingOutput.Recipient = $link.TargetUserOrGroupName } $checkFileSharingOutput.Created = $link.CreationTime #CreationTime is returned in local time $checkFileSharingOutput } } else { if ($ShowNonMatches) {Write-Host 'FileSharing: No files were shared within the search window.'} } } function Get-TeamMemberAdded { Write-ProgressHelper -Activity 'Checking Team member additions' $operations = @('MemberAdded') $auditMembers = Search-UnifiedAuditLog -UserIds $UserPrincipalName -StartDate $StartDate -EndDate $EndDate ` -Operations $operations if ($auditMembers) { foreach ($entry in $auditMembers) { $auditData = $entry.AuditData | ConvertFrom-Json foreach ($user in $auditData.Members) { $checkTeamsMemberAddedOutput = "" | Select-Object -Property Check,User,Operation,Member,Team,Date $checkTeamsMemberAddedOutput.Check = 'TeamMemberAdd' $checkTeamsMemberAddedOutput.User = $UserPrincipalName $checkTeamsMemberAddedOutput.Operation = $entry.Operations if ($user.UPN -like '*#EXT#*') #Extract UPN from guest account { $id = $user.UPN.Substring(0,$user.UPN.IndexOf('#EXT#')) -replace ('_','@') } else #Member is internal { $id = $user.UPN } $checkTeamsMemberAddedOutput.Member = $id $checkTeamsMemberAddedOutput.Team = $auditData.TeamName $checkTeamsMemberAddedOutput.Date = $entry.CreationDate #CreationDate is returned in local time $checkTeamsMemberAddedOutput } } } else { if ($ShowNonMatches) {Write-Host 'TeamMemberAdd: No members were added to any Team within the search window.'} } } function Get-GroupMemberAdded { Write-ProgressHelper -Activity 'Checking Office 365 Group member additions' #Unified audit logs do not include Group member changes, so they must be obtained #from the AAD directory audit logs via Graph if ($useGraphApi) { #Filter looks for the action of member added and the UPN of the actor is the specific user $groupMemberAddGraphFilter = "?`$filter=activityDisplayName eq `'Add member to group`' and initiatedBy/user/userPrincipalName eq `'$UserPrincipalName`'" Write-Progress -Activity ' Getting audit logs via Graph' -Id 2 -ParentId 1 $addedMemberLogs = Get-GraphData -queryType 'DirAudits' -filter $groupMemberAddGraphFilter Write-Progress -Activity ' Getting audit logs via Graph' -Id 2 -Completed #Exclude changes to Teams because they were obtained in another check $noTeamsLogs = $addedMemberLogs | Where-Object {$_.initiatedBy.user.displayName -ne 'Microsoft Teams Services'} if ($noTeamsLogs) { foreach ($entry in $noTeamsLogs) { $checkGroupsMemberAddedOutput = "" | Select-Object -Property Check,User,Operation,Member,Group,Date $checkGroupsMemberAddedOutput.Check = 'GroupMemberAdd' $checkGroupsMemberAddedOutput.User = $UserPrincipalName $checkGroupsMemberAddedOutput.Operation = 'MemberAdded' $modifiedGroup = $entry.targetResources.modifiedProperties | Where-Object {$_.displayName -eq 'Group.DisplayName'} | Select-Object -ExpandProperty newValue $modifiedGroup = $modifiedGroup.SubString(1,$modifiedGroup.Length - 2) $addedUPN = $entry.targetResources.userPrincipalName[0] if ($addedUPN -like '*#EXT#*') #Extract UPN from guest account { $addedUPN = $addedUPN.Substring(0,$addedUPN.IndexOf('#EXT#')) -replace ('_','@') } $checkGroupsMemberAddedOutput.Member = $addedUPN $checkGroupsMemberAddedOutput.Group = $modifiedGroup $checkGroupsMemberAddedOutput.Date = [datetime]($entry.ActivityDateTime) $checkGroupsMemberAddedOutput } } else { if ($ShowNonMatches) {Write-Host 'GroupMemberAdd: No members were added to any Office 365 Group within the search window.'} } } } function Get-Flows { #Flow management via PowerShell or Graph is non-existent, but an entry from the unified audit log #includes the admin URL of the Flow for manual further review, as well as the connectors being used Write-ProgressHelper -Activity 'Checking Flows' $operations = @('EditFlow','CreateFlow') $auditFlows = Search-UnifiedAuditLog -UserIds $UserPrincipalName -StartDate $StartDate -EndDate $EndDate ` -Operations $operations if ($auditFlows) { foreach ($entry in $auditFlows) { $checkFlowsOutput = "" | Select-Object -Property Check,User,Operation,FlowUrl,Connectors,Date $checkFlowsOutput.Check = 'FlowEdit' $checkFlowsOutput.User = $UserPrincipalName $auditData = $entry.AuditData | ConvertFrom-Json $checkFlowsOutput.Operation = $auditData.Operation $checkFlowsOutput.FlowUrl = $auditData.FlowDetailsUrl $checkFlowsOutput.Connectors = $auditData.FlowConnectorNames $checkFlowsOutput.Date = $entry.CreationDate #CreationDate is returned in local time $checkFlowsOutput } } else { if ($ShowNonMatches) {Write-Host 'FlowEdit: No Flows were edited during the search window.'} } } #endregion LM Check Functions if ($StartDate -lt (Get-Date).AddDays(-30) -and $useGraphApi) { $warningText = 'The specified start date is more than 30 days ago. Azure AD directory audit and ' + 'sign-in activity is available for the last 30 days with P1/P2 licenses. O365 Group member ' + 'changes and application sign-in history may be incomplete.' Write-Warning -Message $warningText } if ($useGraphApi) { $accessToken = Get-AccessToken } $step = 0 $totalSteps = 10 $cmr = Get-MailboxRules $cof = Get-OWAForwarding $cfp = Get-FolderPermissionAdditions $ccp = Get-CalendarPublishing #Mobile device partnership isn't actually persistence, but can #be uncommented to show partnerships, particularly new ones #$cmd = Get-MobileDevices $cac = Get-Consents | Sort-Object -Property ConsentDate -Descending $cfs = Get-FileSharing $ctm = Get-TeamMemberAdded $cgm = Get-GroupMemberAdded $cfe = Get-Flows if ($PassThru) { $cmr $cof $cfp $ccp $cmd $cac $cfs $ctm $cgm $cfe } else { $cmr | Format-List $cof | Format-Table $cfp | Format-List $ccp | Format-Table $cmd | Format-Table $cac | Format-Table $cfs | Format-Table $ctm | Format-Table $cgm | Format-Table $cfe | Format-List } |