PowerShell for Penetration Testing - Dr. Andrew Blyth - E-Book

PowerShell for Penetration Testing E-Book

Dr. Andrew Blyth

0,0
35,99 €

oder
-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

PowerShell for Penetration Testing is a comprehensive guide designed to equip you with the essential skills you need for conducting effective penetration tests using PowerShell.
You'll start by laying a solid foundation by familiarizing yourself with the core concepts of penetration testing and PowerShell scripting. In this part, you'll get up to speed with the fundamental scripting principles and their applications across various platforms. You’ll then explore network enumeration, port scanning, exploitation of web services, databases, and more using PowerShell tools. Hands-on exercises throughout the book will solidify your understanding of concepts and techniques. Extending the scope to cloud computing environments, particularly MS Azure and AWS, this book will guide you through conducting penetration tests in cloud settings, covering governance, reconnaissance, and networking intricacies. In the final part, post-exploitation techniques, including command-and-control structures and privilege escalation using PowerShell, will be explored. This section encompasses post-exploitation activities on both Microsoft Windows and Linux systems.
By the end of this book, you’ll have covered concise explanations, real-world examples, and exercises that will help you seamlessly perform penetration testing techniques using PowerShell.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



PowerShell for Penetration Testing

Explore the capabilities of PowerShell for pentesters across multiple platforms

Dr. Andrew Blyth

PowerShell for Penetration Testing

Copyright © 2024 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 Rana

Book Project Manager: Ashwini Gowda

Senior Editor: Athikho Sapuni Rishana

Technical Editor: Nithik Cheruvakodan

Copy Editor: Safis Editing

Proofreader: Athikho Sapuni Rishana

Indexer: Subalakshmi Govindhan

Production Designer: Vijay Kamble

Senior DevRel Marketing Coordinator: Maylou De Mello

First published: May 2024

Production reference: 1260424

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-83508-245-4

www.packtpub.com

I would like to thank my family and friends for all of their help, love, and support. Without them, this project would not have been possible.

– Dr. Andrew Blyth

Foreword

PowerShell for Penetration Testing is an impressively comprehensive guide created to empower both professional and aspiring pen testers in their journey to master the art of penetration testing.

As an old hand in the field of cybersecurity and penetration testing, I can say that the development and transformative power of automation in our craft cannot be denied, and in an ever-evolving landscape of threats and vulnerabilities, time is of the essence. Efficiency is paramount and provides the ability to swiftly and effectively execute assessment tasks that can make all the difference between stopping a potential breach and falling victim to it. In any time-limited penetration test, efficiencies that can be made on mundane tasks provide more opportunities to better examine and understand the threat surface of your scoped targets.

In this book, you will delve into the depths of PowerShell, a versatile and robust scripting language that serves as a potent weapon in the arsenal of any pen tester. From its origins as a Windows shell scripting tool to its current status as a cross-platform powerhouse, PowerShell has emerged as a vital weapon in cybersecurity, enabling practitioners to automate routine tasks, streamline workflows, and orchestrate complex attacks with precision, repeatability, and reliability.

Learning PowerShell can save you hundreds or even thousands of hours of toil. It empowers you to automate routine, but essential, assessment tasks and replicate exploits across diverse environments. The techniques in this book will allow you to scale your penetration testing efforts with ease. By utilizing the full capability of PowerShell, you can unleash your creativity, elevate your skill set, stay ahead of adversaries, and stand out from your peers.

In the pages that follow, you will undertake a journey that crosses the boundaries of conventional pen testing methodologies. Through hands-on tutorials, real-world examples, and expert insight, you will unlock the full potential of PowerShell and emerge as a formidable force in the world of penetration testing.

Whether you’re a veteran pen tester seeking to sharpen your skills or a novice eager to embark on a new adventure, PowerShell for Pen Testers has something to offer for everyone. So, grab your keyboard, fire up your terminals, and prepare to absorb the skills that will redefine the way you approach penetration testing.

