Friday, November 11, 2016

Using the Birthday calendar in EWS in Exchange 2016 and Office365

One of the new features that has been added in Exchange 2016 and Office365 in OWA is a birthday calendar which is a dedicated calendar for the Birthday appointments that are associated with contacts. eg



Like many of the special folders in a Mailbox the folder name for this is localized so if your mailbox is set to use a different language this folder name should appear in your localized language. Unlike most of the special folders in Exchange there is no WellKnownFolder enumeration for the birthday calendar so if you want to open this folder you either need to search for it by name (as long as you know the localization of the Mailbox) or you can use the following extended property that should exist on the root mailbox folder.


So in EWS you can do something like the following to access the HexEntryId value from this extended property which you can then convert to a EWSId using the ConvertId operation and then you will be able to bind to the folder using that ID. eg


function Get-BirthDayCalendar{
 param (
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
     [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
     [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation    )
 
process{
        
     $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
     if($useImpersonation.IsPresent){
        $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
     }
     $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
     $BirthdayCalendarFolderEntryId = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,"BirthdayCalendarFolderEntryId",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary); 
     $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
     $psPropset.Add($BirthdayCalendarFolderEntryId)
     $EWSRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid,$psPropset)
     $BirthdayCalendarFolderEntryIdValue = $null
     $BirthdayCalendarFolderHexValue = $null
     if($EWSRootFolder.TryGetProperty($BirthdayCalendarFolderEntryId,[ref]$BirthdayCalendarFolderEntryIdValue)){
        $BirthdayFolderEWSId = new-object Microsoft.Exchange.WebServices.Data.FolderId((ConvertId -HexId ([System.BitConverter]::ToString($BirthdayCalendarFolderEntryIdValue).Replace("-",""))))
        $BirthdayFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$BirthdayFolderEWSId);
        return $BirthdayFolder
     }
     else
    {   
          throw [System.IO.FileNotFoundException] "folder not found."
    }
    }
}

Enumerating through birthdays and working out a persons age :

Birthdays are stored as recurring appointments (as they do occur every year) so if you want to display all the birthdays in a calendar its better to use a CalendarView to expand any recurring appointments. To determine the Age of the person associated with the calendar appointment you can use the Birthdaylocal property which holds the actual date of birth (if it was entered). eg


If you then do a Time difference between that and the Start time of the appointment that will give you the Age of the person in days which you can then convert to years using some simple math. In code this looks like

function Get-Birthdays{
     param (
      [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation    )
 process{
        
        $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
 if($useImpersonation.IsPresent){
  $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
 }
        $strtime = (Get-date).Year.ToString() + "0101"    
        $endtime = (Get-date).AddYears(1).Year.ToString() + "0101"           
        $StartDate =  [datetime]::ParseExact($strtime,"yyyyMMdd",$null)
        $EndDate =  [datetime]::ParseExact($endtime,"yyyyMMdd",$null)
        $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
        $BirthdayCalendarFolderEntryId = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,"BirthdayCalendarFolderEntryId",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary); 
        $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
        $psPropset.Add($BirthdayCalendarFolderEntryId)
 $EWSRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid,$psPropset)
        $BirthdayCalendarFolderEntryIdValue = $null
 $BirthdayCalendarFolderHexValue = $null
        if($EWSRootFolder.TryGetProperty($BirthdayCalendarFolderEntryId,[ref]$BirthdayCalendarFolderEntryIdValue)){
   $BirthdayFolderEWSId = new-object Microsoft.Exchange.WebServices.Data.FolderId((ConvertId -HexId ([System.BitConverter]::ToString($BirthdayCalendarFolderEntryIdValue).Replace("-",""))))
   $BirthdayFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$BirthdayFolderEWSId);
   $CalendarView = New-Object Microsoft.Exchange.WebServices.Data.CalendarView($StartDate,$EndDate,1000)    
            $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
            $BirthDayLocal = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Address,0x80DE, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime)
            $psPropset.Add($BirthDayLocal)
            $CalendarView.PropertySet = $psPropset
            $fiItems = $service.FindAppointments($BirthdayFolder.Id,$CalendarView)    
            foreach($Item in $fiItems.Items){      
                $exportObj = "" | Select subject,StartTime,EndTime,DateOfBirth,Age
                $exportObj.StartTime = $Item.Start
                $exportObj.EndTime = $Item.End
                $exportObj.Subject = $Item.Subject
                $BirthDavLocalValue = $null
                if($Item.TryGetProperty($BirthDayLocal,[ref]$BirthDavLocalValue)){
                    $exportObj.DateOfBirth = $BirthDavLocalValue
                    $exportObj.Age = [Math]::Truncate(($Item.Start  $BirthDavLocalValue).TotalDays / 365); 
                }
                Write-Output $exportObj
            }
        }
 else
 {   
         throw [System.IO.FileNotFoundException] "folder not found."
 }
    }
    
}

