Advanced Office 365 Routing: Locking Down Exchange On-Premises when MX points to Office 365
Published Feb 15 2019 07:53 AM 74.6K Views

We often get request from customers to control mail flow routing in a hybrid deployment, for various compliance requirements. Achieving the desired routing greatly depends on where the MX record is pointed to and the involvement of 3rd party mail gateways. Also, use of Centralized Mail Transport and the two mandatory Office 365 native domains - tenant.onmicrosoft.com and tenant.mail.onmicrosoft.com may make it even more complex. In this article, we will discuss the scenario, which is recommended for most hybrid organizations, where MX is pointed to EOP and customer wants to restrict their on-premises Exchange servers to only accept emails from their own Office 365 tenant. Before we start, we highly recommend that you go through the following articles to understand the basics of Hybrid mail flow:

hybmailflow1 The above diagram shows mail routing for contoso.com. Their MX record is pointed to Office365. This means on-premises Exchange servers are not supposed to receive external emails directly. Inbound email to Contoso’s On-premises servers will always originate from or relay through their Office 365 tenant. Contoso wants to block direct email delivery from other Office 365 tenants like fabricam.com to their on-premises Exchange Servers, because that would bypass policies and rules created on their Office 365 tenant. In a hybrid Setup, mail from Exchange Online will be received by the on-premises Exchange server either by the Default Frontend Receive Connector or the “Inbound from Office 365” receive Connector created by hybrid configuration wizard. By default, “Inbound from Office 365” Receive Connector will have all Office 365 IP Address ranges as allowed Remote IP Range. Or, in case of the Frontend Receive connector, it will be open to all IPs (0.0.0.0-255.255.255.255). Perhaps it goes without saying, but if your MX record points to Office 365, you definitely don’t want to allow anonymous submissions via the on-premises receive connector. But it’s not as simple as disabling anonymous permission on the receive connector. For Exchange 2010 server, disabling anonymous permission on “Inbound from Office 365” receive connector would cause “5.7.1 Client was not authenticated” NDR for emails coming from even your own Tenant. Whereas, for Exchange 2013 onwards, it works inversely, disabling anonymous permission does not block email from your tenant and for that matter, emails from other tenants are also allowed. So, disabling anonymous permission is not enough to lock down the on-premises Exchange server to only accept emails from your own Office 365 tenant. The concern with this configuration is: any Office 365 tenant who knows external hostname/IP address of your server can send emails to your on-premises servers directly. I want to clarify here that although our on-premises receive connector allows all Exchange Online IP Addresses to submit emails, mails sent from other tenants will not be an authenticated submission and they wouldn’t be able to relay through your on-premises server or be treated as internal to your organization. The emails from other tenants will have the X-MS-Exchange-Organization-AuthAs header set to “Anonymous”. Still, customers might want to go further than this to restrict other tenants to send emails directly to their on-premises environment to avoid various compliance issues. One obvious example is that you may have DLP rules configured inside of your Office 365 tenant, so sending email directly to your on-premises server would bypass that rule. First, let’s try to understand the difference between the situations when mail is sent from your own tenant and mail is sent from other tenants. When email is sent from or relayed through your own tenant, Exchange Online will send XOORG SMTP command extension with the “MAIL FROM” Command which will be extracted from the sender’s P2 or P1 if it’s an accepted domain. In cases where the sender is external (like forward scenario) the XOORG use the default accepted domain. The following two conditions are checked on the on-premises Server:

  1. If the Receive connector TlsDomainCapabilities is set to AcceptedCloudServicesMail, and
  2. If the XOORG Domain mentioned with MAIL FROM Command matches on-premises Accepted Domain or matches any remote domains with TrustedMailInboundEnabled set to true.

If the above conditions are true, on-premises server will treat the connection as Authenticated and will promote cross premises headers to org headers. The protocol log collected from on-premises server for an email received from Hotmail and relayed through Contoso tenant will look something like below-

2018-11-09T16:30:50.288Z,E161\Default Frontend E161,08D61A879C5AB8C3,13,192.168.2.52:25,4.4.0.1:29143,<,MAIL FROM:<someuser@hotmail.com> SIZE=22396 AUTH=<> XOORG=contoso.com,
2018-11-09T16:30:50.289Z,E161\Default Frontend E161,08D61A879C5AB8C3,14,192.168.2.52:25,4.4.0.1:29143,*,SMTPAcceptAnyRecipient SMTPAcceptAuthoritativeDomainSender BypassAntiSpam BypassMessageSizeLimit,Granted Mail Item Permissions
2018-11-09T16:30:50.289Z,E161\Default Frontend E161,08D61A879C5AB8C3,15,192.168.2.52:25,4.4.0.1:29143,*,08D61A879C5AB8C3;2018-11-09T16:30:48.725Z;1,receiving message
2018-11-09T16:30:50.290Z,E161\Default Frontend E161,08D61A879C5AB8C3,16,192.168.2.52:25,4.4.0.1:29143,<,RCPT TO:John@contoso.com,
2018-11-09T16:30:50.290Z,E161\Default Frontend E161,08D61A879C5AB8C3,17,192.168.2.52:25,4.4.0.1:29143,>,250 2.1.0 Sender OK,
2018-11-09T16:30:50.290Z,E161\Default Frontend E161,08D61A879C5AB8C3,18,192.168.2.52:25,4.4.0.1:29143,>,250 2.1.5 Recipient OK,
2018-11-09T16:30:50.538Z,E161\Default Frontend E161,08D61A879C5AB8C3,19,192.168.2.52:25,4.4.0.1:29143,<,BDAT 11393 LAST,
2018-11-09T16:30:50.789Z,E161\Default Frontend E161,08D61A879C5AB8C3,20,192.168.2.52:25,4.4.0.1:29143,*,,Set mail item OORG to 'contoso.com' based on 'MAIL FROM:'

Also, this will make sure that all emails directly sent from or relayed through EOP have the “X-OriginatorOrg” header set to your Verified Domain in EXO. So, the email will have the following header:

X-OriginatorOrg: contoso.com

All of this is setup for you by the Hybrid Configuration Wizard, and as long as Office 365 is connecting directly to your on-premises Exchange server(s), XOORG SMTP command is how we keep things secure – you only trust your Office 365 tenant, not others. In fact, because the XOORG command is only understood by Exchange, we say it is more secure to connect Office 365 directly to Exchange or Exchange Edge. Other application layer filtering devices, etc. do not understand XOORG, cannot pass it, and you actually end up in a less secure state. Emails directly sent from other tenants to on-premises servers will also use the XOORG SMTP Extension and will have the X-OriginatorOrg header, but it will not match with your Accepted domain or Remote domain with TrustedMailInboundEnabled. They are still allowed by default into your on-premises Exchange environment because we must allow other possible routing configurations. Can someone spoof XOORG? The answer is “no”, the XOORG headers cannot be spoofed because it is the combination of the EOP TLS certificate, connector setting and accepted domain – and we control the headers when they pass through us, which is the case when our certificate is used.

Note: X-MS-Exchange-Organization-AuthAs header stamped on email received by on-premises server from O365 can be either “Internal” or “Anonymous”. For instance, emails sent from your EXO tenant to on-premises servers, will have the X-MS-Exchange-Organization-AuthAs set to “Internal”. If it’s an external email which is relayed through your tenant, the original “Anonymous” identity would be preserved and the X-MS-Exchange-Organization-AuthAs will be set to “Anonymous”. Thus, X-MS-Exchange-Organization-AuthAs header would not differentiate between email coming directly to your on-premises and email relayed through your tenant.

How to make sure other Office 365 tenants can’t bypass intended routing

Now we know how to differentiate between emails from your own tenant and from others. XOORG validation and X-OriginatorOrg header is the key. You can create a transport rule on your on-premises organization to forward these messages for approval (if X-OriginatorOrg header is not stamped correctly, because these emails are not received through your Office 365 tenant). Alternately, you can generate incident report or redirect these emails to someone else for investigation. This way, you will know if there are valid emails which are coming directly to your on-premises server because of some configuration issues. For example, it might be an internal application sending emails directly on your in-house servers.

AdvRouting2.jpg

Once you identify these issues and decide if you’re ready to take more drastic measures, you can tweak the rule to reject instead of redirect or forward:

AdvRouting03.jpg

The “RejectMessageReasonText” parameter (equivalent to the action “Reject the message with the explanation…”) does not work in Edge server. For Edge Server, you can use other similar parameters like “SmtpRejectMessageRejectText” or “RedirectMessageTo” or “DeleteMessage:$true”.

