Skip to main content

EWS Managed API and Powershell How-To Series Part 8 Folder Permissions

In this series so far I've covered a lot of ground in EWS covering all the everyday operations so its time now to look at some of the more interesting and useful things you can do. Folder permissions are one thing that can both affect the code you run if you don't have the correct or enough rights in a folder your accessing and are also something you may want to manage using EWS. As before in this series I should point out that folder permission can be managed within the Exchange Management Shell using the Get and Set-MailboxFolderPermissions cmdlets and this can be a better solution for managing permissions.

Exchange Folder permission in a netshell

Exchange uses the normal discretionary access control list (DACL) with Access Control Entries (ACE's) to control access to its resources but there are a few special things to keep in mind. (There are also SACL's on public folders which you can't set from EWS).

Special ACE's in the Folder DACL : There are two special Group ACE's in a Exchange DACL there is the Default ACE (basically every authenticated mailbox user) and the Anoymous ACE (more for public folders which im not really going to dicuss).

FreeBusy Permissions : In Exchange 2007 freebusy rights where introduced see http://blogs.msdn.com/b/stephen_griffin/archive/2007/05/25/new-freebusy-rights-in-exchange-outlook-2007.aspx . So if your accessing the calendar folder in a users mailbox in EWS you will use a different class to accommodate these extra free-busy permissions.

Let's start by looking at some samples, to access the permission on a users Inbox you can use the following

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  2. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3. foreach($Permission in $Inbox.Permissions){  
  4.     if($Permission.UserId.StandardUser -eq $null){  
  5.         "User : " + $Permission.UserId.PrimarySmtpAddress  
  6.     }  
  7.     else{  
  8.         "User : " + $Permission.UserId.StandardUser.ToString()  
  9.     }  
  10.     $Permission  
  11. }  
To show the FreeBusy Permissions on the Calendar Folder

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)     
  2. $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3. foreach($Permission in $Calendar.Permissions){  
  4.     $rptObj = "" | Select User,FreeBusyRights  
  5.     if($Permission.UserId.StandardUser -eq $null){  
  6.         $rptObj.User = $Permission.UserId.PrimarySmtpAddress  
  7.         $rptObj.FreeBusyRights = $Permission.ReadItems  
  8.     }  
  9.     else{  
  10.         $rptObj.User = $Permission.UserId.StandardUser.ToString()  
  11.         $rptObj.FreeBusyRights = $Permission.ReadItems  
  12.     }  
  13.     $rptObj  
  14. }  
Modifying Folder Permissions

When you want to modify folder permission using EWS you first need to get the existing ACL from the folder check to see if there is an existing ACE for the user you want to add/modify and either change the existing ACE's permission or delete it and  add a new ACE (what you are trying to avoid is duplicating the ACE which will cause an error). Here is an example of adding reviewer rights for a specific user to the Inbox in this code if it detects an existing ACE it just removes that ACE and adds a new one with reviewer rights.

  1. $UsertoAdd = "user@domain.comm"  
  2. $PermissiontoAdd = [Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::Reviewer  
  3. $existingperm = $null  
  4. foreach($fperm in $Inbox.Permissions){  
  5.     if($fperm.UserId.PrimarySmtpAddress -ne $null){  
  6.         if($fperm.UserId.PrimarySmtpAddress.ToLower() -eq $UsertoAdd.ToLower()){  
  7.                 $existingperm = $fperm  
  8.         }  
  9.     }  
  10. }  
  11. if($existingperm -ne $null){  
  12.     $Inbox.Permissions.Remove($existingperm)  
  13. }   
  14. $newfp = new-object Microsoft.Exchange.WebServices.Data.FolderPermission($UsertoAdd,$PermissiontoAdd)  
  15. $Inbox.Permissions.Add($newfp)  
  16. $Inbox.Update()  
Special considerations for the Calendar Folder

When working with calendar folder permissions you should also make sure you mirror any changes that you make to the Freebusy folder in the Non_IPM_Subtree if you don't do this you may find that you cant modify appointments even though you have rights in the folder. Eg the following is an example of giving the Default ACE (which essentially means everybody) editor access to a calendar.

  1. function addFolderPerm($folder){    
  2.     $existingperm = $null    
  3.     foreach($fperm in $folder.Permissions){    
  4.         if($fperm.UserId.StandardUser -eq $null){    
  5.             if ($fperm.UserId.PrimarySmtpAddress.ToLower() -eq $NewACLUser.ToLower()){    
  6.                 $existingperm = $fperm    
  7.             }    
  8.         }    
  9.     }    
  10.     if($existingperm -ne $null){    
  11.         $folder.Permissions.Remove($existingperm)    
  12.     }     
  13.     $newfp = new-object Microsoft.Exchange.WebServices.Data.FolderPermission($NewACLUser,$Permission)    
  14.     $folder.Permissions.Add($newfp)    
  15.     $folder.Update()    
  16. }    
  17.     
  18. "Checking : " + $MailboxName     
  19. $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)    
  20. $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidcnt)    
  21. "Set Calendar Rights"    
  22. addFolderPerm($Calendar)    
  23. $sf1 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"Freebusy Data")    
  24.     
  25. $fvFolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  26. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;    
  27.     
  28. $folderidRoot = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)    
  29. $fiResult = $Service.FindFolders($folderidRoot,$sf1,$fvFolderView)    
  30. if($fiResult.Folders.Count -eq 1){    
  31.     "Set FreeBusy Rights"    
  32.     $Freebusyfld = $fiResult.Folders[0]    
  33.     $Freebusyfld.Load()    
  34.     addFolderPerm($Freebusyfld)    
  35. }    