I've put a copy of this script up on github at https://github.com/gscales/Powershell-Scripts/blob/master/BirthDayCalendar.ps1

Wednesday, October 19, 2016

Using EWS to upload / set user photos in Exchange Online and 2016

Between Exchange 2013 and 2016 there where few new operations introduced into EWS, one operation that was introduced was the SetUserPhoto operation which pairs with the GetUserPhoto operation that was introduced in Exchange 2013.

What this operation does is allows you to set/upload a high resolution photo for a user to be used in Exchange and Skype for Business in Exchange Online or Exchange 2016. A little bit more about the high ressolution user photo is that when you set this it uploads this as an item in the Non_IPM_Root of the Mailbox (so it is not visible to the user) with a message class of IPM.UserPhoto if you where to look at a Mailbox with a Mapi Editor you can see the object that this creates. eg


If you look at the UserPhoto Object itself you can see the different size formats are stored ready to access in a number of different Binary Mapi properties eg


So what the SetUserPhoto operation does is handles creating this object and all the different photo formats that applications might require.

Currently there isn't anything in the EWS Managed API to take advantage of this new operation so to use this you can either use the WSDL Proxy Objects (generated against Exchange 2016 or Exchange Online) or just raw soap like the following.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <RequestServerVersion Version="Exchange2016" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" />
  </soap:Header>
  <soap:Body>
    <SetUserPhoto xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
      <Email>$MailboxName</Email>
      <Content>$Content</Content>
      <TypeRequested>UserPhoto</TypeRequested>
    </SetUserPhoto>
  </soap:Body>
</soap:Envelope>

I've put together a Powershell script that use the EWS Managed API to do the discovery and then uses raw soap to do the upload the photo.. I've put this script up on GitHub here https://github.com/gscales/Powershell-Scripts/blob/master/Upload-Photo.ps1

To use this script you use the cmdlet like

Set-PhotoEWS -MailboxName mailbox@domain -Photo c:\temp\photo1.jpg

The script itself looks like

function Connect-Exchange{ 
    param( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [string]$url
    )  
  Begin
   {
  Load-EWSManagedAPI
  
  ## Set Exchange Version  
  $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013
    
  ## Create Exchange Service Object  
  $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
    
  ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
    
  #Credentials Option 1 using UPN for the windows Account  
  #$psCred = Get-Credential  
  $creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
  $service.Credentials = $creds      
  #Credentials Option 2  
  #service.UseDefaultCredentials = $true  
   #$service.TraceEnabled = $true
  ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
    
  Handle-SSL 
    
  ## 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  
    
  #CAS URL Option 1 Autodiscover  
  if($url){
   $uri=[system.URI] $url
   $service.Url = $uri    
  }
  else{
   $service.AutodiscoverUrl($MailboxName,{$true})  
  }
  Write-host ("Using CAS Server : " + $Service.url)   
     
  #CAS URL Option 2 Hardcoded  
    
  #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
  #$service.Url = $uri    
    
  ## Optional section for Exchange Impersonation  
    
  #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  if(!$service.URL){
   throw "Error connecting to EWS"
  }
  else
  {  
   return $service
  }
 }
}