– Campbell Murray, ChCSP, CSTL, CISSP

Contributors

About the author

Dr. Andrew Blyth boasts over three decades of extensive expertise spanning penetration testing, red teaming, forensics, and cybersecurity. Holding a BSc, MSc, and PhD in computer science, he stands as a stalwart in the field. Formerly occupying the esteemed position of professor of cybersecurity at the University of South Wales, he has contributed over 20 years to the realms of education and research, shaping the future of cybersecurity professionals. Notably, he played a pivotal role as a founding member of the renowned Tiger Scheme, a testament to his profound influence within the industry. His insights and knowledge have been widely shared across numerous security conferences, solidifying his status as a thought leader and authority in the cybersecurity domain.

About the reviewer

Gopi Narayanaswamy, with over 25 years in IT, excels in infrastructure, design, and cybersecurity. He assesses security for both on-premises and cloud environments, designing robust measures for networks, cloud platforms, and operational technology. A certified penetration tester, he utilizes offensive and defensive tools alongside Python, PowerShell, and Go for security automation. Gopi leverages SIEM/XDR tools (Wazuh and Microsoft Sentinel) and contributes to the field by developing Ansible modules with Python. His expertise extends to creating and implementing Python code for diverse IT tasks across various regions.

Table of Contents

Preface

Part 1: Introduction to Penetration Testing and PowerShell

1

Introduction to Penetration Testing

What is penetrating testing?

Stakeholders

Ethical, legal, and regulatory requirements

Managing and executing a penetration test

Using the cyber kill chain

Standards in penetration testing

Report writing

Summary

2

Programming Principles in PowerShell

Basic concepts of PowerShell and pipelines in PowerShell

JSON in PowerShell

Retrieving JSON data from web APIs

Parsing JSON data

JSON manipulation for payloads

Interacting with JSON from files

Web scraping and data extraction

XML in PowerShell

Reading and parsing XML files

Extracting information from XML nodes

Modifying XML data

Crafting XML payloads

XML injection testing

COM, WMI, and .NET in PowerShell

Using WMI for system information gathering

Querying WMI for network information

Interacting with COM objects

Using .NET for cryptographic operations

Using .NET for network operations

Analyzing .NET assemblies for vulnerabilities

Summary

Part 2: Identification and Exploitation

3

Network Services and DNS

Network services

TCP/IP network services

The IP addresses

The TCP/UDP port numbers

The OSI stack

DNS and types of DNS queries

DNS overview

Types of DNS queries

DNS and PowerShell

Summary

4

Network Enumeration and Port Scanning

Network enumeration using PowerShell

TCP port scanning using PowerShell

Single port scanning with Test-NetConnection

Multiple port scanning with Test-NetConnection

Enumerating open ports with Test-NetConnection

Single port scanning with .NET

Multiple port scanning with .NET

Enumerating all open ports with .NET

UDP port scanning using PowerShell

Using PowerShell tools for port scanning

Summary

5

The WEB, REST, and SOAP

PowerShell and the web

Web application security testing with PowerShell

REST application security testing with PowerShell

SOAP application security testing with PowerShell

Encoding JSON and XML in PowerShell

Encoding JSON in PowerShell

Decoding JSON in PowerShell

Encoding XML in PowerShell

Decoding XML in PowerShell

PowerShell and REST

OWASP analysis – injection

OWASP analysis – broken authentication

OWASP analysis – sensitive data exposure

OWASP analysis – XML External Entities (XXE)

OWASP analysis – broken access control

OWASP analysis – security misconfiguration

OWASP analysis – Cross-Site Scripting (XSS)

OWASP analysis – Cross-Site Request Forgery (CSRF)

OWASP analysis – unvalidated redirects and forwards

OWASP analysis – insecure deserialization

PowerShell and SOAP

OWASP analysis – injection

OWASP analysis – XXE

OWASP analysis – authentication bypass

OWASP analysis – insecure deserialization

OWASP analysis – unvalidated redirects and forwards

Summary

6

SMB, Active Directory, LDAP and Kerberos

PowerShell and SMB

Enumerating SMB shares

An SMB version assessment

Testing for weak passwords

SMB vulnerability scanning

Assessing SMB signing and encryption

The enumeration of active SMB sessions

Checking for guest access

Evaluating share permissions

SMB session monitoring

Automated ransomware detection

PowerShell, AD, and LDAP

The enumeration of active directory objects

Assessing user account security

Identifying inactive user accounts

Auditing group memberships

Identifying privileged accounts

Auditing password policy

Assessing LDAP permissions

Testing LDAP authentication

Identifying unsecured LDAP ports

Monitoring LDAP traffic

Testing LDAP with LDAPS

Identifying anomalies with PowerShell scripts

PowerShell and Kerberos

The enumeration of Kerberos tickets

Service Principal Name (SPN) enumeration

Credential harvesting with Mimikatz

Detecting golden ticket attacks

Kerberos ticket renewal analysis

Analyzing event logs

Password spray attacks

Summary

7

Databases: MySQL, PostgreSQL, and MSSQL

Accessing SQL databases using PowerShell

PowerShell and MySQL

Introduction to PowerShell and MySQL

Connecting to MySQL with PowerShell

Vulnerability assessment

Penetration testing

Access control verification

Security policy testing

Data protection and encryption

Logging and monitoring

PowerShell and PostgreSQL

Introduction to PowerShell and PostgreSQL

Connecting to PostgreSQL with PowerShell

Vulnerability assessment

Penetration testing

Access control verification

Security policy testing

Data protection and encryption

Logging and monitoring

PowerShell and Microsoft SQL (MSSQL)

Vulnerability assessment

Penetration testing

Access control verification

Security policy testing

Data protection and encryption

Logging and monitoring

Summary

8

Email Services: Exchange, SMTP, IMAP, and POP

PowerShell and Exchange

Enumeration with PowerShell

Autodiscover enumeration

Exploitation with PowerShell

PowerShell and SMTP

Enumeration with PowerShell

Exploitation with PowerShell

PowerShell and IMAP

Vulnerabilities in IMAP servers

Establishing an IMAP connection

Scanning for IMAP servers

PowerShell and POP

Port identification

Authentication checks

Brute-forcing

Banner grabbing

Summary

9

PowerShell and FTP, SFTP, SSH, and TFTP

PowerShell and FTP

Banner grabbing for FTP

Connecting to an FTP server

Brute-forcing authentication of an FTP connection

Anonymous access check

SSL/TLS support for an FTP server

Listing files on the FTP server

Uploading a file to an FTP server

Downloading a file from an FTP server

Strong password policies for FTP

Firewall and access control lists for FTP

PowerShell and TFTP

Identifying the TFTP server

Enumerating a TFTP server configuration

Verifying access controls for TFTP

PowerShell and SSH, SCP, and SFTP

SSH server configuration assessment

Brute-forcing authentication for SSH

SSH server access control

Reviewing user access

SCP server configuration assessment

SFTP server configuration assessment

Reviewing SFTP configuration

Security auditing tools for SSH

User authentication and authorization

Monitoring and logging

Modules

Summary

10

Brute Forcing in PowerShell

Brute forcing, in general, using PowerShell

Automated scripting

Password list attacks

Dictionary attacks

Credential stuffing

Rate limiting and stealth

Brute forcing FTP using PowerShell

Setting up the environment

Creating credential lists

FTP login attempt script

Handling FTP server responses

Rate limiting and stealth

Logging and reporting

Brute forcing SSH using PowerShell

Setting up the environment

Creating credential lists

SSH login attempt script

Handling SSH server responses

Rate limiting and stealth

Logging and reporting

Brute forcing web services using PowerShell

Understanding the web service

Setting up the environment

Installing required modules

Creating credential lists

Web service authentication

Handling web service responses

Rate limiting and stealth

Logging and reporting

Adapting to web service specifics

Handling CAPTCHA and multifactor authentication

Iterating and refining

Bruteforcing a hash

Understanding hash brute forcing

Setting up the environment

Hash types and hashcat

PowerShell script for hash brute forcing

Customization for different hash algorithms

Salting

Handling larger character sets and optimizing

Summary

11

PowerShell and Remote Control and Administration

Remote access and PowerShell

Enabling PowerShell remoting

Configuring WinRM

Connecting to a remote machine

Executing commands on remote machines

Remoting with credentials

Configuring trusted hosts

Session configuration

Parallel remoting

PowerShell and remote administration

Establishing remote sessions

Executing commands on remote machines

Remote variable usage

Remote script execution

Handling background jobs

Parallel remoting

Remote registry manipulation

Remote event log retrieval

Remote service management

Remote software installation

Remoting to Azure virtual machines

Remote network configuration

Remote user management

Security considerations

Remote file copy

Using PowerShell for SNMP

SNMP module installation

SNMP agent query

SNMP walking

SNMP settings

SNMP trap handling

SNMP bulk requests

SNMP monitoring with PowerShell

SNMP and PowerShell integration

SNMP and graphical interfaces

SNMP and logging

Summary

Part 3: Penetration Testing on Azure and AWS cloud Environments

12

Using PowerShell in Azure

Introduction to Azure

Azure architecture and governance

Azure Policy enforcement

Role-based access control (RBAC)

Resource tagging

Resource locking

Azure blueprint deployment

Compliance reporting

Accessing Azure

Install and import the Azure PowerShell module

Authenticate and connect to Azure

Networking in Azure

Resource discovery

Virtual network enumeration

Subnet analysis

Network security group exploration

Public IP address enumeration

Azure Active Directory (AAD) reconnaissance

Service principal enumeration

Constructing the network map

Identity Management and Role-Based Access Control

Gathering information about users and Identity Management

Exploring RBAC assignments

Reviewing access control settings for resources

Modifying RBAC assignments for simulation

Automating Identity Management and RBAC analysis

Azure Data Storage and permissions

Analyzing Azure Data Storage

Investigating data permissions

Checking RBAC settings

Analyzing data security with Azure Key Vault

Automating Data Storage and permissions analysis

Azure and SQL

Analyzing Azure Identity

Analyzing Azure SQL

Automating Identity and SQL analysis

Azure and key vaults

Analyzing Azure resources

Analyzing Azure Key Vaults

Automating the analysis of Azure resources and Key Vaults

Azure and virtual machines

Azure and Web Services

Analyzing Azure resources

Analyzing Web Services in Azure

Automating the analysis of Azure resources and Web Services

Summary

13

Using PowerShell in AWS

AWS governance and components

Accessing AWS and reconnaissance

AWS CLI and PowerShell integration

AWS Tools for PowerShell

AWS service enumeration

AWS resource profiling

Security group analysis

AWS Lambda function assessment

CloudTrail analysis

AWS credential validation

Continuous monitoring

Reporting and documentation

Networking in AWS

Amazon VPC enumeration

Subnet discovery

Security group assessment

Network ACL inspection

Elastic load balancer profiling

Route table analysis

VPN connection assessment

Direct Connect

Network flow logging

DNS configuration inspection

S3 bucket access check

Monitoring for anomalies

Continuous network scanning

Reporting and documentation

Data storage and S3 buckets

Listing all S3 buckets

Retrieving the bucket policy

Checking bucket permissions

Object listing and metadata

Downloading objects

Versioning checking

Server-side encryption assessment

Logging configuration

S3 bucket replication status

Cross-origin resource sharing (CORS) configuration

Intelligent-tiering configuration

Data classification and tagging

Continuous monitoring

Reporting and documentation

AWS and databases

Amazon RDS enumeration

Database configuration details

Security group analysis

IAM database authentication status

Database snapshots

Amazon Aurora cluster profiling

Database parameter groups

Database events

Encryption assessment

Database log files

Connection pooling configuration

Continuous monitoring

Reporting and documentation

AWS and security

AWS security group analysis

IAM user permissions assessment

KMS audit

AWS CloudTrail analysis

Amazon GuardDuty findings

AWS Inspector assessment

S3 bucket permissions

NACL inspections

Continuous monitoring

Reporting and documentation

AWS and containers

Amazon Elastic Container Registry (ECR) enumeration

Docker image analysis

ECS task definition examinations

Kubernetes cluster information

kubeconfig file validation

ECS service analysis

Kubernetes Pod inspection

Container security scanning

ECS task log retrieval

Kubernetes RBAC assessment

Continuous monitoring

ECS Container Insights

Reporting and documentation

AWS and web services

AWS API Gateway enumeration

Lambda function analysis

CloudFront distribution profiling

Amazon S3 website configuration

Route 53 DNS record inspection

AWS Certificate Manager (ACM) certificates

Application Load Balancer (ALB) profiling

AWS WAF Web ACL configuration

Amazon RDS for web application databases

WAF logging

AWS X-Ray for tracing

Continuous monitoring

Reporting and documentation

Security headers inspection

SSL/TLS configuration assessment

Cross-site scripting (XSS) vulnerability testing

SQL injection testing

Summary

Part 4: Post Exploitation and Command and Control

14

Command and Control

Post-exploitation, C2, and the cyber kill chain

PowerShell components used for C2

Cmdlets for network communication

Scripting for payload delivery

Encoded payloads to evade detection

Dynamic code loading with functions

DNS tunneling for covert communication

Living-off-the-land techniques

Using Empire for C2

An introduction to PowerShell Empire

Generating and delivering payloads

Executing commands on compromised systems

Post-exploitation modules for advanced tasks

Exfiltrating data

Web drive-by attacks

Evading antivirus detection

Dynamic scripting

Defensive measures

Using Meterpreter and PowerShell for C2

An introduction to Meterpreter

Setting up the attack environment

Exploiting a vulnerability

Utilizing Meterpreter

Post-exploitation with Meterpreter

Integrating PowerShell for enhanced capabilities

Obfuscating PowerShell commands

Using PowerShell for C2

Defensive measures

Summary

15

Post-Exploitation in Microsoft Windows

The role of post-exploitation in Microsoft Windows on a penetration test

Post-exploitation on Microsoft Windows

Privilege escalation

Credential dumping

Persistence

Lateral movement

Data exfiltration

Covering tracks

Profiling a user with PowerShell on Microsoft Windows

User information

Running processes

Network connections

File and directory access

Installed software

Recent activities

File permissions in Microsoft Windows

Viewing file permissions

Granting file permissions

Modifying file permissions

Revoking file permissions

Using PowerShell for privilege escalation on Microsoft Windows

Checking the current user’s privileges

Enumerating local administrators

Exploiting unquoted service paths

Exploiting insecure service permissions

DLL hijacking

Registry manipulation

Exploiting weak folder permissions

Scheduled task exploitation

Exploiting unattended installations

Summary

16

Post-Exploitation in Linux

The role of post-exploitation in Linux on a penetration test

Post-exploitation on Linux

Establishing persistence

Privilege escalation

Enumerating users and groups

Network enumeration

File and directory enumeration

Data exfiltration

Covering tracks

Profiling a user with PowerShell in Linux

User information

Running processes

Network connections

File and directory access

Installed software

Recent activities

Data exfiltration

File permissions in Linux

Viewing file permissions

Granting file permissions

Modifying file permissions

Revoking file permissions

Changing ownership

Checking effective permissions

Inheriting permissions

Checking Access Control Lists (ACLs)

Using PowerShell for privilege escalation in Linux

Checking the current user’s privileges

Enumerating local groups and users

Checking sudo configuration

Checking executable file permissions

Exploiting weak service configurations

Exploiting crontab entries

Exploiting world-writable directories

DLL hijacking

Password files and sensitive information

Exploiting wildcard injection

Exploiting setuid and setgid binaries