Reporting on all Shared folders in a Mailbox

Here's a full script that will enumerate every folder in a mailbox and check all the ACE's and report on any folders that are shared.

  1. $ReportingCollection = @()  
  2. $MailboxName = "user@domain.com"  
  3.   
  4. ## Load Managed API dll    
  5. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"    
  6.     
  7. ## Set Exchange Version    
  8. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  9.     
  10. ## Create Exchange Service Object    
  11. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  12.     
  13. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  14.     
  15. #Credentials Option 1 using UPN for the windows Account    
  16. $creds = New-Object System.Net.NetworkCredential("user@domain.com","password")     
  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. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}    
  25.     
  26. ## 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    
  27.     
  28. #CAS URL Option 1 Autodiscover    
  29. $service.AutodiscoverUrl($MailboxName,{$true})    
  30. "Using CAS Server : " + $Service.url     
  31.      
  32. #CAS URL Option 2 Hardcoded    
  33.     
  34. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  35. #$service.Url = $uri      
  36.     
  37. ## Optional section for Exchange Impersonation   
  38.   
  39. function ConvertToString($ipInputString){    
  40.     $Val1Text = ""    
  41.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){    
  42.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))    
  43.             $clInt++    
  44.     }    
  45.     return $Val1Text    
  46. }    
  47.     
  48. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  49.   
  50. # Bind to the Archive Root folder    
  51. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)     
  52. $fldRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  53.   
  54. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  55. #Deep Transval will ensure all folders in the search path are returned   
  56.    
  57. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  58. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  59. #The Search filter will exclude any Search Folders   
  60. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  61. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);     
  62. $psPropertySet.Add($PR_Folder_Path);    
  63. $fvFolderView.PropertySet = $psPropertySet;   
  64. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  65. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  66. $fiResult = $null    
  67. do {    
  68.     $fiResult = $Service.FindFolders($folderid,$sfSearchFilter,$fvFolderView)    
  69.     foreach($ffFolder in $fiResult.Folders){    
  70.         $foldpathval = $null  
  71.         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))    
  72.         {    
  73.             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)    
  74.             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }    
  75.             $hexString = $hexArr -join ''    
  76.             $hexString = $hexString.Replace("FEFF""5C00")    
  77.             $fpath = ConvertToString($hexString)    
  78.         }    
  79.         "Processing : "  + $fpath  
  80.         $ffFolder.Load()  
  81.         foreach($Permission in $ffFolder.Permissions){    
  82.             if($Permission.PermissionLevel -ne [Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::None){  
  83.                 $rptobj = "" | Select FolderPath, User, Permission  
  84.                 if($Permission.UserId.StandardUser -eq $null){   
  85.                     $rptobj.FolderPath = $fpath  
  86.                     $rptobj.User = $Permission.UserId.PrimarySmtpAddress   
  87.                     $rptobj.Permission = $Permission.PermissionLevel  
  88.                     $ReportingCollection += $rptobj  
  89.                 }    
  90.                 else{    
  91.                     $rptobj.FolderPath = $fpath  
  92.                     $rptobj.User = $Permission.UserId.StandardUser.ToString()   
  93.                     $rptobj.Permission = $Permission.PermissionLevel  
  94.                     $ReportingCollection += $rptobj     
  95.                 }    
  96.             }  
  97.         }           
  98.     }   
  99.     $fvFolderView.Offset += $fiResult.Folders.Count  
  100. }while($fiResult.MoreAvailable -eq $true)   
  101.   
  102. $ReportingCollection  
  103. $ReportingCollection | Export-Csv -NoTypeInformation -Path c:\temp\sharedfolders.csv  

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 Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You ...

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