function Load-EWSManagedAPI{
    param( 
    )  
  Begin
 {
  ## Load Managed API dll  
  ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
  $EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
  if (Test-Path $EWSDLL)
      {
      Import-Module $EWSDLL
      }
  else
      {
      "$(get-date -format yyyyMMddHHmmss):"
      "This script requires the EWS Managed API 1.2 or later."
      "Please download and install the current version of the EWS Managed API from"
      "http://go.microsoft.com/fwlink/?LinkId=255472"
      ""
      "Exiting Script."
      #exit
      } 
   }
}

function Handle-SSL{
    param( 
    )  
  Begin
 {
  ## Code From http://poshcode.org/624
  ## Create a compilation environment
  $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
  $Compiler=$Provider.CreateCompiler()
  $Params=New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.GenerateExecutable=$False
  $Params.GenerateInMemory=$True
  $Params.IncludeDebugInformation=$False
  $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
  $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
  $TAAssembly=$TAResults.CompiledAssembly

  ## We now create an instance of the TrustAll and attach it to the ServicePointManager
  $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
  [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

  ## end code from http://poshcode.org/624

 }
}


function Set-PhotoEWS  {
     param( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
  [Parameter(Position=4, Mandatory=$true)] [String]$Photo
    )  
  Begin
 {
  
        if($url){
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials -url $url 
  }
  else{
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
  }
  if($useImpersonation.IsPresent){
   $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  }
        [Byte[]]$FileContent = [System.IO.File]::ReadAllBytes($Photo);
        $Base64Content = [System.Convert]::ToBase64String($FileContent);
        $request = Get-SetPhotoRequest -MailboxName $MailboxName -Content $Base64Content
        $SetPhotoRequest = [System.Net.HttpWebRequest]::Create($service.url.ToString());
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($request);
        $SetPhotoRequest.ContentLength = $bytes.Length;
        $SetPhotoRequest.ContentType = "text/xml";
        $SetPhotoRequest.UserAgent = "EWS Photo upload";            
        $SetPhotoRequest.Headers.Add("Translate", "F");
        $SetPhotoRequest.Method = "POST";
        $SetPhotoRequest.Credentials =  New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
        $RequestStream = $SetPhotoRequest.GetRequestStream();
        $RequestStream.Write($bytes, 0, $bytes.Length);
        $RequestStream.Close();
        $SetPhotoRequest.AllowAutoRedirect = $true;
        $Response = $SetPhotoRequest.GetResponse().GetResponseStream()
        $sr = New-Object System.IO.StreamReader($Response)
        [XML]$xmlReposne = $sr.ReadToEnd()
        if($xmlReposne.Envelope.Body.SetUserPhotoResponse.ResponseClass -eq "Success"){
            Write-Host("Photo Uploaded")
        }
        else
        {
            Write-Host("Upload failed")
            Write-Host  $sr.ReadToEnd()
        } 

    }
}

function Get-SetPhotoRequest
{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
        [Parameter(Position=0, Mandatory=$true)] [String]$Content
    )  
  Begin
 {

        $request = @"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <RequestServerVersion Version="Exchange2016" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" />
  </soap:Header>
  <soap:Body>
    <SetUserPhoto xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
      <Email>$MailboxName</Email>
      <Content>$Content</Content>
      <TypeRequested>UserPhoto</TypeRequested>
    </SetUserPhoto>
  </soap:Body>
</soap:Envelope>
"@
    return $request
    }
}


Wednesday, October 05, 2016

EWS Basics Accessing and using Shared mailboxes

