Skip to main content

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  

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.