Skip to main content

Reporting on forwarding rules in Mailboxes and Public Folders via a script

Reporting on rules in mailboxes and public folders can get a little challenging for the humble sysadmin. Because most the time the setting of these rules is out of your control knowing where some rules are forwarding can be a little scary (and in some cases can be against company policy or breach privacy laws). There are a few ways to manipulate rules one of the most often used is the rule.dll which can be used to create and enumerate rules while this is useful it still only offers you the hex value of the binary action property which contains the list of the recipient addresses for a forwarding rule. An active rule in a mailbox or public folders is a special message in a mailbox of type IPM.Rule.Message. In CDO 1.2 you can access these messages by using the hidden messages collection on a folder. If a rule is a forwarding rule then the email address’s the rule is forwarding to gets stored in the PR_RuleMsgActions (0x65EF0102) Mapi Property on that IPM.Rule.Message. Unfortunately this property is a binary property whose format is undocumented. Reverse engineering a complete decode for this property is a little hard and time consuming so what I did was just concentrate on matching the patterns within the binary property (its kind of like doing a jigsaw in the dark) but armed with my trusty ASCII chart I came up with some formulas that can separate out the text address’s from the rest of the information that is stored in the property and produce some meaning results (well it works for me anyway).

I’ve created two versions of this script the first loops though all the mailboxes on a server and looks at rules in the inbox of each mailbox. The second script loops though all the public folders on a server and reports on any forwarding rules in those public folders. The results are output to the screen and also a CSV file is created on the c: drive with the results.

The flow of the mailbox script is it takes in the name of the server as a command line parameter and then does a query of active directory for all the visible mailboxes on this server. Its then opens all the mailboxes and checks the hidden collection for any IPM.Rule.Message rule messages and then checks the PR_RuleMsgActions property on any rule messages it finds. If any address objects are found these are output to the command line and also stored in an array so they can be written to a CSV file at the end of the iteration. Once all rules have been checked for a mailbox the result is written in to a CSV file and it moves on to the next mailbox. The public folders script works similarly except instead of querying for mailboxes via Active Directory it uses CDO to loop though the folders collection and any subfolder therein.

To run the mailbox script you need to add the name of the server you want it to run against as a command-line parameter eg cscript mbxruleloop.vbs servername .With the public folders script you need to configure the servername and the name of mailbox on the server you want to report against (this is so the script can logon to the server the actually mailbox content isn’t accessed).

I’ve posted a downloadable copy of the script here the Mailbox script looks like

servername = wscript.arguments(0)
PR_HAS_RULES = &H663A000B
PR_URL_NAME = &H6707001E
PR_CREATOR = &H3FF8001E
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\mbxforwardingRules.csv",2,true)
wfile.writeline("Mailbox,FolderPath,Creator,AdressObject,SMTPForwdingAddress")
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = "<LDAP://" & strNameingContext & ">;(&(objectCategory=msExchExchangeServer)(cn="
& Servername & "));cn,name,legacyExchangeDN;subtree"
Com.ActiveConnection = Conn
Com.CommandText = svcQuery
Set Rs = Com.Execute
while not rs.eof
GALQueryFilter = "(&(&(&(& (mailnickname=*)(!msExchHideFromAddressLists=TRUE)(|
(&(objectCategory=person) (objectClass=user)(msExchHomeServerName=" &
rs.fields("legacyExchangeDN") & ")) )))))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter & ";distinguishedName,mailnickname;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery
Set Rs1 = Com.Execute
while not Rs1.eof
call procmailboxes(servername,rs1.fields("mailnickname"))
wscript.echo rs1.fields("mailnickname")
rs1.movenext
wend
rs.movenext
wend
rs.close
wfile.close
set fso = nothing
set conn = nothing
set com = nothing
wscript.echo "Done"


Sub procmailboxes(servername,mailboxname)

set objSession = CreateObject("MAPI.Session")
objSession.Logon "","",false,true,true,true,servername & vbLF & mailboxname
Set objInfoStores = objSession.InfoStores
set objInfoStore = objSession.GetInfoStore
set Inbox = objSession.Inbox
if inbox.fields.item(PR_HAS_RULES) = true then
Set objMessages = inbox.HiddenMessages
for Each objMessage in objMessages
if objMessage.type = "IPM.Rule.Message" then
call procrule(objMessage,mailboxname,inbox.fields.item(PR_URL_NAME).value)
end if
next
end if

end sub

sub procrule(objmessage,MailboxName,folderpath)
frule = false
splitarry = split(hextotext(objmessage.fields.item(&H65EF0102)),chr(132),-1,1)
if ubound(splitarry) <> 0 then
wscript.echo
wscript.echo "Mailbox Name :" & MailboxName
wscript.echo "Folder Path :" & folderpath
wscript.echo "Rule Created By : " & objmessage.fields.item(PR_CREATOR).value
mbname = MailboxName
fpath = folderpath
creator = objmessage.fields.item(PR_CREATOR).value
frule = true
end if
tfirst = 0
addcount = 1
for i = 0 to ubound(splitarry)
addrrsplit = split(splitarry(i),chr(176),-1,1)
for j = 0 to ubound(addrrsplit)
addrcontsep = chr(3) & "0"
if instr(addrrsplit(j),addrcontsep) then
if tfirst = 1 then addcount = addcount + 1
wscript.echo
wscript.echo "Address Object :" & addcount
redim Preserve resarray(1,1,1,1,1,addcount)
resarray(1,0,0,0,0,addcount) = mbname
resarray(1,1,0,0,0,addcount) = fpath
resarray(1,1,1,0,0,addcount) = creator
if instr(addrrsplit(j),"0/o=") then
resarray(1,1,1,1,0,addcount) = mid(addrrsplit(j),(instr(addrrsplit(j),"0/o=")+1),len(addrrsplit(j)))
WScript.echo "ExchangeDN :" & mid(addrrsplit(j), (instr(addrrsplit(j),"0/o=")+1),len(addrrsplit(j)))
else
WScript.echo "Address :" & mid(addrrsplit(j),3, len(addrrsplit(j)))
resarray(1,1,1,1,0,addcount) = mid(addrrsplit(j),3,len(addrrsplit(j)))
end if
tfirst = 1
end if
smtpsep = Chr(254) & "9"
if instr(addrrsplit(j),smtpsep) then
slen = instr(addrrsplit(j),smtpsep) + 2
elen = instr(addrrsplit(j),chr(3))
Wscript.echo "SMTP Forwarding Address : " & mid(addrrsplit(j),slen,(elen-slen))
resarray(1,1,1,1,1,addcount) = mid(addrrsplit(j),slen,(elen-slen))
end if
next
next
if frule = true then
for r = 1 to ubound(resarray,6)
wfile.writeline(resarray(1,0,0,0,0,r) & "," & resarray(1,1,0,0,0,r) & "," &
resarray(1,1,1,0,0,r) & "," & resarray(1,1,1,1,0,r) & "," &
resarray(1,1,1,1,1,r))
next
end if

end sub


Function hextotext(binprop)
arrnum = len(binprop)/2
redim aout(arrnum)
slen = 1
for i = 1 to arrnum
if CLng("&H" & mid(binprop,slen,2)) <> 0 then
aOut(i) = chr(CLng("&H" & mid(binprop,slen,2)))
mid(binprop,slen,2)))
end if
slen = slen+2
next
hextotext = join(aOUt,"")
end function
 

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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 I wrote th

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 Graph is limited to a m
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.