Advertisement
Guest User

Untitled

a guest
Aug 8th, 2018
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #This script will allow you to execute a recommended set of steps to fully re-secure and remediate a known breached account in Office 365.
  2. #It peroms the following actions:
  3. # Reset password (which kills the session).
  4. # Remove mailbox delegates.
  5. # Remove mailforwarding rules to external domains.
  6. # Remove global mailforwarding property on mailbox.
  7. # Enable MFA on the user's account.
  8. # Set password complexity on the account to be high.
  9. # Enable mailbox auditing.
  10. # Produce Audit Log for the admin to review.
  11. # Remove ALL inbox rules
  12. #$upn = "Brandon@a830edad9050849NDA3313.onmicrosoft.com"
  13.  
  14. [CmdletBinding()]
  15. Param(
  16.     [Parameter(Mandatory=$True,Position=0)][ValidateNotNullOrEmpty()]
  17.         [string]$upn
  18.    
  19.     #[Parameter(Mandatory=$False)]
  20.     #    [date]$startDate,
  21.    
  22.     #[Parameter(Mandatory=$False)]
  23.     #    [date]$endDate,
  24.    
  25.     #[Parameter(Mandatory=$False)]
  26.     #    [string]$fromFile
  27.  
  28. )
  29.  
  30. $userName = $upn -split "@"
  31.  
  32. $transcriptpath = ".\" + $userName[0] + "RemediationTranscript" + (Get-Date).ToString('yyyy-MM-dd') + ".txt"
  33. Start-Transcript -Path $transcriptpath
  34.  
  35.  
  36. Write-Output "You are about to remediate this account: $upn"
  37. Write-Output "Let's get a credential and get connected to Office 365."
  38.  
  39. #Import the right module to talk with AAD
  40. import-module MSOnline
  41.  
  42. #First, let's get us a cred!
  43. $adminCredential = Get-Credential
  44.  
  45.     Write-Output "Connecting to Exchange Online Remote Powershell Service"
  46.     $ExoSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $adminCredential -Authentication Basic -AllowRedirection
  47.     if ($null -ne $ExoSession) {
  48.         Import-PSSession $ExoSession
  49.     } else {
  50.         Write-Output "  No EXO service set up for this account"
  51.     }
  52.  
  53.     Write-Output "Connecting to EOP Powershell Service"
  54.     $EopSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $adminCredential -Authentication Basic -AllowRedirection
  55.     if ($null -ne $EopSession) {
  56.         Import-PSSession $EopSession -AllowClobber
  57.     } else {
  58.         Write-Output "  No EOP service set up for this account"
  59.     }
  60.  
  61. #This connects to Azure Active Directory
  62. Connect-MsolService -Credential $adminCredential
  63.  
  64. #Load "System.Web" assembly in PowerShell console
  65. [Reflection.Assembly]::LoadWithPartialName("System.Web")
  66.  
  67. function Reset-Password($upn) {
  68.     $newPassword = ([System.Web.Security.Membership]::GeneratePassword(16,2))
  69.     Set-MsolUserPassword –UserPrincipalName $upn –NewPassword $newPassword -ForceChangePassword $True
  70.     Write-Output "We've set the password for the account $upn to be $newPassword. Make sure you record this and share with the user, or be ready to reset the password again. They will have to reset their password on the next logon."
  71.    
  72.     Set-MsolUser -UserPrincipalName $upn -StrongPasswordRequired $True
  73.     Write-Output "We've also set this user's account to require a strong password."
  74.  
  75. }
  76.  
  77. function Enable-MailboxAuditing($upn) {
  78.     Write-Output "##############################################################"
  79.     Write-Output "We are going to enable mailbox auditing for this user to ensure we can monitor activity going forward."
  80.  
  81.     #Let's enable auditing for the mailbox in question.
  82.     Set-Mailbox $upn -AuditEnabled $true -AuditLogAgeLimit 365
  83.  
  84.     Write-Output "##############################################################"
  85.     Write-Output "Done! Here's the current configuration for auditing."    
  86.     #Double-Check It!
  87.     Get-Mailbox -Identity $upn | Select Name, AuditEnabled, AuditLogAgeLimit
  88. }
  89.  
  90. function Remove-MailboxDelegates($upn) {
  91.     Write-Output "##############################################################"
  92.     Write-Output "Removing Mailbox Delegate Permissions for the affected user $upn."
  93.  
  94.     $mailboxDelegates = Get-MailboxPermission -Identity $upn | Where-Object {($_.IsInherited -ne "True") -and ($_.User -notlike "*SELF*")}
  95.     Get-MailboxPermission -Identity $upn | Where-Object {($_.IsInherited -ne "True") -and ($_.User -notlike "*SELF*")}
  96.    
  97.     foreach ($delegate in $mailboxDelegates)
  98.     {
  99.         Remove-MailboxPermission -Identity $upn -User $delegate.User -AccessRights $delegate.AccessRights -InheritanceType All -Confirm:$false
  100.     }
  101.  
  102.     #Possibly add the admin running the script to the user's mailbox?
  103.     #Add-MailboxPermission -Identity $upn -User $adminCredential.UserName -AccessRights FullAccess -InheritanceType All
  104.     #TO DO: Need to figure out how to check delegate permissions set on a all the folders for the user, then remove them. Looks to be a user-only cmdlet permission set
  105.     #$mailboxFolders = Get-MailboxFolder -Identity admin -Recurse
  106.     #foreach ($folder in $mailboxFolders)
  107.     #{
  108.     #    $thisUpnFolder = $upn + ":\" + $folder.FolderPath
  109.     #    Get-MailboxFolderPermission -Identity $thisUpnFolder | Where-Object {($_.AccessRights -ne "None")}
  110.         #Remove-MailboxFolderPermission: https://technet.microsoft.com/en-us/library/dd351181(v=exchg.160).aspx
  111.     #}
  112.    
  113. }
  114.  
  115. function Disable-MailforwardingRulesToExternalDomains($upn) {
  116.     Write-Output "##############################################################"
  117.     Write-Output "Disabling mailforwarding rules to external domains for the affected user $upn."
  118.     Write-Output "We found the following rules that forward or redirect mail to other accounts: "
  119.     Get-InboxRule -Mailbox $upn | Select Name, Description, Enabled, Priority, ForwardTo, ForwardAsAttachmentTo, RedirectTo, DeleteMessage, SendTextMessageNotificationTo | Where-Object {(($_.Enabled -eq $true) -and (($_.ForwardTo -ne $null) -or ($_.ForwardAsAttachmentTo -ne $null) -or ($_.RedirectTo -ne $null) -or ($_.SendTextMessageNotificationTo -ne $null)))} | Format-Table
  120.     Get-InboxRule -Mailbox $upn | Where-Object {(($_.Enabled -eq $true) -and (($_.ForwardTo -ne $null) -or ($_.ForwardAsAttachmentTo -ne $null) -or ($_.RedirectTo -ne $null) -or ($_.SendTextMessageNotificationTo -ne $null)))} | Disable-InboxRule -Confirm:$false
  121.  
  122.     #Clean-up disabled rules
  123.     #Get-InboxRule -Mailbox $upn | Where-Object {((($_.ForwardTo -ne $null) -or ($_.ForwardAsAttachmentTo -ne $null) -or ($_.RedirectTo -ne $null) -or ($_.SendTextMessageNotificationTo -ne $null)))} | Remove-InboxRule -Confirm:$false
  124.  
  125.     Write-Output "##############################################################"
  126.     Write-Output "Aight. We've disabled all the rules that move your email to other mailboxes. "
  127. }
  128.  
  129.  
  130. function Remove-MailboxForwarding($upn) {
  131.     Write-Output "##############################################################"
  132.     Write-Output "Removing Mailbox Forwarding configurations for the affected user $upn. Current configuration is:"
  133.     Get-Mailbox -Identity $upn | Select Name, DeliverToMailboxAndForward, ForwardingSmtpAddress
  134.  
  135.     Set-Mailbox -Identity $upn -DeliverToMailboxAndForward $false -ForwardingSmtpAddress $null
  136.  
  137.     Write-Output "##############################################################"
  138.     Write-Output "Mailbox forwarding removal completed. Current configuration is:"
  139.     Get-Mailbox -Identity $upn | Select Name, DeliverToMailboxAndForward, ForwardingSmtpAddress
  140.  
  141. }
  142.  
  143. function Enable-MFA ($upn) {
  144.  
  145.     #Create the StrongAuthenticationRequirement object and insert required settings
  146.     $mf = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
  147.     $mf.RelyingParty = "*"
  148.     $mfa = @($mf)
  149.     #Enable MFA for a user
  150.     Set-MsolUser -UserPrincipalName $upn -StrongAuthenticationRequirements $mfa
  151.  
  152.     Write-Output "##############################################################"
  153.     Write-Output "Aight. We've enabled MFA required for $upn. Let them know they'll need to setup their additional auth token the next time they logon."
  154.  
  155.     #Find all MFA enabled users
  156.     Get-MsolUser -UserPrincipalName $upn | select UserPrincipalName,StrongAuthenticationMethods,StrongAuthenticationRequirements
  157.  
  158. }
  159.  
  160. function Get-AuditLog ($upn) {
  161.     Write-Output "##############################################################"
  162.     Write-Output "We've remediated the account, but there might be things we missed. Review the audit transcript for this user to be super-sure you've got everything."
  163.  
  164.     $userName = $upn -split "@"
  165.     $auditLogPath = ".\" + $userName[0] + "AuditLog" + (Get-Date).ToString('yyyy-MM-dd') + ".csv"
  166.    
  167.     $startDate = (Get-Date).AddDays(-7).ToString('MM/dd/yyyy')
  168.     $endDate = (Get-Date).ToString('MM/dd/yyyy')
  169.     $results = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -UserIds $upn
  170.     $results | Export-Csv -Path $auditLogPath
  171.  
  172.     Write-Output "##############################################################"
  173.     Write-Output "We've written the log to $auditLogPath. You can also review the activity below."
  174.     Write-Output "##############################################################"
  175.     $results | Format-Table    
  176.  
  177. }
  178.  
  179. function Remove-InboxRule ($upn) {
  180.     Write-Output "##############################################################"
  181.     Write-Output "We are remvoing ALL inbox rules"
  182.     Write-Output "##############################################################"
  183.    
  184.     #Removing Inbox Rules
  185.     Get-InboxRule -Mailbox $upn | Remove-InboxRule
  186.  
  187.     Write-Output "##############################################################"
  188.     Write-Output "We've Removed ALL inbox rules"
  189.     Write-Output "##############################################################"
  190. }
  191.  
  192. Reset-Password $upn
  193. Enable-MailboxAuditing $upn
  194. Remove-MailboxDelegates $upn
  195. Disable-MailforwardingRulesToExternalDomains $upn
  196. Remove-MailboxForwarding $upn
  197. Enable-MFA $upn
  198. Get-AuditLog $upn
  199.  
  200. Stop-Transcript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement