Tag Archives: Exchange

Retrieving attachments from Exchange mailbox using python

Story:

I got a request from a client who constantly gets CVs and have to download them for the hiring managers to review them and wanted to get some way an automated mechanism of downloading all those emails.

Googling lead me to the exchangelib project which is a great python source for such a purpose. I built my local lab of the following servers to test it

  1. AD 2016 moh10ly.local
  2. Exchange 2016 = exch01.moh10ly.local
  3. AAD = Another 2016 server to test from

I built my local Certification authority and made sure that all servers has the CA installed to avoid any issues on python.

If you are going to use this on your production environment you can basically install Python anywhere even on your own computer and it should work if EWS is exposed and Autodiscover is configured propely and have a valid and trusted 3rd party Certificate.

However, If you would like to schedule this to work on a daily basis and let it download attachments from mailbox then you’ll need a server or at least a computer to rely on that it would be on when the scheduled task works.

Prerequisites :

Windows Server 2016:

  • Download and install latest version of Python 3.10
  • From CMD run the following cmd
    • Pip install exchangelib
    • Pip install exchangelib[kerberos]
    • Pip install exchangelib[sspi]
  • Download and install MIT Kerberos MSI from https://web.mit.edu/KERBEROS/dist 64bit version
  • If you’re doing this on a local Lab without a trusted 3rd certificate you’ll need to make sure to export your certificatation Authority Certificate in CER format, copy the cert and add it to the end of Python root PEM.

Testing Scenario

  • I created two mailboxes on my local Exchange server lab
  • I have sent myself an email to info@moh10ly.com with 3 attachments in it as you can see.
  • Setup a server to use to download all attachments from the mailbox.

Prepare your Python Script

  • Import Packages in order to use them.

from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, EWSDateTime, EWSTimeZone, Configuration, NTLM, GSSAPI, CalendarItem, Message, Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, HTMLBody, Build, Version, FolderCollection
  • Prepare Credentials of the user you would like to retrieve the attachments from.
credentials = Credentials(username='moh10ly\info', password='Bc12345$')
  • Enter your Exchange server configuration. Since autodiscover didn’t work for me as I don’t have a public certifiate so I went ahead and placed the server configuration.
ews_url = 'https://mail.moh10ly.com/EWS/exchange.asmx'
ews_auth_type = 'NTLM'
primary_smtp_address = 'info@moh10ly.com'
config = Configuration(service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type)
  • Place the account type and configuration
account = Account(
primary_smtp_address=primary_smtp_address,
config=config, autodiscover=False,
access_type=DELEGATE)
  • Configure the local path of where you want to save attachments to on the server where this code is going to be launched from. in my code example I have created a folder called “Temp” on the C root drive and that’s what I will use.
  • You can pickup a different local path by changing the /temp path in the line “local_path = os.path.join(‘/temp‘, attachment.name)”
import os.path
from exchangelib import Account, FileAttachment, ItemAttachment, Message

some_folder = account.inbox 
for item in some_folder.all():
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            local_path = os.path.join('/temp', attachment.name)
            with open(local_path, 'wb') as f:
                f.write(attachment.content)

This by now should be working fine and you should see that it is saving all your mailbox attachments to the folder that you have configured in the path section of the code.

Complete code to run

Working config


from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, EWSDateTime, EWSTimeZone, Configuration, NTLM, GSSAPI, CalendarItem, Message, Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, HTMLBody, Build, Version, FolderCollection


credentials = Credentials(username='moh10ly\info', password='Bc12345$')

ews_url = 'https://mail.moh10ly.com/EWS/exchange.asmx'
ews_auth_type = 'NTLM'
primary_smtp_address = 'info@moh10ly.com'
config = Configuration(service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type)


account = Account(
primary_smtp_address=primary_smtp_address,
config=config, autodiscover=False,
access_type=DELEGATE)

import os.path
from exchangelib import Account, FileAttachment, ItemAttachment, Message

some_folder = account.inbox 
for item in some_folder.all():
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            local_path = os.path.join('/temp', attachment.name)
            with open(local_path, 'wb') as f:
                f.write(attachment.content)


-----------------

#To download all attachments in the inbox:

for item in account.inbox.all():
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            local_path = os.path.join('/sky', attachment.name)
            with open(local_path, 'wb') as f, attachment.fp as fp:
                buffer = fp.read(1024)
                while buffer:
                    f.write(buffer)
                    buffer = fp.read(1024)
            print('Saved attachment to', local_path)

Hope this have helped you

References:

https://towardsdatascience.com/download-email-attachment-from-microsoft-exchange-web-services-automatically-9e20770f90ea

Check under attachments:

https://ecederstrand.github.io/exchangelib/

https://pypi.org/project/exchangelib/

Troubleshoot cert issue

https://stackoverflow.com/questions/51925384/unable-to-get-local-issuer-certificate-when-using-requests-in-python

With graph

https://techcommunity.microsoft.com/t5/identity-authentication/what-oauth-permissions-needed-for-exchangelib/m-p/2858179

Securing and Testing your Exchange Server with Pfsense HAProxy

– Using the CVE-2021-26855 Payload

After the recent vulnerabilities that hit Exchange Servers On-premises I found sometime to install KaliLinux and try to check what kind of information would I get from the patched servers.

I downloaded the payloads and tried to run it against couple of clients that I have patched the servers for luckily no authentication was made.

image

– Using Nikto scanner

By using Nikto command from Kali Linux I could see what  Information could Exchange expose using

The command line is nikto –h mail.domain.com and the result of the scan would be exposing the Server’s name, local IP address, OWA Version,  ASP Net platform and version.

image

Since I have my Exchange Server published via HAProxy 1.8 on Pfsense then I had to tweak HAProxy to strengthen the ciphers, make sure that HSTS is in place and deny the headers that expose the server’s sensitive information.

The result is pretty good as it also has affected the server’s score on ssllabs.com

Prior to the tweaking  my owa scan result on SSL Labs would get an A

image

– Pfsense’s HAProxy Settings before

Before upgrading Pfsense to the latest version HAProxy was on 1.6 and the ssl/tls settings were also different as they were setup through the Advanced SSL options on the frontend however, now this is no longer supported and you’ll have to remove that and set it up on the “Global Advanced pass thru” in the General setting page.

ssl-default-bind-options ssl-min-ver TLSv1.2

tune.ssl.default-dh-param 2048

ssl-default-bind-ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK

image

Right after you save this, you will still need to change another settings on the Frontend to protect your server’s information from being exposed.

In the HAProxy settings Go to Frontend > Scroll down all the way to “Advanced pass thru” and paste the following:

image

# Remove headers that expose security-sensitive information.

rspadd X-Frame-Options:\ SAMEORIGIN
rspidel X-FeServer:.*$
rspidel ^Server:.*$
rspidel ^X-Powered-By:.*$
rspidel ^X-AspNet-Version:.*$
rspidel X-WsSecurity-Enabled:.*$
rspidel X-WsSecurity-For:.*$
rspidel X-OAuth-Enabled:.*$
rspadd X-Xss-Protection:\ 1;\ mode=block
rspadd Strict-Transport-Security:\ max-age=31536000;includeSubDomains;preload
rspadd Referrer-Policy:\ no-referrer-when-downgrade
rspidel Request-Id:.*$
rspidel X-RequestId:.*$
rspadd X-Content-Type-Options:\ nosniff


In the below result, I have got almost everything protected well except for the OWA version which can be a bit problematic. In the next article I am going to try and mitigate this so the server can be protected in the expected manner.

image

image

– The Result

Now the server is showing a totally different result and the Nikto scan is not revealing anything anymore.

SSLabs

image

https://securityheaders.com/

The reason why I got B on security headers is due to the fact that Content-Security-Policy header will malfunction the ECP and OWA Login pages. Permission Policy is new feature and I couldn’t find anything about it on HAProxy.

image

I hope this helps

Refences:

https://securityheaders.com/

https://www.ssllabs.com/

https://www.haproxy.com/documentation/aloha/12-0/traffic-management/lb-layer7/http-rewrite/

https://www.net7.be/blog/article/xss_csrf_http_security.html

Exchange Server backdoor investigation tools

The Story

After the disastrous exploit that was found in Microsoft Exchange Servers lots of corporations started immediately patching their servers with the latest Cumulative update and Security patches. The question is would those patches be enough if the server is already hacked or have a backdoor installed already?

image

What are those 0-day exploits ?

The vulnerabilities recently being exploited were CVE-2021-26855, CVE-2021-26857, CVE-2021-26858, and CVE-2021-27065 which are part of alleged “State-sponsored Chinese group” according to Microsoft.

Let’s get into details of those exploits one by one:

CVE-2021-26855 is a server-side request forgery (SSRF) vulnerability in Exchange which allowed the attacker to send arbitrary HTTP requests and authenticate as the Exchange server.

CVE-2021-26857 is an insecure deserialization vulnerability in the Unified Messaging service. Insecure deserialization is where untrusted user-controllable data is deserialized by a program. Exploiting this vulnerability gave HAFNIUM the ability to run code as SYSTEM on the Exchange server. This requires administrator permission or another vulnerability to exploit.

CVE-2021-26858 is a post-authentication arbitrary file write vulnerability in Exchange. If HAFNIUM could authenticate with the Exchange server then they could use this vulnerability to write a file to any path on the server. They could authenticate by exploiting the CVE-2021-26855 SSRF vulnerability or by compromising a legitimate admin’s credentials.

CVE-2021-27065 is a post-authentication arbitrary file write vulnerability in Exchange. If HAFNIUM could authenticate with the Exchange server then they could use this vulnerability to write a file to any path on the server. They could authenticate by exploiting the CVE-2021-26855 SSRF vulnerability or by compromising a legitimate admin’s credentials.

How to proceed ?

Microsoft released couple of tools that could diagnose your servers and check if you already have been infected with a backdoor or any of these nasty malware and also remove those infected files or clean them and ask you for a restart if it’s required.

Tools:

  1. MSERT (Microsoft Safety Scanner) detects web shells, Download here .
  2. Health Checker (Scans your server for any vulnerabilities and whether you have updated Server CU and installed patches). Download here
  3. Exchange WebShell Detection (A simple PowerShell that is fast and checks if your IIS or Exchange directory has been exploited). Download here
  4. Scan your exchange server for proxy logon:
    https://github.com/microsoft/CSS-Exchange/tree/main/Security
  5. Microsoft very recently created a mitigation tool for Exchange on-premises that would rewrite url for the infected servers and recover the files that were changed. You can download the tools from this github link.

    https://github.com/microsoft/CSS-Exchange/tree/main/Security

    Copy the Test-ProxyLogon code into Notepad
    Save As “Test-ProxyLogon.ps1” with the quotes in your C:\Temp folder
    Run in Exchange Management Shell: .\Test-ProxyLogon.ps1 -OutPath C:\Temp

Scan Result

Scan result should show you the following if your servers has been exploited already.

This will remove the infections and asks for a restart.

clip_image001

References:

https://www.microsoft.com/security/blog/2021/03/02/hafnium-targeting-exchange-servers/

https://www.bleepingcomputer.com/news/security/microsoft-exchange-updates-can-install-without-fixing-vulnerabilities/

https://github.com/dpaulson45/HealthChecker?mkt_tok=eyJpIjoiTURRMk5HRTFaV1V6TkRrMCIsInQiOiJcL3ZOTkRUVzdXdkJmTm5ibUIzTExKTDVxXC9ObFAxTmZLanFRZ0xpcDkxMW5raVE0dlRwV2FhVFFmWlVUVFZaZUdFM1NlcEFNTEZ6dTh5aWlqcVBpV3J2R2IxbGJxMmNUZ1ppYjJyZklnMjZFZngrM2tBUnNsM1JKcHJsSU1ib3BTIn0%3D#download