Wednesday, December 02, 2015

Finding RMS Items in a Mailbox using EWS

If you want to search for emails that have been protected using AD Rights Managed Service using EWS there are a few challenges. How RMS works with Email it is documented in the following Exchange Protocol document https://msdn.microsoft.com/en-us/library/cc463909(v=exchg.80).aspx. The important part when it comes to searching is PidNameContentClass property https://msdn.microsoft.com/en-us/library/office/cc839681.aspx which on RMS messages gets set to rpmsg.message. So to search for this Internet Header you can use a SearchFilter like the following to define the ExtendProperty to search folder

$contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
$sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 

Putting it together in a script that searches a Folder in a Mailbox based on a MailboxName and FolderPath This script is on GitHub https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1  (An important point to note while you can find email that has been protected using RMS with EWS you won't be able to read the encrypted contents using EWS).

function Get-RMSItems{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$true)] [String]$FolderPath

 )
 begin
 {
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $Folder = Get-FolderFromPath -FolderPath $FolderPath -MailboxName $MailboxName -service $service 
  $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
  #Define ItemView to retrive just 1000 Items    
  $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  $fiItems = $null    
  do{    
      $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)    
      #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
      foreach($Item in $fiItems.Items){      
    Write-Output $Item
      }    
      $ivItemView.Offset += $fiItems.Items.Count    
  }while($fiItems.MoreAvailable -eq $true)  
 
 }
}

function Get-FolderFromPath{
 param (
   [Parameter(Position=0, Mandatory=$true)] [string]$FolderPath,
   [Parameter(Position=1, Mandatory=$true)] [string]$MailboxName,
   [Parameter(Position=2, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=3, Mandatory=$false)] [Microsoft.Exchange.WebServices.Data.PropertySet]$PropertySet
    )
 process{
  ## Find and Bind to Folder based on Path  
  #Define the path to search should be seperated with \  
  #Bind to the MSGFolder Root  
  $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)   
  $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  #Split the Search path into an array  
  $fldArray = $FolderPath.Split("\") 
   #Loop through the Split Array and do a Search for each level of folder 
  for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
         #Perform search based on the displayname of each folder level 
         $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
   if(![string]::IsNullOrEmpty($PropertySet)){
    $fvFolderView.PropertySet = $PropertySet
   }
         $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
         $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
         if ($findFolderResults.TotalCount -gt 0){ 
             foreach($folder in $findFolderResults.Folders){ 
                 $tfTargetFolder = $folder                
             } 
         } 
         else{ 
             Write-host ("Error Folder Not Found check path and try again")  
             $tfTargetFolder = $null  
             break  
         }     
     }  
  if($tfTargetFolder -ne $null){
   return [Microsoft.Exchange.WebServices.Data.Folder]$tfTargetFolder
  }
  else{
   throw ("Folder Not found")
  }
 }
}

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
}

One last sample that does a statistics report of all RMS items in a Mailbox using a SearchFilter on the AllItems Search Folder (which is created by the Outlook Desktop client) this outputs a report of the RMS Items and the size of those item in each folder that looks like


This script is on GitHub at https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
} 

function Get-RMSItems-AllItemSearch{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials

 )
 begin
 {
  $FolderCache = @{}
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)  
  $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  GetFolderPaths -FolderCache $FolderCache -service $service -rootFolderId $MsgRoot.Id
  $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);
  $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)
  $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
  $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;
  $sf1 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"2")
  $sf2 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"allitems")
  $sfSearchFilterCol = new-object  Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And)
  $sfSearchFilterCol.Add($sf1)
  $sfSearchFilterCol.Add($sf2)
  $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilterCol,$fvFolderView)
  $fiItems = $null
  $RptCollection = @{}
  $ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
  if($fiResult.Folders.Count -eq 1)
  {
   $Folder = $fiResult.Folders[0]
      $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
   $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
   $fiItems = $null    
   do{    
       $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)    
        #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
       foreach($Item in $fiItems.Items){     
     if($FolderCache.ContainsKey($Item.ParentFolderId.UniqueId))
     {
      if($RptCollection.ContainsKey($FolderCache[$Item.ParentFolderId.UniqueId]))
      {
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalItems++
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalSize+= $Item.Size
      }
      else
      {
       $fldRptobj = "" | Select FolderName,TotalItems,TotalSize
       $fldRptobj.FolderName = $FolderCache[$Item.ParentFolderId.UniqueId]
       $fldRptobj.TotalItems = 1
       $fldRptobj.TotalSize = $Item.Size 
       $RptCollection.Add($fldRptobj.FolderName,$fldRptobj)
      }     
     }
       }    
       $ivItemView.Offset += $fiItems.Items.Count    
   }while($fiItems.MoreAvailable -eq $true)    
   
  }
  write-output $RptCollection.Values
 }
 

}

function GetFolderPaths
{
 param (
      [Parameter(Position=0, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.FolderId]$rootFolderId,
   [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=2, Mandatory=$true)] [PSObject]$FolderCache,
   [Parameter(Position=3, Mandatory=$false)] [String]$FolderPrefix
    )
 process{
 #Define Extended properties  
 $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
 $PR_MESSAGE_SIZE_EXTENDED = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3592, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Long);
 #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling  
 $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)  
 #Deep Transval will ensure all folders in the search path are returned  
 $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;  
 $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
 $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
 #Add Properties to the  Property Set  
 $psPropertySet.Add($PR_Folder_Path);  
 $psPropertySet.Add($PR_MESSAGE_SIZE_EXTENDED)
 $fvFolderView.PropertySet = $psPropertySet;  
 #The Search filter will exclude any Search Folders  
 $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")  
 $fiResult = $null  
 #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox  
 do 
 {  
     $fiResult = $service.FindFolders($rootFolderId,$sfSearchFilter,$fvFolderView)  
     foreach($ffFolder in $fiResult.Folders){
         #Try to get the FolderPath Value and then covert it to a usable String 
   $foldpathval = $null
         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))  
         {  
             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)  
             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }  
             $hexString = $hexArr -join ''  
             $hexString = $hexString.Replace("FEFF", "5C00")  
             $fpath = ConvertToString($hexString)  
         }
   if($FolderCache.ContainsKey($ffFolder.Id.UniqueId) -eq $false)
   {
    if ([string]::IsNullOrEmpty($FolderPrefix)){
     $FolderCache.Add($ffFolder.Id.UniqueId,($fpath)) 
    }
    else
    {
     $FolderCache.Add($ffFolder.Id.UniqueId,("\" + $FolderPrefix + $fpath)) 
    }
   }
     } 
     $fvFolderView.Offset += $fiResult.Folders.Count
 }while($fiResult.MoreAvailable -eq $true)  
 }
}