One of the most commonly asked and misunderstood things that people starting out using Exchange Web Services get wrong is accessing a Shared Mailbox or a Delegated Mailbox other then that of security principal (another way of saying credentials) you are authenticating with.

Autodiscover

One of the first confusion points is with Autodiscover, for people who aren't that familiar with Exchange its important to understand that all Autodisover does is gives you the endpoint to connect to for Exchange Web Services. Some people confuse using the following line

$service.AutodiscoverUrl("Mailbox@domain.com",{$true})

To mean all future EWS requests will go the mailbox you use here which isn't the case all this will do is return the most optimized endpoint for EWS request for that particular user.

Authentication

By default nobody has access to a Mailbox other then the owner of that mailbox, a common problem that people have is to believe they can use the admin account to access any users Mailbox content .  Access to a Mailbox needs to be granted via
  • Adding the user as a Delegate in Outlook or via the EWS Delegate operations
  • Giving the user full access using Add-MailboxPermission in the Exchange Management Shell
  • Grant EWS Impersonations rights on the Mailbox via the Application Impersonation RBAC role
  • Give Access to particular mailbox folder in Outlook or via Add-MailboxFolderPermssion
Accessing a Shared Mailboxes folder

To Access a Mailbox folder in EWS you need to know the EWSId of the folder, the one exception to this rule are the WellKnownFolders like the Inbox,Contacts,Calendar etc. With these WellKnowFolders you can tell EWS which folder you want in which mailbox without knowing the EWSId of that folder.

Eg to Access the Inbox in a Shared Mailbox you use the FolderId overload to define the folderId you want to access and then bind to that folder


$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName) 
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

If its a user created folder you want to access then this is where some complexity comes in, to access the folder you need to get the EWSId of that folder. The easiest way to do this would be to search for that folder within the target mailbox, however depending on what rights you have that this may or may not be a problem. But if you do have Full access or Impersonation rights to a Mailbox then to access a usercreated folder turn the folder you want to access into a path like \\Inbox\folder1\folder2 and you can then use a function like this


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")
  }
 }
}

Once you have the EWSId of the Folder you can use that in FindItems Operation or another other EWS operation that takes a FolderId to do what you want. For Example

Sending Email As a Shared Mailbox

To send a message as another user you need to first have either SendAS permissions to that Mailbox or Send on Behalf off (the latter will mean the message will be marked as Sent On Behalf)

The first thing in you code you want to do is bind to the SentItems folder of the Mailbox you want to send as eg

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)   
$SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

Then when you create a message to Send set the From address to the Mailbox you want to SendAs and set the SentItems FolderId to the Target mailbox so a copy of what you will be sending will be saved to the SentItems folder of that mailbox eg


function Send-EWSMessage  {
     param( 
             [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
  [Parameter(Position=6, Mandatory=$true)] [String]$To,
  [Parameter(Position=7, Mandatory=$true)] [String]$Subject,
  [Parameter(Position=8, Mandatory=$true)] [String]$Body,
  [Parameter(Position=9, Mandatory=$false)] [String]$Attachment
                )  
  Begin
 {
  if($url){
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials -url $url 
  }
  else{
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
  }
  if($useImpersonation.IsPresent){
   $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  }
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)   
  $SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $EmailMessage = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service  
  $EmailMessage.Subject = $Subject
  #Add Recipients    
  $EmailMessage.ToRecipients.Add($To)  
  $EmailMessage.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody  
  $EmailMessage.Body.BodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::HTML  
  $EmailMessage.Body.Text = "Body"  
  $EmailMessage.From = $MailboxName
  if($Attachment)
  {   
   $EmailMessage.Attachments.AddFileAttachment($Attachment)
  }
  $EmailMessage.SendAndSaveCopy($SentItems.Id) 
  
 }
}




Tuesday, September 20, 2016

Search for Credit Card numbers in Address Book\Contact data using EWS

Information security and data breaches are a hot topic at the moment, there seems to be a constant stream of data breaches and vulnerabilities in different products being exploited on a daily basis. One topic that was brought up in the last few weeks has been Address Book data https://www.wired.com/2016/09/people-please-dont-store-private-data-address-book/ . Address books can be the proverbial open window on the house with bars on door and maybe not something that is commonly thought about. 

If you want to detect if people are using Address book to store confidential information it can be a challenge because this data isn't searchable via a conventional eDiscovery type search. But this is where a scripted enumeration and filtering approach can do the job.

I posted a Contacts Powershell module that consolidated a lot of EWS contacts function into one script last year so for this post I've extended this to include a Search that will enumerate all the contacts in a Mailbox's contacts folder and Search for Credit Card Number and Social Security Numbers being stored in any of the Phone number properties and email address properties. The script I've posted does some filtering to separate out the Host part of email address to test so for example if somebody puts the 12345678@fakedomain it will separate out 12345678 to test.

Searching for Credit Card Numbers

To Search for Credit card number you basically need two ingredients, the first is the luhn algorithm which is a Modulus 10 algorithm that will validate if a number sequence is a credit card number. Then you run a number of Regex patterns to determine the type of card and who issued it. The good thing is there are plenty libraries up on GitHub that will  already do this so there is no need to write any code for this. The one I decided to use was https://github.com/gustavofrizzo/CreditCardValidator

Searching for Social Security Numbers (or your own custom RegEx)

To Search for SSI I've used the Google Braintrust Regex of

$SSN_Regex = "^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}$"

I've posted up the script for this https://github.com/gscales/Powershell-Scripts/blob/master/EWSContacts/EWSContactFunctions.ps1 I've put a compiled version of the creditcard validation library I used which need to be in the same directory as the module here https://github.com/gscales/Powershell-Scripts/raw/master/EWSContacts/CreditCardValidator.dll

To Run the script you just use something like the following to produce a report of any hits in  a Mailbox. Note because of the Regexs used for the SSI and the fact that phone numbers can easily look like validate credit card numbers this script can produce a large number of false positives.

Search-ContactsForCCNumbers -MailboxName mailbox@domain.com | Export-csv -NoTypeInformation -Path c:\temp\CCrep.csv



Friday, September 02, 2016

How to Like\Unlike an Item using EWS in Exchange Online

Likes and Mentions are a new feature in Exchange Online (in OWA) that was introduced late last year in First Release for Office365. With the focused Inbox now being rolled out to replace clutter these are some of the new social user curation type features that could change the user experience (hopefully for the better) in the coming years. While none of these features are new to those people using other Social platforms like facebook, twitter etc they do offer a world of new possibilities to those that have a little imagination.

In this post I'm going to look at how you can Like an item using Exchange Web Services eg

Currently there is no real documentation on the use of Likes in any API or how they are delivered in Exchange Online so care should be taken as this may mean the feature is subject to change in any of the future service updates.

Versioning your Requests

To use likes fully you need to make sure you version your EWS requests (which involves setting the ServerRequestVersion in the SOAP header) to V2015_10_05 or higher.  The Like information is returned by Exchange as a Strongly Type property in EWS (LikeType). If you look at a Response that includes the Like information in the SOAP response you should see both Like and LikePreview returned eg

<t:Likes>
  <t:Like>
    <t:Id>150bb06c-1c9a-4ac2-8b55-8cf15854b555</t:Id>
    <t:CreatedBy>
      <t:Name>Glen Scales</t:Name>
      <t:EmailAddress>gscales@datarumble.com</t:EmailAddress>
      <t:ExternalObjectId>150bb06c-1c9a-4ac2-8b55-8cf15854b555</t:ExternalObjectId>
    </t:CreatedBy>
    <t:CreatedDateTime>2016-08-28T10:26:40.299Z</t:CreatedDateTime>
    <t:ServerCreatedDateTime>2016-08-28T10:26:40.299Z</t:ServerCreatedDateTime>
  </t:Like>
</t:Likes>
<t:LikesPreview>
  <t:LikeCount>1</t:LikeCount>
  <t:IsLiked>true</t:IsLiked>
  <t:Likers>
    <t:Name>Glen Scales</t:Name>
    <t:EmailAddress>gscales@datarumble.com</t:EmailAddress>
    <t:RoutingType>SMTP</t:RoutingType>
    <t:MailboxType>Mailbox</t:MailboxType>
    <t:ExternalObjectId>150bb06c-1c9a-4ac2-8b55-8cf15854b555</t:ExternalObjectId>
  </t:Likers>
</t:LikesPreview>
<t:AtAllMention>false</t:AtAllMention>

If you have the latest proxy objects from the Exchange Online WSDL then you should see the Likes and LikePreview property collections in the ItemType Class. In the latest EWS Managed API from github https://github.com/OfficeDev/ews-managed-api only the Likes class is currently available.

Liking an Item (Unsupported)

The EWS LikeItem operation currently has no definition in the Services.WSDL so liking an Item via EWS is currently unsupported. However you can still use the operation as long as you construct the request using Raw SOAP message eg a request to like or unlike and item using EWS look like

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
  <soap:Header>
    <t:RequestServerVersion Version="V2015_10_05"/>
  </soap:Header>
  <soap:Body xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
    <LikeItem>
      <ItemId Id="AAM.." ChangeKey="CQA.."/>
      <IsUnlike>false</IsUnlike>
 </LikeItem>
  </soap:Body>
</soap:Envelope>

As this is an unsupported operation if you do something like try to like the same item twice you will get a 500 error rather then a nice SOAP based error response. I've put together a scrip that allows you to search for an Item via subject and like or unlike it using EWS. I've put this up on GitHub here https://github.com/gscales/Powershell-Scripts/blob/master/EWSLIkeMessage.ps1

Wednesday, August 17, 2016

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 need to authorize it in you tenant (eg build a small app that can do that which will prompt for authorization). One that is done you then need to set that ClientId variable in the sketch

String ClientId = "8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307";

I've put a copy of this Sketch up https://github.com/gscales/Arduino-MRK1000/blob/master/REST-Office365SendSample.ino the code looks like


#include <ArduinoJson.h>

#include <Base64.h>
#include <ArduinoHttpClient.h>

/*
This example creates a client object that connects and transfers
data using always SSL.

It is compatible with the methods normally related to plain
connections, like client.connect(host, port).

Written by Arturo Guadalupi
last revision November 2015

*/

#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "SSOecure"; //  your network SSID (name)
char pass[] = "pass@#";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)
const size_t MAX_CONTENT_SIZE = 5120;

//Office365 Credentials
String ExUserName = "user@domain.com";
String ExPassword = "passw";
String ClientId = "8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307";
//Message Details
String Auth = ExUserName + ":" + ExPassword;
String Subject = "Subject of the Message";
String To = "mailbox@domain.com";
String Body = "Something happening in the Body";
String Access_Token = "";

bool DebugResponse = false;

int cCount = 0;

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiSSLClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  TokenAuth(ClientId,ExUserName,ExPassword);
  if(Access_Token.length() > 0){
      Serial.println("Send Message");
      SendRest(Access_Token,To,Subject,Body);
      Serial.println("Done");
  }

}

