29,99 €
Take your cybersecurity skills to the next level with this comprehensive guide to PowerShell security! Whether you’re a red or blue teamer, you’ll gain a deep understanding of PowerShell’s security capabilities and how to use them.
After revisiting PowerShell basics and scripting fundamentals, you’ll dive into PowerShell Remoting and remote management technologies. You’ll learn how to configure and analyze Windows event logs and understand the most important event logs and IDs to monitor your environment. You’ll dig deeper into PowerShell’s capabilities to interact with the underlying system, Active Directory and Azure AD. Additionally, you’ll explore Windows internals including APIs and WMI, and how to run PowerShell without powershell.exe. You’ll uncover authentication protocols, enumeration, credential theft, and exploitation, to help mitigate risks in your environment, along with a red and blue team cookbook for day-to-day security tasks. Finally, you’ll delve into mitigations, including Just Enough Administration, AMSI, application control, and code signing, with a focus on configuration, risks, exploitation, bypasses, and best practices.
By the end of this book, you’ll have a deep understanding of how to employ PowerShell from both a red and blue team perspective.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 705
Veröffentlichungsjahr: 2023
Hacking and defense for red and blue teamers
Miriam C. Wiesner
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: Prachi Sawant
Senior Editor: Romy Dias
Technical Editor: Irfa Ansari
Copy Editor: Safis Editing
Project Coordinator: Ashwin Kharwa
Proofreader: Safis Editing
Indexer: Hemangini Bari
Production Designer: Ponraj Dhandapani
Marketing Coordinator: Marylou Dmello
First published: July 2023
Production reference: 1030823
Published by Packt Publishing Ltd
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB
ISBN 978-1-80056-637-8
www.packtpub.com
To my loving husband, Felix, and my son, who both supported me tremendously during the writing of this book with their support, patience, and love.
To my former mentor, Chris Jackson, and his family; he was so excited when I started writing this book, but unfortunately, he tragically passed away before it was published.
To my family and friends, who were patient with me and supportive—I cannot mention all of you by name, but you know who you are.
Miriam and I first met when I worked at Microsoft, where we connected over discussions of security automation, how to get accepted to speak at conferences, and her love of PowerShell. We kept in touch over the years, as it’s not often you meet someone who is “the same kind of nerd” that you are. When she told me she was writing a book about using PowerShell for hacking and defending, I was not surprised at all!
Before Miriam even started thinking about writing this book, she had already created and open sourced her PowerShell tool EventList to help people gather logging evidence when investigating security incidents. She has also presented at numerous conferences on the topics of digital forensics, incident response, logging, infrastructure security, Just Enough Administration, and so much more. She has constantly and consistently shared her research with the community, in an effort to help everyone lock down their secure systems.
This book is an extension of her efforts to share knowledge while hacking all the things. Every security-related feature of PowerShell, and how to use it to your distinct advantage, is in this book. Whether you’re calling Windows APIs or other subsystem functions, using it to manipulate Azure, or bypassing security controls, there’s something in this book for you. With Windows being the most popular operating system on the planet, this powerful scripting language can take you further than most others for penetration tests, red teaming, and security research.
This book can also serve as a playbook on where to start, where to go next, and so on when using PowerShell for an offensive security engagement, but also how to use it to ensure you defend and harden your systems from these attacks. You can even create scripts to alert you when people are attempting, but failing, to get into your systems!
Although previous scripting knowledge is necessary to follow this book, you will start off with the PowerShell fundamentals, such as hardening and detection, then move on to more advanced topics such as hacking Azure Active Directory, API and Windows system calls, language modes, and JEA.
If you want to be a penetration tester that works with Windows and/or Azure, or you’re interested in security automation, this book is for you. I hope you love it as much as I did!
Tanya Janca
Author of Alice and Bob Learn Application Security
CEO and Founder of We Hack Purple
"PowerShell Automation and Scripting for Cybersecurity is a rare treat of a book and one that I am honored to have been a technical reviewer for. In the security industry, accurate information about PowerShell Security is hard to find. Often, what you do find is shallow, incorrect, or just entirely theoretical.
Until now.
Miriam has been an influential member of the PowerShell Security community for many years. This book takes her mountains of real-world PowerShell Security experience and then distills it down to what matters. If it’s here, Miriam has either used it to help companies defend their networks or has had to defend against it in their networks.
We are fortunate to have this gem of a book that is certain to jumpstart your journey into PowerShell Security."
—Lee Holmes Partner Security Architect, Azure Security Original PowerShell developer and author of the PowerShell Cookbook
Recommended for anyone who wants to learn automation and scripting in a security context. Miriam is an expert in her field and imparts invaluable knowledge.
— Sarah Young Senior Security Program Manager and author
Set to become the definitive standard in PowerShell security, this book offers practical, real-world examples empowering both red and blue teams at any expertise level. Unleash the full power of PowerShell to master Windows, Active Directory, and Azure with confidence.
— Andy Robbins Co-Creator of BloodHound
Miriam C. Wiesner is a senior security researcher at Microsoft, with over 15 years of experience in IT and IT security. She has held various positions, including administrator/system engineer, software developer, premier field engineer, program manager, security consultant, and pentester.
She is also a renowned creator of open source tools based in PowerShell, including EventList and JEAnalyzer. She has been invited multiple times to present the research behind her tools at many international conferences, such as Black Hat (the US, Europe, and Asia), PSConfEU, and MITRE ATT&CK workshop. Outside of work, Miriam is a dedicated wife and mother, residing with her family near Nuremberg, Germany.
Thanks to my publisher, my amazing technical reviewers, and all the great people that were involved in creating and publishing this book. All of your input and help was really invaluable during the writing of this book.
Michael Melone is a cybersecurity professional with over 20 years of IT experience, including over 7 years of performing targeted attack incident response as part of Microsoft Incident Response (formerly DART). In his current role, he works as a Principal Security Researcher for Microsoft Defender Experts for XDR helping investigate and respond to threats experienced by its customers. Michael is a member of the Keiser University curriculum board and holds multiple industry certifications, a Master of Science in information assurance and security from Capella University, and an Executive Master of Business Administration from the University of South Florida. He is the author of the books Designing Secure Systems and Think Like a Hacker.
Carlos Perez has been active in the information security and information systems scene since the late 90s, covering all parts of the spectrum of positions and projects. He worked for Compaq, Microsoft, HP, and Tenable Network Security, working on attack emulation, data center design, incident response, and automation. His contribution to security in automation with PowerShell has earned him the Microsoft Most Valuable Professional (MVP) award for over ten years. He is currently working as a research lead developing both offensive and defensive tooling, in addition to being active in the community as a whole.
Lee Holmes is a security architect in Azure security, an original developer on the PowerShell team, a fanatical hobbyist, and the author of The PowerShell Cookbook.
You can find him on Mastodon (@[email protected]), as well as his personal site (leeholmes.com).
Pawel Partyka is a cybersecurity professional with over 10 years of experience in the field. He has worked extensively with Microsoft products, including Microsoft 365 and Azure, and has a strong background in threat protection.
In his current role as a principal security researcher in Microsoft 365 Defender, Pawel is responsible for analyzing emerging threats, creating detections and correlations to address new attack vectors, and simplifying the investigation of security incidents.
Prior to this, Pawel worked in various roles at Microsoft, including program manager, Azure consultant, and premier field engineer.
Pawel is a volunteer at the CyberPeace Institute. Outside of work, Pawel enjoys mountain biking, hiking, and skiing.
Francesco Castano is a seasoned cybersecurity consultant with over 17 years of experience in the IT industry. Working as a Principal consultant within the Microsoft Incident Response team has given Francesco experience and deep knowledge of the Microsoft Azure suite, mainly focused on identity management in Azure AD, as well as a strong knowledge of on-premises Active Directory and all aspects related to authentication protocols (Kerberos, NTLM, OpenID, OAuth 2.0, WS-FED, and SAML). Francesco has great experience in managing integration between on-premises data centers and the IaaS, SaaS, and PaaS solutions offered by Azure.
I want to thank all the people who have always trusted me, allowing me to achieve important results in my career. Thanks to my managers, my colleagues, and Miriam (the author) for giving me the chance to collaborate on this amazing project.
Christian Handschuher has worked in IT for more than 20 years, with 14 years mainly focusing on client management.
In addition to his current role as a senior cloud solution architect and technical trainer at Microsoft, he can look back on many years as a consultant and premier field engineer. The topic of security is always right at the top for his customers, who are among the top 500 in industry and business, as it is for customers from the public sector.
As the owner and an active member of various communities, such as the System Center User Group Germany, it is important to him to actively share knowledge and contribute to the community.
Jonathan Bar Or JBO is a principal security researcher at Microsoft, working as the Microsoft Defender research architect for cross-platform. Jonathan has many years of rich experience in vulnerability research, exploitation, cryptanalysis, and offensive security in general.
PowerShell is everywhere – it is preinstalled on every modern Windows operating system. On the one hand, this is great for administrators, as this enables them to manage their systems out of the box, but on the other hand, adversaries can leverage PowerShell to execute their malicious payloads.
PowerShell itself provides a variety of features that can not only help you to improve the security of your environment but also help you with your next red team engagement. In this book, we will look at PowerShell for cybersecurity from both sides of the coin – attacker and defender, red and blue team. By reading this book, you’ll gain a deep understanding of PowerShell’s security capabilities and how to use them.
You will learn that PowerShell is not “dangerous,” as some people assume; you will, rather, learn how to configure and utilize it to strengthen the security of your environment instead.
This book provides guidance on using PowerShell and related mitigations to detect attacks and strengthen your environment against threats. We’ll first revisit the basics of PowerShell and learn about scripting fundamentals. You’ll gain unique insights into PowerShell security-related event logging that you won’t find elsewhere, and learn about configuring PowerShell remoting.
We will dive into system and API access, exploring exploitation and hijacking techniques, and how adversaries leverage Active Directory and Azure AD/Entra ID, combined with a variety of deep and detailed knowledge behind those technologies. The red and blue team cookbooks both provide valuable code snippets for the daily use of PowerShell practitioners.
Another very important topic is mitigations that help you secure your environment. We will deep-dive into Just Enough Administration (JEA), a technology that is not very well known, providing you with detailed explanations, examples, and even a way to simplify deploying this technology. We will explore language modes and learn how application control and code signing impact PowerShell. We’ll also look at the Antimalware Scan Interface (AMSI) and learn why it is helpful and how adversaries attempt to bypass it.
So, what are you waiting for? Get ready to transform PowerShell into your greatest ally, empowering both red and blue teamers alike in the relentless battle against cyber threats.
This book is designed for security professionals, penetration testers, system administrators, red and blue teamers, and cybersecurity enthusiasts who want to enhance their security operations with PowerShell. Whether you’re experienced or new to the field, the book provides valuable insights and practical techniques to leverage PowerShell for various security tasks, including research and development exploits and security bypasses, as well as understanding how adversaries operate to mitigate threats and better protect your environment.
A basic understanding of PowerShell and cybersecurity fundamentals is recommended, and familiarity with concepts such as Active Directory and other programming languages, such as C and Assembly, can be beneficial.
Chapter 1, Getting Started with PowerShell, provides an introduction to PowerShell, exploring its history and highlighting its relevance in cybersecurity. You will learn about Object-Oriented Programming principles, key concepts such as the execution policy and the help system, and the security features introduced in each PowerShell version.
Chapter 2, PowerShell Scripting Fundamentals, covers the PowerShell scripting essentials, including variables, data types, operators, control structure conditions and loops, and naming conventions. The chapter also explores PowerShell profiles, PSDrives, and creating reusable code with cmdlets, functions, modules, and aliases.
Chapter 3, Exploring PowerShell Remote Management Technologies and PowerShell Remoting, dives into some of PowerShell’s remote management technologies, such as WinRM, WMI, CIM, OMI, SSH remoting, and, of course, PowerShell remoting. You will learn how to configure PowerShell remoting to establish remote connections, create custom endpoints, and execute PowerShell commands remotely.
Chapter 4, Detection – Auditing and Monitoring, explores the importance of logging for effective detection and monitoring in PowerShell environments. You will learn about essential log files, logging features such as module and script block logging, protected event logging, PowerShell transcripts, and how to analyze event logs using PowerShell.
Chapter 5, PowerShell Is Powerful – System and API Access, explores PowerShell’s system and API access capabilities. You will learn about working with the Windows registry, employing the Windows API, utilizing .NET classes for advanced techniques, and leveraging the power of WMI. The chapter also covers how to execute PowerShell without directly invoking powershell.exe.
Chapter 6, Active Directory – Attacks and Mitigation, explores AD security, including authentication protocols, enumeration, privileged accounts, password spraying, access rights, credential theft risks, and mitigation strategies. We will also look at Microsoft security baselines and the Security Compliance Toolkit.
Chapter 7, Hacking the Cloud – Exploiting Azure Active Directory/Entra ID, delves into Azure AD/Entra ID and explores its authentication mechanisms, privileged accounts, PowerShell access, and various attack vectors. You will gain insights into techniques such as anonymous enumeration, password spraying, and credential theft in Azure AD, along with mitigation strategies.
Chapter 8, Red Team Tasks and Cookbook, introduces you to the phases of an attack and common PowerShell red team tools. The chapter then provides a red team cookbook with various recipes, sorted by MITRE ATT&CK areas, such as reconnaissance, execution, persistence, defense evasion, credential access, discovery, lateral movement, command and control, exfiltration, and impact.
Chapter 9, Blue Team Tasks and Cookbook, focuses on blue team tasks and provides a cookbook of practical PowerShell code snippets. It first introduces the “protect, detect, respond” approach and highlights common PowerShell blue team tools. The cookbook provides a variety of blue team recipes, such as examining installed and missing updates, monitoring and preventing bypasses, isolating compromised systems, and analyzing and managing processes, services, and network connections.
Chapter 10, Language Modes and Just Enough Administration (JEA), first explores language modes in PowerShell and their impact on script execution. It then focuses on JEA, enabling administrators to delegate specific tasks to non-admin users using role-based access control. The chapter explains JEA in detail, including role capability and session configuration files, logging, and best practices, and provides guidance on how to efficiently deploy JEA.
Chapter 11, AppLocker, Application Control, and Code Signing, dives into application control and code signing, focusing on preventing unauthorized script execution, planning for application control, and deploying mechanisms such as Microsoft AppLocker and Windows Defender Application Control. It also explores virtualization-based security and the impact on PowerShell when application control is enforced.
Chapter 12, Exploring the Antimalware Scan Interface (AMSI), covers the AMSI, exploring its functionality and purpose. It provides practical examples to demonstrate the importance of the AMSI in detecting malicious activities. The chapter also discusses various techniques that adversaries use to bypass and disable AMSI, including obfuscation and Base64 encoding.
Chapter 13, What Else? – Further Mitigations and Resources, provides an overview of the additional PowerShell-related mitigations and resources to enhance your security, such as secure scripting, Desired State Configuration, hardening systems and environments, and Endpoint Detection and Response.
For most chapters, you will need PowerShell 7.3 and above, as well as a Visual Studio Code installation to examine and edit your code.
Depending on the chapter you follow, we will also look at other technologies, such as Windows PowerShell 5.1, Visual Studio, C/C++/C#, Visual Basic, Assembly, Ghidra, Wireshark, and Microsoft Excel.
Software/hardware covered in the book
Operating system requirements
PowerShell 7.3 and above
Windows 10 and above
Windows PowerShell 5.1
Windows Server 2019 and above
Visual Studio Code
Although most examples in this book might work with one test machine only, it is highly recommended to set up a demo environment to improve your experience for some parts of this book.
I used virtual machines to set up my environment, and I recommend doing the same to follow along. Hyper-V is a free hypervisor that you can use to set up your machines.
For my demo environment, I set up the following machines, which I will reference throughout this book:
PSSec-PC01: 172.29.0.12, Windows 10 Enterprise, 22H2, joined to the domain PSSec.localPSSec-PC02: 172.29.0.13, Windows 10 Enterprise, 22H2, joined to the domain PSSec.localPSSec-Server: 172.29.0.20, Windows Server 2019 Datacenter, joined to the domain PSSec.localDC01: 172.29.0.10, Windows Server 2019 Datacenter, hosting the domain PSSec.localInstalled relevant roles: Active Directory Certificate, Active Directory Domain Services, DNS Server, and Group Policy ManagementAzure demo environment for Chapter 7: PSSec-Demo.onmicrosoft.comOptional: Linux and macOS to follow the PowerShell remoting (SSH) configuration in Chapter 3The following diagram demonstrates the relevant setup used in this book:
Figure P.1 – The setup used in this book
This setup is only configured in a test environment and should, therefore, not be used in production environments.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/PowerShell-Automation-and-Scripting-for-Cybersecurity. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
All the links mentioned in each chapter will be maintained on our GitHub repository. Links are often subject to change, the links on the GitHub repository will remain up-to-date (of course following update cycles) in case the printed URLs give an error.
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: “Export one or more aliases with Export-Alias – either as a .csv file or as a script.”
A block of code is set as follows:
if (<condition>) { <action> }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
if ($color -eq "blue") { Write-Host "The color is blue!" } elseif ($color -eq "green"){ Write-Host "The color is green!" }Any command-line input or output is written as follows:
> ("Hello World!").Length 12Bold: 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: “Configure the Turn on Script Execution setting, and choose the Allow local scripts and remote signed scripts option.”
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. You can also contact the author via Twitter (@miriamxyra) or via Mastodon (@[email protected]).
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 PowerShell Automation and Scripting for CyberSecurity, 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/9781800566378
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part, we are revisiting the PowerShell fundamentals necessary for getting started with PowerShell for cybersecurity. We will begin by reviewing the basics, including Object-Oriented Programming principles, the differences between Windows PowerShell and PowerShell Core, the fundamental concepts of PowerShell, as well as the security features introduced in each PowerShell version.
Next, we’ll explore the essential foundations of PowerShell scripting. By the end of this part, you will have the skills to write PowerShell scripts utilizing various control structures, variables, and operators, enabling you to create reusable code efficiently.
You will also explore how to configure and utilize remote management technologies, with a special focus on PowerShell Remoting. You will gain insights into the security-specific facts and best practices regarding PowerShell Remoting and authentication.
Finally, we will look into PowerShell-related Event Logging: you will understand which Windows event logs and events are the most important ones when it comes to PowerShell cybersecurity. We’ll examine how to configure Script Block Logging, Module Logging, and transcripts and how to analyze event logs most efficiently.
This part has the following chapters:
Chapter 1, Getting Started with PowerShellChapter 2, PowerShell Scripting FundamentalsChapter 3, Exploring PowerShell Remote Management Technologies and PowerShell RemotingChapter 4, Detection – Auditing and MonitoringThis introductory chapter will take a look at the fundamentals of working with PowerShell. It is meant as a basic primer on PowerShell for cybersecurity and acts as an introduction to object-oriented programming (OOP) and how to get started when working with PowerShell.
This chapter complements Chapter 2, PowerShell Scripting Fundamentals, in which we will dive deeper into the scripting part. Both chapters should help you to get started and act as a reference when working with later chapters.
You will learn the basics of what PowerShell is, its history, and why it has gained more importance in the last few years when it comes to cybersecurity.
You will get an overview of the editors and how to help yourself using existing functionalities. In this chapter, you will gain a deeper understanding of the following topics:
What is PowerShell?The history of PowerShellWhy is PowerShell useful for cybersecurity?Introduction to OOPWindows PowerShell and PowerShell CoreExecution policyHelp systemPowerShell versionsPowerShell editorsTo get the most out of this chapter, ensure that you have the following:
PowerShell 7.3 and aboveVisual Studio Code installedAccess to the GitHub repository for Chapter01:https://github.com/PacktPublishing/PowerShell-Automation-and-Scripting-for-Cybersecurity/tree/master/Chapter01
PowerShell is a scripting framework and command shell, built on .NET. It is implemented, by default, on Windows Operating Systems (OSs). It is object-based, which means that everything you work with (such as variables, input, and more) has properties and methods. That opens up a lot of possibilities when working with PowerShell.
Additionally, PowerShell has a pipeline and allows you to pipe input into other commands to reuse it. This combines the advantages of a command line-based script language with an object-oriented language. And on top of this, it has a built-in help system that allows you to help yourself while working on the console.
PowerShell does not exclusively run on Windows OSs. Since PowerShell Core was released in 2016, it can run on any OS, including Linux and macOS devices.
It helps security professionals to get a lot of work done in a very short space of time. Not only do blue teamers find it useful, but also red teamers. As with every feature that provides a lot of capabilities and enables you to do your daily work in a more efficient way, it can be used for good and bad purposes. It can be a mighty tool for professionals, but as usual, security professionals need to do their part to secure their environments so that existing tools and machines will not be abused by adversaries.
But first, let's take a look at how PowerShell was born and how it developed over the years.
Before PowerShell was created, there were already Command Line Interfaces (CLIs) available, shipped with each OS to manage the system via command line: COMMAND.COM was the default in MS DOS and Windows 9.x, while cmd.exe was the default in the Windows NT family. The latter, cmd.exe, is still integrated within modern Windows OSs such as Windows 10.
Those CLIs could be used to not only execute commands from the command line but also to write scripts to automate tasks, using the batch file syntax.
Because not all functions of the Graphical User Interface (GUI) were available, it was not possible to automate all tasks via the command line. Additionally, the language had inconsistencies, so scripting was not as easy as it should have been in the first place.
In 1998, Microsoft released Windows Script Host (cscript.exe) in Windows 98 to overcome the limits of the former CLIs and to improve the scripting experience. With cscript.exe, it now became possible to work with the APIs of the Component Object Model (COM), which made this interface very mighty; so mighty that not only did system administrators leverage this new feature but also the malware authors. This quickly lent cscript.exe the reputation of being a vulnerable vector of the OS.
Additionally, the documentation of Windows Script Host was not easily accessible, and there were even more CLIs developed for different use cases besides cscript.exe, such as netshand wmic.
In 1999, Jeffrey Snover, who had a UNIX background, started to work for Microsoft. Snover was a big fan of command lines and automation, so his initial goal was to use UNIX tools on Microsoft systems, supporting the Microsoft Windows Services for UNIX (SFU).
However, as there is a big architectural difference between Windows and UNIX-based systems, he quickly noticed that making UNIX tools work on Windows didn't bring any value to Windows-based systems.
While UNIX systems relied on ASCII files that could be easily leveraged and manipulated with tools such as awk, sed, grep, and more, Windows systems were API-based, leveraging structured data.
So, he decided that he could do better and, in 2002, started to work on a new command-line interface called Monad (also known as Microsoft Shell/MSH).
Now, Monad not only had the option to pass structured data (objects) into the pipe, instead of simple text, but also run scripts remotely on multiple devices. Additionally, it was easier for administrators to use Monad for administration as many default tasks were simplified within this framework.
On April 25, 2006, Microsoft announced that Monad was renamed PowerShell. In the same year, the first version of PowerShell was released, and not much later (in January 2007), PowerShell was released for Windows Vista.
In 2009, PowerShell 2.0 was released as a component of Windows 7 and Windows Server 2008 R2 that was integrated, by default, into the OS.
Over the years, PowerShell was developed even further, and many new versions were released in the meantime, containing new features and improvements.
Then, in 2016, Microsoft announced that PowerShell would be made open source (MIT license) and would also be supported cross-platform.
PowerShell 5.1, which was also released in 2016, was the last Windows-only PowerShell version. It is still shipped on Windows systems but is no longer developed.
The PowerShell team was in the process of supporting Nano Server. So, there was a full version of PowerShell supporting Windows servers and clients. Nano Server had a severely trimmed version of .NET (called .NET Core), so the team had to reduce functions and chop it down to make PowerShell work with .NET Core. So, technically PowerShell 5.1 for Nano Server was the first version of PowerShell Core.
The first real and official version of PowerShell Core was 6.0, which also offered support for cross-platform such as macOS and Linux.
PowerShell runs on most modern Windows systems as a default. It helps administrators to automate their daily workflows. Since PowerShell is available on all systems, it also makes it easier for attackers to use the scripting language for their own purposes – if attackers get access to a system, for example, through a credential theft attack.
For attackers, that sounds amazing: a preinstalled scripting framework that provides direct access to cmdlets and the underlying .NET Framework. Automation allows you to get a lot done – not just for a good purpose.
No! I have often heard this question when talking to CISOs. As PowerShell is seen more and more in the hands of the red team, some people fear the capabilities of this mighty scripting framework.
But as usual, it's not black and white, and organizations should rather think about how to harden their systems and protect their identities, how to implement better detection, and how to leverage PowerShell in a way that benefits their workloads and processes – instead of worrying about PowerShell.
In the end, when you set up a server, you don't just install it and connect it to the internet. The same goes for PowerShell: you don't just enable PowerShell remote usage in your organization allowing everybody to connect remotely to your servers, regardless of their role.
PowerShell is just a scripting language, similar to the preinstalled cscript or batch. Technically, it provides the same potential impact as Javaor .NET.
And if we compare it to Linux or macOS, saying that PowerShell is dangerous is like saying that Bash or zsh is dangerous.
A friend who worked in incident response for many years once told me about adversaries dropping C# code files on the target boxes and calling csc.exe (which is part of the .NET Framework) to compile the dropped files directly on the box. Which is a very effective way to abuse a preinstalled software to install the adversary's code on the system without even leveraging PowerShell.
So, in other words, it is not the language that is dangerous or malicious; adversaries still require identities or authorization for the execution, which can be constrained by the security expert or administrator who is responsible for the environment's security.
And to be honest, all red teamers that I know or have talked to are starting to move more and more to other languages such as C# or C++ instead of PowerShell, if they want to stay undetected during their attacks.
If the right security measures and detections are implemented, it is almost impossible to go unnoticed when using PowerShell for an attack in a well-configured and protected environment. Once you have followed the security best practices, PowerShell will support you to keep your environment safe and help you track any attackers in your environment.
Additionally, a lot of your environmental security depends on your global credentials and access hygiene: before attackers can leverage PowerShell, first, they need access to a system. We'll take a closer look at how to secure your environment credential-wise in Chapter 6, Active Directory – Attacks and Mitigation.
PowerShell not only enables your IT professionals to work more efficiently and to get things done quicker, but it also provides your security team with great options.
PowerShell offers a lot of built-in safety guards that you will learn more about in this book:
Automation and compliance: One of the main benefits is that you can automate repeatable, tedious tasks. Not only will your administrators benefit from automating tasks, but your Security Operations Center (SOC) can automate response actions taken, triggered by certain events.One of the main reasons organizations are getting breached is missing security updates. It is not easy to keep all systems up to date – even with updated management systems such as Windows Server Update Services (WSUS) in place. PowerShell can help to build a mechanism to regularly check whether updates are missing to keep your environment secure.
Auditing and enforcing compliance can easily be achieved using Desired State Configuration (DSC).
Automate security checks to audit Active Directory or server security and enforce your security baselines. DSC allows you to control the configuration of your servers at any time. You can configure your machines to reset their configuration up to every 15 minutes to the configuration you specified.
Additionally, if you integrate DSC as part of your incident response plan, it is very easy to rebuild potentially compromised servers from the scratch.
Control who is allowed to do what and where: By configuring PowerShell remoting/WinRM, you can specify who is allowed to log on to which device or server. Of course, it does not help against credential theft (as this is not a PowerShell topic), but it helps to granularly define which identity is allowed to do what. Additionally, it provides great auditing capabilities for remote connections.Constrained Language mode lets you restrict which PowerShell elements are allowed in a session. This can already help to prevent certain attacks.
And using Just Enough Administration (JEA), you can even restrict which roles/identities are allowed to run which commands on which machine. You can even restrict the parameters of a command.
Find out what is going on in your environment: PowerShell provides an extensive logging framework with many additional logging options such as creating transcripts and script block logging.Every action in PowerShell can be tracked if the right infrastructure is put behind it. You can even automate your response actions using a Security Orchestration, Automation, and Response (SOAR) approach.
Using PowerShell, you can quickly pull and search event logs of multiple servers, connecting remotely to analyze them.
In a case of a security breach, PowerShell can also help you to collect and investigate the forensic artifacts and to automate the investigation. There are great modules such as PowerForensics that you can reuse for your forensics operations and post-breach remediation.
Restrict which scripts are allowed to run: By default, PowerShell brings a feature called Execution Policy. Although it is not a security control, it prevents users from unintentionally running scripts.Signing your code helps you to verify whether a script that is run is considered legit: if you allow only signed scripts to run, this is a great way to prevent your users to run scripts directly downloaded from the internet.
AppLocker, in combination with Code Signing, can help you to control which scripts are allowed to run in your organization.
The mentioned solutions do not restrict interactive code restriction though.
Detect and stop malicious code from execution: The Antimalware Scan Interface (AMSI) provides a possibility to have your code checked by the antimalware solution that is currently present on the machine. This can help to detect malicious code and is also a great safeguard against file-less malware attacks (living off the land) – attacks that don't require files to be stored on the machine, but rather directly run the code in memory.It is integrated directly into PowerShell and can assess scripts, interactive use, and dynamic code evaluation.
These are only some examples of how PowerShell can support the blue team, but it should already give you an overview of how blue teamers can benefit from using and auditing PowerShell.
It is also worth reading the great blog article PowerShell ♥ the Blue Team that the Microsoft PowerShell team has published to provide advice on how PowerShell supports blue teamers: https://devblogs.microsoft.com/powershell/powershell-the-blue-team/.
You will learn more about possible attacks, mitigations, and bypasses during your journey throughout this book.
But first, let's start refreshing your knowledge of PowerShell fundamentals. Enjoy!
Before we can jump directly into scripting for cybersecurity and crazy red or blue team tasks, it is important to know some of the basics of PowerShell. Here are some refreshers that will help you to get started.
Introduction to OOP
PowerShell is an object-oriented language. OOP allows developers to think of software development as if they were working with real-life objects or entities. Some of the main advantages of OOP are that it's scalable, flexible, and overall, it lets you efficiently reuse your code.
Some of the base terminologies in OOP are classes, objects, properties, and methods. And if we look at the four main principles of OOP – encapsulation, abstraction, inheritance, and polymorphism – you quickly feel overwhelmed if you have no experience with OOP yet.
But don't worry, it is not as hard as it sounds, and OOP will make your life easier!
To better understand those concepts and principles, let's look at Alice and Bob as an example. They are both human beings; therefore, they share the same class: human. Both are our working entities in our example and, therefore, are our objects.
A class is a collection of properties and methods, similar to a blueprint for objects. Alice and Bob are both humans and share many properties and methods. Both have a certain amount of energy they can spend per day, can feel more or less relaxed, and need to work to gain money.
Both need to work and like to drink coffee. During the night, both need to sleep to restore their energy:
Figure 1.1 – Alice, the CISO
Alice works as a Chief Information Security Officer (CISO) and, often, plays between meetings and in the evening with her cat Mr. Meow, which helps her to relax.
Figure 1.2 – Bob, the security consultant
In comparison, Bob works as a security consultant. Although he is also a human, he has different methods than Alice: Bob does not have a cat, but he enjoys painting in his spare time, which makes him feel relaxed and restores his batteries.
Let's explore the four main principles of OOP, looking at Alice and Bob.
Encapsulation is achieved if each object keeps its state private inside a class. Other objects cannot access it directly, they need to call a method to change its state.
For example, Alice's state includes the private EnergyLevel, RelaxationStatus, and Money properties. She also has a private SighHappily() method. She can call this method whenever she wants; the other classes can't influence whenever Alice sighs happily. When Alice plays with her cat Mr. Meow, the SighHappily() method is called by default – Alice really enjoys this activity.
What other classes can do is call the public Work(), DrinkCoffee(), Sleep(), and PlayWithCat() functions. Those functions can change the internal state and even call the private SighHappily() method when Alice plays with her cat Mr. Meow:
Figure 1.3 – A closer look at public and private methods
To summarize, if you want to change a private property's value, you always need to call a public method that is linked to the private state. Like in real life, there is no magic cure – besides coffee – to immediately remove your tiredness. And even with coffee, you still need to perform an action to drink it. The binding that exists between the private state and the public methods is called encapsulation.
Abstraction can be thought of as a natural extension of encapsulation. Often, a code base becomes super extensive, and you can lose the overview. Applying abstraction means that each object should expose its methods at only a high level and should hide details that are not necessary to other objects.
So, for example, we have the Work() method defined in the human class.
Depending on how technical your parents are, they might understand what you do in your daily job. Mine, however, do not understand a word that I say. They just know that I work with computers. So, if I talk with my parents on the phone, instead of telling them every detail and boring them to death, I just tell them that I have finished work.
A similar principle should also apply when writing object-oriented code. Although there are many different operations behind the Work()method, it is abstracted and only the relevant data is shown.
Another example could be an elevator in the office. When you push a button to get to a different floor, something happens below the surface. But only the buttons and the display, indicating the floor level, are shown to the user of the elevator. This principle is called abstraction and helps to keep an overview of the task that should be achieved.
If you require very similar classes or objects, you won't want to duplicate existing code. This would make things more complicated, work-intensive, and there would be a higher chance of implementing bugs – for example, if you have to change the code for all different instances and forget one.
So, our Alice and Bob objects are quite similar and share a common logic, but they are not entirely the same. They are both humans, but they have different professions that require different skillsets and tasks performed.
All CISOs and all security consultants are humans, so both roles inherit all properties and methods from the human class.
Similar to the SecurityConsultant class, the CISO class inherits all properties and methods of the human class. However, while the CISO class also introduces the StrategicPlanningSkillset property and the CalculateRisk() method, they are not necessary for the SecurityConsultant class.
The SecurityConsultant class defines their own TechnicalAuditingSkillset property and AnalyzeSystem() and TalkToCustomer() methods.
Alice inherits all the skills that were defined in the human class, and in the CISO class, which builds a hierarchy: human is now the parent class of the CISO class, while the CISO class is Alice's parent class – in this case, Alice is the child object.
Additionally, Bob inherits all the properties and methods defined in the human class, but in comparison to Alice, he inherits everything from the SecurityConsultant class:
Figure 1.4 – Inheritance: parent and child classes and objects
And yes, dear security consultants and CISOs, I know that your profession requires far more skills and that your role is far more challenging than is shown in this example. I tried to make it abstract to keep it simple.
Looking at Alice and Bob, Alice enjoys spending time with her cat, Mr. Meow, so she brings her unique PlayWithCat() and SighHappily() methods. Bob does not have a cat, but he enjoys painting and, therefore, has the unique Paint() method.
Using inheritance, we only need to add what is necessary to implement the required changes while using the existing logic with the parent classes.
Now that we have looked into the concept of inheritance, polymorphism is not far off. Polymorphism means that although you can create different objects out of different classes, all classes and objects can be used just like their parents.
If we look at Alice and Bob, both are humans. That means we can rely on the fact that both support the EnergyLevel, RelaxationStatus, and Money properties along with the Work(), DrinkCoffee(), and Sleep() methods.
Additionally, they can support other unique properties and methods, but they always support the same ones as their parents to avoid confusion.
Please note that this overview should only serve as a high-level overview; if you want to dive deeper into the concepts of OOP, you might want to look into other literature solely on OOP, such as Learning Object-Oriented Programming, which is written by Gaston C. Hillar and also published by Packt.
Now that you understand the base concepts of OOP, let's get back to working with PowerShell.
By default, Windows PowerShell 5.1 is installed on all newer systems, starting with Windows 10. You can either open it by searching in your Start menu for PowerShell, or you can also start it via Windows key + R and typing in powershellor powershell.exe.
In this console, you can run commands, scripts, or cmdlets:
Figure 1.5 – The Windows PowerShell version 5.1 CLI
On Windows 10 devices, the default location of Windows PowerShell v5.1 is under the following:
Windows PowerShell: %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exeWindows PowerShell (x86): %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exeWhy Is There a v1.0 in the Path? Does That Mean I'm Running an Old Version?
As we will also take a more detailed look at PowerShell versions in this book, you might think Omg, I heard that old versions do not provide all necessary security features, such as logging and many more! Am I at risk?
No, you aren't. Although the path contains v1, newer versions are being installed in this exact path. Originally it was planned to create a new folder with the correct version name, but later Microsoft decided against it so that no breaking changes are caused.
You might have also noticed the .ps1 script extension. We have the same reason here: originally it was also planned that each version will be differentiated by the script extension. But out of backward compatibility reasons, this idea was not implemented for PowerShell v2 logic.
But since Windows PowerShell will not be developed further, it makes sense to install and use the latest PowerShell Core binaries.
On newer systems, Windows PowerShell version 5.1 is still installed by default. To use the latest PowerShell Core version, you need to manually download and install it. While this book was written, the latest stable PowerShell Core version was PowerShell 7.3.6.
To learn more about how to download and install the latest PowerShell Core version, you can leverage the official documentation: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows.
You will find the latest stable PowerShell Core version here: https://aka.ms/powershell-release?tag=stable.
Download it and start the installation. The installation wizard opens and guides you through the installation. Depending on your requirements, you can specify what should be configured by default:
Figure 1.6 – Installing PowerShell 7
Don't worry if you haven't enabled PowerShell remoting yet. You can configure this option later. The wizard runs through and installs PowerShell Core in the separate $env:ProgramFiles\PowerShell\7 location. PowerShell 7 is designed to run parallel to PowerShell 5.1.
After the setup is complete, you can launch the new PowerShell console and pin it to your taskbar or the Start menu:
Figure 1.7 – The PowerShell version 7 CLI
Now you can use the latest PowerShell Core version instead of the old Windows PowerShell version 5.1.
To define consistent options for your servers in your environment, Group Policy helps with the configuration.
When installing PowerShell 7, Group Policy templates, along with an installation script, will be populated under $PSHOME.
Group Policy requires two kinds of templates (.admx, .adml) to allow the configuration of registry-based settings.
You can find the templates as well as the installation script using the Get-ChildItem -Path $PSHOME -Filter *Core*Policy* command:
Figure 1.8 – Locating the PowerShell Core Group Policy templates and installation script
Type $PSHOME\InstallPSCorePolicyDefinitions.ps1 into your domain controller, press Tab, and confirm with Enter.
The Group Policy templates for PowerShell Core will be installed, and you can access them by navigating to the following:
Computer Configuration | Administrative Templates | PowerShell CoreUser Configuration |Administrative Templates | PowerShell CoreYou can now use them to configure PowerShell Core in your environment, in parallel to Windows PowerShell.
You can configure both policies differently, but to avoid confusion and misconfiguration, I recommend configuring the setting in Windows PowerShell and checking the Use Windows PowerShell Policy setting box, which is available in all PowerShell Core Group Policy settings.
Autocompleting commands can be very useful and can save a lot of time. You can either use Tab or Ctrl + spacebar for autocompletion:
With Tab, the command that comes nearest to the command that you already typed in is shown. With every other Tab you can switch through the commands and have the next one – sorted alphabetically – entered.If there are multiple commands that fit the string you entered, you can type Ctrl + spacebar to see all possible commands. You can use the arrow keys to select a command. Confirm with Enter:Figure 1.9 – Using Ctrl + spacebar to choose the right command
Sometimes, it can be useful to find out which commands you have used recently in your PowerShell session:
Figure 1.10 – Using Get-History
All recently used commands are shown. Use the arrow keys to browse the last-used commands, change them, and run them again.
In this example, one of the last commands that was run was the Enter-PSSession command, which initiates a PowerShell remoting session to the specified host – in this case, to PSSEC-PC01.
If you want to initiate another PowerShell remoting session to PSSEC-PC02 instead of PSSEC-PC01, you don't have to type in the whole command again: just use the arrow up key once, then change -ComputerName to PSSEC-PC02 and hit Enter to execute it.
If your configuration allows you to connect to PSSEC-PC02 from this PC using the same credentials, the connection is established, and you can work remotely on PSSEC-PC02.
We will have a closer look at PowerShell remoting in Chapter 3, Exploring PowerShell Remote Management Technologies and PowerShell Remoting.
To search the history, pipe the Get-History command to Select-String and define the string that you are searching for:
Get-History | Select-String <string to search>If you are a person who likes to keep your commands terse, aliases might speak to you. We will take a look at them later, but for now, here's an example of how you'd search the history, using the same commands but abbreviated as an alias:
h | sts <string to search>If you want to see all the PowerShell remoting sessions that were established in this session, you can search for the Enter-PSSession string:
Figure 1.11 – Searching the session history
However, if you only search for a substring such as PSSession, you can find all occurrences of the PSSession string, including the last execution of Get-History:
Figure 1.12 – Searching the session history
When you are looking for a command that was run recently, you don't have to query the entire history. To only get the last X history entries, you can specify the -Count parameter.
In this example, to get the last five entries, specify -Count 5:
Figure 1.13 – Getting the last five history entries
When you close a PowerShell session, the session history is deleted. That means you will get no results if you use the session-bound Get-History command upon starting a new session.
But there's also a persistent history that you can query, as provided by the PSReadline