Monday, May 07, 2012

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