Exploiting environment variables

Index

Other Books You May Enjoy

Preface

Welcome to the realm of PowerShell penetration testing! In an era where cybersecurity threats are evolving alarmingly, understanding how to assess and fortify digital defenses effectively is paramount. PowerShell, a powerful scripting language native to Windows environments, has emerged as a versatile tool for offensive and defensive security operations. With its extensive capabilities and widespread deployment, mastering PowerShell for penetration testing is indispensable for security professionals striving to safeguard their organizations’ assets in today’s cyber landscape.

This book serves as a comprehensive guide to harnessing PowerShell’s potential for penetration testing purposes. Whether you are a seasoned cybersecurity practitioner or a novice enthusiast eager to delve into the intricacies of offensive security, this resource is designed to equip you with the knowledge and techniques needed to conduct efficient and effective penetration tests using PowerShell.

Throughout the pages of this book, we will embark on a journey that explores the fundamentals of penetration testing methodologies, the inner workings of PowerShell scripting, and the integration of various tools and techniques to simulate real-world attack scenarios. From reconnaissance and information gathering to exploitation and post-exploitation activities, each chapter is meticulously crafted to provide practical insights and hands-on exercises that reinforce your understanding of the subject matter.

As you progress through the chapters, you will learn how to leverage PowerShell’s built-in cmdlets, modules, and scripting capabilities to automate tasks, manipulate system components, and exploit vulnerabilities within target environments. Moreover, you will gain insights into how adversaries utilize PowerShell as a weapon of choice in their malicious campaigns, enabling you to adopt a proactive stance in mitigating potential threats.

Furthermore, this book goes beyond the technical aspects of penetration testing by emphasizing the importance of ethical conduct, responsible disclosure, and continuous learning within the cybersecurity community. By adhering to ethical guidelines and fostering a collaborative mindset, we can collectively enhance the resilience of digital infrastructures and promote a safer online ecosystem for all.

Whether you aspire to become a proficient penetration tester, bolster your organization’s security posture, or satisfy your curiosity about PowerShell’s capabilities in cybersecurity, this book is your definitive companion on the journey ahead. So, let us embark on this transformative odyssey together and unlock PowerShell’s full potential for penetration testing excellence.

Who this book is for

This book is for people practicing penetration testing and those wanting to learn it. It takes a practical, hands-on approach to learning and provides real-world examples. The book’s structure makes it easy for people to follow and develop an understanding of the core technologies relating to PowerShell as a tool for penetration testing.

What this book covers

Chapter 1, Introduction to Penetration Testing, explains a penetration test and its various components.

Chapter 2, Programming Principles in PowerShell, introduces the principles of PowerShell as they relate to penetration testing.

Chapter 3, Network Services and DNS, explores the concepts of using PowerShell to profile network services and DNS using a set of worked examples.

Chapter 4, Network Enumeration and Port Scanning, discusses using PowerShell for network enumeration and profiling and then re-enforces this learning through structured examples.

Chapter 5, The WEB, REST, and SOAP, explores concepts relating to how PowerShell can be used as part of a penetration test against web applications and web services using REST and SOAP. The learning associated with each concept is reinforced via a set of staged practical examples.

Chapter 6, SMB, Active Directory, LDAP, and Kerberos, introduces the concepts and tools within PowerShell that can be used to test SMB, Active Directory, LDAP, and Kerberos applications. Issues and concepts are discussed via practical examples.

Chapter 7, Databases: MySQL, PostgreSQL, and MSSQL, focuses on how PowerShell interfaces into databases and can be used as part of a security assessment.

Chapter 8, Email Services: Exchange, SMTP, IMAP, and POP, introduces how PowerShell can assess the security posture of email services.

Chapter 9, PowerShell and FTP, SFTP, SSH, and TFTP, explores the concepts of testing FTP, SFTP, SSH, and TFTP using PowerShell.

Chapter 10, Brute Forcing in PowerShell, shows how PowerShell can perform brute-forcing authentication for various network services.