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

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 Gr...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...
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.