Now anyone who tries to send emails directly to your on-premises server bypassing your MX record (which points to EOP) will receive the following non-delivery report:

hybmailflow4 The rule will function similarly in all scenarios, whether centralized mail transport is enabled or not. There is one more slightly different routing scenario which we want to cover in this article. Imagine MX for contoso.com is pointed to a 3rd party email filter which forwards the email to their on-premises Exchange server. And then based on recipient’s mailbox location, it can either be delivered locally or forwarded to Office 365. So although the routing is different, we have a very similar issue as mentioned earlier, that any Office 365 tenant who knows external hostname/IP address of your server can send emails to your on-premises server directly. hybmailflow5 Stopping those emails using the Transport rule described above won’t work because inbound emails from internet through the 3rd party device won’t have the X-OriginatorOrg header and all those valid emails will be blocked too. Now, looking at the above diagram, and from our earlier discussion, we can make following assumptions for an inbound email to the on-premises server:

  1. Inbound email from internet will have IP Address of the 3rd party email filter in the receive header if it’s correctly routed through the MX.
  2. In hybrid mail flow, email from your own tenant contoso.com is considered as sent from “Inside the organization”.
  3. Email from other tenants like fabrikam will be treated as anonymous email from “Outside the organization”.
  4. Email from your tenant (Including calendar delegation forward meetings, OOF etc) will always have the “X-OriginatorOrg” header set to your Verified Domain in EXO (or the onmicrosoft domain depending on sender’s Primary address).

So, based on the above assumptions, we can create the following rule to block email which is sent directly to on-premises server bypassing the 3rd party filter. In this example, 192.168.2.51 is the IP address of your 3rd party email filter.

Newrule.jpg We hope this post will be helpful in planning your hybrid mailflow. I also want to take a moment and thank Scott Landry, Daniel Talbot, Lou Mandich, Denis Vilaca Signorelli and Ramon Infante for their contributions.

Arindam Thokder

25 Comments
Not applicable
For the last scenario, you will need both possible exceptions, correct? The IP address(es) of the mail gateway and the X-OriginatingOrg with your default tenant domain.
Not applicable
Hello Dustin, for the last scenario, we don't need X-OriginatingOrg exception because mail from your own tenant will be considered as from “Inside the organization”. So mail from your tenant will be exempted anyway.
Not applicable
We are in the last scenario, MX records point to on premise 3rd party filtering, then routing through on prem to our ExO tenant (we have centralized mailflow). I can tell you from experience (and a case with support) that just adding the IPs is not enough. You'll need to Exempt 'calendaring' message types (or external messages sent to delegates will be blocked as 'external' when delegation sends it to the delegate on behalf of the 'boss'), and exempt messages with headers 'x-ms-exchange-organization-AuthAs' of 'internal' or internal Out of Office messages will be blocked.
Not applicable
Hello MRI503X, I tested the scenario you explained here, however I am unable to repro this in my lab. I tested few scenarios-

Scenario1-

Meeting is sent from External Domain to a user in tenant1 (say user1). User1 forwarded the Meeting to tenant2 whose MX is pointed to 3rd Party. I see the email is sent to 3rd party itself and not directly to tenant2. So the IP Address of 3rd party will be there in the header and the email won’t be blocked by the rule (because of IP exception)

Scenario2-

Meeting is Sent from External Domain to tenant1 (say user1). User1 on behalf of his manager forward the e-mail to an On-Prem user. Here the Auth-AS header is set to Internal. Again the email won’t be blocked by the rule (because the rule is only for external email, internal mails are bypassed)

Did I miss the scenario? Could you please explain the exact problem scenario so that I can do more testing in my lab?

Not applicable
Yes this is a pretty botched up scenario and organizations have started taking notice of this design flow and microsofts response of getting this fixed using transport rules has been pretty flawed. They have the source and destination code control and it would be good if they put some engineering on this.

This fix does not work when:

1. Senders with calendar delegation forward meetings.

2. Senders that are on O365 hybrid but are striping their headers for security concerns.

Not applicable
Hi Arindam,

Some info on our environment and then I will confirm the scenario:

-Exchange 2016 Hybrid mode. All user mailboxes in cloud.

-We have "Centralized Mailflow" enabled. My understanding now of what this really does, is a process in the tenant look at a message during transport, and if it hasn't come from on prem, it's sent on prem (even user to user - cloud hosted mb to cloud hosted mb)

