Tuesday, June 25, 2013

EWS Powershell default Mailbox Folder ACE audit script

The default Access Control Entry ACE in an Exchange Mailbox Folder DACL controls the rights that all authenticated users have to a particularity mailbox folder. Generally from a security perspective its something you don't want users to use as they may not understand when then set this ACE they are giving all people access to certain information. Eg Giving the default user reviewer rights to your Inbox means everyone in the Exchange org can now read mailbox in you Inbox which may not provide much privacy to your email. The following script will enumerate the permissions on every folder in a Mailbox and then produce a report of the folders where the default ACE isn't set to none. For most users the only folder that should show up in the report in the calendar folder. This script uses EWS but you could also use the Exchange Management Shell Get-MailboxFolderPermission cmdlet.

To run this script you need to feed is with a CSV file that contains the SMTPAddress of the Mailboxes you want it to run against. I've put a download of this script here the script itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2. $Script:rptCollection = @()  
  3. ## Load Managed API dll    
  4. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  5.     
  6. ## Set Exchange Version    
  7. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  8.     
  9. ## Create Exchange Service Object    
  10. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  11.     
  12. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  13.     
  14. #Credentials Option 1 using UPN for the windows Account    
  15. $psCred = Get-Credential    
  16. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  17. $service.Credentials = $creds        
  18.     
  19. #Credentials Option 2    
  20. #service.UseDefaultCredentials = $true    
  21.     
  22. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  23.     
  24. ## Code From http://poshcode.org/624  
  25. ## Create a compilation environment  
  26. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  27. $Compiler=$Provider.CreateCompiler()  
  28. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  29. $Params.GenerateExecutable=$False  
  30. $Params.GenerateInMemory=$True  
  31. $Params.IncludeDebugInformation=$False  
  32. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  33.   
  34. $TASource=@' 
  35.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  36.     public class TrustAll : System.Net.ICertificatePolicy { 
  37.       public TrustAll() {  
  38.       } 
  39.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  40.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  41.         System.Net.WebRequest req, int problem) { 
  42.         return true; 
  43.       } 
  44.     } 
  45.   } 
  46. '@   
  47. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  48. $TAAssembly=$TAResults.CompiledAssembly  
  49.   
  50. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  51. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  52. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  53.   
  54. ## end code from http://poshcode.org/624  
  55.     
  56. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  57.     
  58. #CAS URL Option 1 Autodiscover    
  59.   
  60.      
  61. #CAS URL Option 2 Hardcoded    
  62.     
  63. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  64. #$service.Url = $uri      
  65.     
  66. ## Optional section for Exchange Impersonation    
  67.     
  68. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  69.   
  70. # Bind to the Inbox Folder  
  71. #Define Function to convert String to FolderPath    
  72. function ConvertToString($ipInputString){    
  73.     $Val1Text = ""    
  74.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){    
  75.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))    
  76.             $clInt++    
  77.     }    
  78.     return $Val1Text    
  79. }   
  80.   
  81. function Process-Mailbox{  
  82.     param (  
  83.             $SmtpAddress = "$( throw 'SMTPAddress is a mandatory Parameter' )"  
  84.           )  
  85.     process{  
  86.   
  87.         #Define Extended properties    
  88.         $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  89.         $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$SmtpAddress)  
  90.         #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling    
  91.         $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  92.         #Deep Transval will ensure all folders in the search path are returned    
  93.         $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  94.         $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  95.         $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);    
  96.         #Add Properties to the  Property Set    
  97.         $psPropertySet.Add($PR_Folder_Path);    
  98.         $fvFolderView.PropertySet = $psPropertySet;    
  99.         #The Search filter will exclude any Search Folders    
  100.         $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  101.         $fiResult = $null  
  102.         #Process the Mailbox Root Folder  
  103.         $psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  104.         $psPropset.Add([Microsoft.Exchange.WebServices.Data.FolderSchema]::Permissions);  
  105.         #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox    
  106.         do {    
  107.             $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilter,$fvFolderView)    
  108.             foreach($ffFolder in $fiResult.Folders){    
  109.                 $foldpathval = $null    
  110.                 #Try to get the FolderPath Value and then covert it to a usable String     
  111.                 if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))    
  112.                 {    
  113.                     $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)    
  114.                     $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }    
  115.                     $hexString = $hexArr -join ''    
  116.                     $hexString = $hexString.Replace("FEFF""5C00")    
  117.                     $fpath = ConvertToString($hexString)    
  118.                 }    
  119.                 "Processing FolderPath : " + $fpath    
  120.                 $ffFolder.Load($psPropset)  
  121.                 foreach($Permission in  $ffFolder.Permissions){  
  122.                     if($Permission.UserId.StandardUser -eq [Microsoft.Exchange.WebServices.Data.StandardUser]::Default){  
  123.                         if($Permission.DisplayPermissionLevel -ne "None"){  
  124.                             $rptObj = "" | Select Mailbox,FolderPath,FolderType,PermissionLevel  
  125.                             $rptObj.Mailbox = $SmtpAddress  
  126.                             $rptObj.FolderPath = $fpath  
  127.                             $rptObj.FolderType = $ffFolder.FolderClass  
  128.                             $rptObj.PermissionLevel = $Permission.DisplayPermissionLevel  
  129.                             $Script:rptCollection += $rptObj  
  130.                         }   
  131.                     }  
  132.                 }  
  133.   
  134.             }   
  135.             $fvFolderView.Offset += $fiResult.Folders.Count  
  136.         }while($fiResult.MoreAvailable -eq $true)   
  137.     }  
  138. }  
  139. Import-Csv -Path $args[0] | ForEach-Object{  
  140.     if($service.url -eq $null){  
  141.         $service.AutodiscoverUrl($_.SmtpAddress,{$true})   
  142.         "Using CAS Server : " + $Service.url   
  143.     }    
  144.     Process-Mailbox -SmtpAddress $_.SmtpAddress  
  145. }  
  146. $Script:rptCollection  

2 comments:

Anonymous said...

This script requires Microsoft Exchange Web Services Managed API 2.0

Anonymous said...

Got this to run. But where does the output go?