void TokenAuth(String ClientId,String UserName, String Password)
{
     char endOfHeaders[] = "\r\n\r\n";
     char passwordCA[Password.length()+1];
     Password.toCharArray(passwordCA,Password.length()+1);
     String content = "resource=https%3A%2F%2Foutlook.office.com&client_id=" + ClientId + "&grant_type=password&username=" + ExUserName + "&password=" + URLEncode(passwordCA) + "&scope=openid";
     Serial.println("\nStarting connection to server...");
     if (client.connectSSL("login.windows.net", 443)) {
       Serial.println("connected to server");
       client.print("POST ");
       client.println("https://login.windows.net/Common/oauth2/token HTTP/1.1");
       client.println("Content-Type: application/x-www-form-urlencoded");
       client.println("client-request-id: " + ClientId);
       client.println("return-client-request-id: true");
       client.println("x-client-CPU: x32");
       client.println("x-client-OS: Arduino");
       client.println("Host: login.windows.net");
       client.print("Content-Length: ");
       client.println(content.length());
       client.println("Expect: 100-continue");
       client.println(""); 
       client.println(content);
       client.find(endOfHeaders);
       bool ok =  client.find(endOfHeaders);
       if (!ok) {
         Serial.println("No response or invalid response!");
       }
       else{
         Serial.println("Request Okay");
       }
       char response[MAX_CONTENT_SIZE];
       readAuthReponse(response, sizeof(response));
    }
}

void readAuthReponse(char* content, size_t maxSize) {
  size_t length = client.readBytes(content, maxSize);
  content[length] = 0;
  Serial.println(content);
  content[length] = 0;
  DynamicJsonBuffer jsonBuffer;
  JsonObject&root = jsonBuffer.parseObject(content);
  if (!root.success()) {
    Serial.println("JSON parsing failed!");
  }
  else{
      String token = root["access_token"]; 
      Access_Token = token;
  }
  
}


String URLEncode(const char* msg)
{
    const char *hex = "0123456789abcdef";
    String encodedMsg = "";

    while (*msg!='\0'){
        if( ('a' <= *msg && *msg <= 'z')
                || ('A' <= *msg && *msg <= 'Z')
                || ('0' <= *msg && *msg <= '9') ) {
            encodedMsg += *msg;
        } else {
            encodedMsg += '%';
            encodedMsg += hex[*msg >> 4];
            encodedMsg += hex[*msg & 15];
        }
        msg++;
    }
    return encodedMsg;
}


void SendRest(String Bearer,String MessageTo, String MessageSubject, String MessageBody)
{
    //DebugResponse = true;
    char endOfHeaders[] = "\r\n\r\n";  
    String content = "{";
    content += "        \"Message\": {";  
    content += "           \"Subject\": \"" + MessageSubject + "\",";  
    content += "            \"Body\": {";  
    content += "                \"ContentType\": \"Text\",";  
    content += "                \"Content\": \"" + MessageBody + "\"";  
    content += "                       },";  
    content += "            \"ToRecipients\": [";  
    content += "                {";  
    content += "                    \"EmailAddress\": {";  
    content += "                        \"Address\": \"" + MessageTo + "\"";  
    content += "                    }";  
    content += "                }";  
    content += "            ]";  
    content += "        },";  
    content += "        \"SaveToSentItems\": \"false\"";  
    content += "    }";  
    Serial.println("\nStarting connection to server...");
    // if you get a connection, report back via serial:
    if (client.connectSSL("outlook.office365.com", 443)) {
      Serial.println("connected to server");
      client.print("POST ");
      client.print("https://outlook.office365.com/api/v2.0/me/sendmail");
      client.println(" HTTP/1.1"); 
      client.print("Host: "); 
      client.println("outlook.office365.com");
      client.print("Authorization: Bearer ");
      client.println(Bearer); 
      client.println("Connection: close");
      client.print("Content-Type: ");
      client.println("application/json");
      client.println("User-Agent: mrk1000Sender");
      client.print("Content-Length: ");
      client.println(content.length());
      client.println();
      client.println(content);
      char okayString[] = "HTTP/1.1 202 Accepted";
      bool ok =  client.find(okayString);
      if (!ok) {
        Serial.println("Message Sent");
      }
      else{
        Serial.println("Request Failed");
      }
    }

}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if(DebugResponse){
  while (client.available()) {
    char c = client.read();
    Serial.print(c); 
  }
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();
    // do nothing forevermore:
    while (true);
  }
}


void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}