-Our MX records point to an on premise SMTP relay.

-These relays pass email to our on premise Exchange servers, which then transfer it to the tenant.

Scenario:

-All users are in the same cloud tenant. Boss1 had delegate User1. Boss1 has set up his delegation such that notices are forwarded/copied to the Delegate (user1).

-Boss1 gets a meeting invitation from user2 (a tenant mailbox user) and delegation forwards on to user1. User1 receives it.

-Boss1 gets a meeting invitation from an external sender, and his delegation configuration forwards it to user1. User1 does not receive the message.

-For User1 to get these messages, we had to add an exception to the transport rule of "Is message type 'Calendaring'"

Not applicable
Hi Arindam,

Great Article. I am little stuck though.

We are using Symantec Message Labs as the email filtering service.

Emails route from on-prem to Office 365 (For now)

I am not able to figure out what mailflow rule to create on the On-Prem Server to Allow only emails from Symantec IP's https://support.symantec.com/en_US/article.INFO4532.html

I cannot just add the subnets I guess I will have to add each and every IP in the Rule example above?

Not applicable
HI Naveen, Adding each IP will work.....otherwise you can also look at some unique header which is added by Symantec (see email header which is routed to on-premises through Symantec) and created a transport rule based on that condition.
Copper Contributor

This is not an acceptable solution. They also fail to tell you about a bundle of other things that will be blocked by using the transport rule.

1) Delegates will not receive calendar appointments sent to them because of this rule (Exchange strips the Received: headers out and still considers the message external)
2) If you have a Centralized Mail Flow turned on so that all your Office 365 emails exit via your on-premesis servers, it will reject those messages for some reason believing they are NOT internal (Though it will still let you email from a 365 user to an Online user).

3) If you have Unified Message setup and you receive a call from someone that doesn't have an extension on your system (Like EVERY external user), Exchange doesn't enter an email address in the from and then will not consider the message Internal and it will be blocked.

Microsoft

@idspispopd - Thanks for your feedback, we were able to reproduce the issue and now we modified the rule for the second scenario. The modified rule should be able to fix the issue.

Copper Contributor

Hi,

Thanks for the interesting article.

When using an Exchange Edge Server for hybrid mailflow the following PS creates the necessary transportrule.

 

New-TransportRule -name "Controlling Hybrid mailflow" -FromScope NotInOrganization -SmtpRejectMessageRejectText "You are not allowed to send email directly, please use mx" -ExceptIfHeaderContainsMessageHeader X-OriginatorOrg -ExceptIfHeaderContainsWords contoso.com

Regards

Copper Contributor

@Arindam Thokder The above rule would still have issue with UM. When a UM message is left from someone outside of Exchange, Exchange will typically put "CALLER ID NAME <>" as the sender. Exchange would consider the message external (I believe because of the email address) and would redirect it because it doesn't have the aforementioned IPs in the received header 

@idspispopd Could you please share a UM header sample with me? Denis.signorelli@microsoft.com

@idspispopd I already shared this with you offline, but let me also reply to this comment as it could help others in the same situation. For this UM messages where there is no Return-path, you can try a different logic for lockdown’s rule:

 

  • Condition If “X-OriginatorOrg” matches: “$”

 

  • Action Reject (test it for a couple of months using “generated incident report” before reject)

 

  • Except If “X-OriginatorOrg” matches: “contoso.com or contoso.onmicrosoft.com or (all EXO accepted domains)”

 

Basically, the rule doesn’t rely on the Internal/External condition, but it will looking for the X-OriginatorOrg presence. If we find any header containing X-OriginatorOrg, we are sure that someone sent it bypassing the 3rd-party antispam. The reason is that X-OrinatorOrg is only accepted by Exchange if the message was sent through mail.protection.outlook.com STARTTLS. Your antispam will accept this header, but when the antispam send the message to the Exchange, this header should be stripped as your antispam doesn’t has  mail.protection.outlook.com certificate.

When I say “should” is because there is some caveat to be aware. The receive connector that accepts messages from the 3rd-party antispam cannot have Externally Secured permission, otherwise it will accept X-OriginatorOrg from your 3rd-party antispam.

Copper Contributor

Good article but has some short commings.

 

In my testing, I found that an internal relay email is also blocked as a result of this mailflow rule. That email does not have the header  “X-OriginatorOrg”

So emails from printers etc are also blocked. is there any other way to achieve this efficiently ?

@Rana_Banerjee see my last comment, that solution that I provided doesn't rely on "Internal/External" ETR condition.

Copper Contributor

@Denis_Signorelli Thanks for your prompt response and for this workaround :),
Please see the following PowerShell command which I used to configure the transport rule on On prmeise Exchange Server (2016).

So far I have confirmed following is working.

  • Email Only from 'YourDomain' is accepted. other emails are rejected from non authorized O365 Tenant.
  • SMTP Relay emails working as expected sent via a Custom Receive connector (before it was not working).
  • Calender invites and delegates not tested yet.

Command below - Please replace 'YourDomain' with your actual domain. Also add all accepted domains if needed (not sure if this is needed).

I am using PowerShell Splatting for better readablity

 

$transportRuleName = 'Accept Only [YourDomain] O365 Emails on Hybrid Connector'
$RejectMessage = 'Direct email relay is not allowed. Please use MX to relay your emails.'
$header = 'X-OriginatorOrg'
$HeaderWords=@(
    'YourDomain.com'
    'YourDomain.mail.onmicrosoft.com'
    'YourDomain.onmicrosoft.com'
)

$paramNewTransportRule = @{
	Name							    = $transportRuleName
	HeaderMatchesMessageHeader		    = $header
	HeaderMatchesPatterns			    = '$'
	RejectMessageReasonText			    = $RejectMessage
	ExceptIfHeaderContainsMessageHeader = $header
	ExceptIfHeaderContainsWords		    = $HeaderWords
	Enabled							    = $true
	StopRuleProcessing				    = $true
	Mode							    = 'Enforce'
	SetAuditSeverity				    = 'High'
}

New-TransportRule @paramNewTransportRule

 

@Denis_Signorelli Can you pelase advise if there are any other caveats or considerations to use this solution ? 

@Rana_Banerjee this solution can works fine if your Exchange is behind a third-party antispam solution, I explained the reason here: "Basically, the rule doesn’t rely on the Internal/External condition, but it will looking for the X-OriginatorOrg presence. If we find any header containing X-OriginatorOrg, we are sure that someone sent it bypassing the 3rd-party antispam. The reason is that X-OriginatorOrg is only accepted by Exchange if the message was sent through mail.protection.outlook.com STARTTLS. Your antispam will accept this header, but when the antispam send the message to the Exchange, this header should be stripped as your antispam doesn’t has mail.protection.outlook.com certificate."

 

No caveat as far as I know, just be sure that you are not using Externally Secured in your Exchange receive connector and you don't have too many domains to add in the rule exception, otherwise you probably will reach the size limit of the transport rule.

Copper Contributor

@The_Exchange_Team @Denis_Signorelli How would I also allow Journal generated messages from O365 that are sent to EOP Journal mailbox. At the moment it does not include the X-OriginatorOrg field?, therefore gets rejected by my Anti spoof.

@Janx_ could you better elaborate the scenario? (e.g.: EXO -> 3rd party antispam -> Edge -> Journal mailbox ?)

Copper Contributor

Hi @Denis_Signorelli , On-Prem mail user sends mail to 0365 User. O365 Journal rule sents a journal msg back to Exchange on-prem journal mailbox. Anti spoof blocks the Journal msg from 0365

Sorry @Janx_ but I cannot propose a solution as I don't know what exacly is this "anti spoof" that is blocking Jornal reports and why this is happening. What I can say is that Journal Reports should have the "X-OriginatorOrg" header (I just tested it in my demo tenant). I suggest you to open a case with our support so we can take a look on this.

Copper Contributor

Hi @Denis_Signorelli the anti Spoof I was referring to was the EOP protection rule that prevents external users from sending from my domain. Regardless the fact that the Journal messages uses the  "X-OriginatorOrg" header is all the info I needed to confirm. thanks for the help

Copper Contributor

The screenshot for the transport rule in the ECP has X-OriginatingOrg, it should be X-OriginatorOrg.

Copper Contributor

Is there a way of getting this to work with journaling enabled? I have a journal rule which sends from O365 to onpremise for a phishing platform from Cofense. I noticed that in the journal messages there is no X-Originator-Org being added.

Co-Authors
Version history
Last update:
‎Aug 17 2022 02:20 PM
Updated by: