
Python for Cybersecurity
Beschreibung
Python For Cybersecurity: Using Python for Cyber Offense and Defense delivers an intuitive and hands-on explanation of using Python for cybersecurity. It relies on the MITRE ATT&CK framework to structure its exploration of cyberattack techniques, attack defenses, and the key cybersecurity challenges facing network administrators and other stakeholders today.
Offering downloadable sample code, the book is written to help you discover how to use Python in a wide variety of cybersecurity situations, including:
* Reconnaissance, resource development, initial access, and execution
* Persistence, privilege escalation, defense evasion, and credential access
* Discovery, lateral movement, collection, and command and control
* Exfiltration and impact
Each chapter includes discussions of several techniques and sub-techniques that could be used to achieve an attacker's objectives in any of these use cases. The ideal resource for anyone with a professional or personal interest in cybersecurity, Python For Cybersecurity offers in-depth information about a wide variety of attacks and effective, Python-based defenses against them.
Weitere Details
Weitere Ausgaben
Person
Inhalt
- Cover
- Title Page
- Copyright Page
- About the Author
- Acknowledgments
- About the Technical Editor
- Contents at a Glance
- Contents
- Introduction
- How This Book Is Organized
- Tactics and Techniques
- Why MITRE ATT&CK?
- Tools You Will Need
- Setting Up Python
- Accessing Code Samples
- Installing Packages
- From Here
- Chapter 1 Fulfilling Pre-ATT&CK Objectives
- Active Scanning
- Scanning Networks with scapy
- Implementing a SYN Scan in scapy
- Performing a DNS Scan in scapy
- Running the Code
- Network Scanning for Defenders
- Monitoring Traffic with scapy
- Building Deceptive Responses
- Running the Code
- Search Open Technical Databases
- Offensive DNS Exploration
- Searching DNS Records
- Performing a DNS Lookup
- Reverse DNS Lookup
- Running the Code
- DNS Exploration for Defenders
- Handling DNS Requests
- Building a DNS Response
- Running the Code
- Summary
- Suggested Exercises
- Chapter 2 Gaining Initial Access
- Valid Accounts
- Discovering Default Accounts
- Accessing a List of Default Credentials
- Starting SSH Connections in Python
- Performing Telnet Queries in Python
- Running the Code
- Account Monitoring for Defenders
- Introduction to Windows Event Logs
- Accessing Event Logs in Python
- Detecting Failed Logon Attempts
- Identifying Unauthorized Access to Default Accounts
- Running the Code
- Replication Through Removable Media
- Exploiting Autorun
- Converting Python Scripts to Windows Executables
- Generating an Autorun File
- Setting Up the Removable Media
- Running the Code
- Detecting Autorun Scripts
- Identifying Removable Drives
- Finding Autorun Scripts
- Detecting Autorun Processes
- Running the Code
- Summary
- Suggested Exercises
- Chapter 3 Achieving Code Execution
- Windows Management Instrumentation
- Executing Code with WMI
- Creating Processes with WMI
- Launching Processes with PowerShell
- Running the Code
- WMI Event Monitoring for Defenders
- WMI in Windows Event Logs
- Accessing WMI Event Logs in Python
- Processing Event Log XML Data
- Running the Code
- Scheduled Task/Job
- Scheduling Malicious Tasks
- Checking for Scheduled Tasks
- Scheduling a Malicious Task
- Running the Code
- Task Scheduling for Defenders
- Querying Scheduled Tasks
- Identifying Suspicious Tasks
- Running the Code
- Summary
- Suggested Exercises
- Chapter 4 Maintaining Persistence
- Boot or Logon Autostart Execution
- Exploiting Registry Autorun
- The Windows Registry and Autorun Keys
- Modifying Autorun Keys with Python
- Running the Code
- Registry Monitoring for Defenders
- Querying Windows Registry Keys
- Searching the HKU Hive
- Running the Code
- Hijack Execution Flow
- Modifying the Windows Path
- Accessing the Windows Path
- Modifying the Path
- Running the Code
- Path Management for Defenders
- Detecting Path Modification via Timestamps
- Enabling Audit Events
- Monitoring Audit Logs
- Running the Code
- Summary
- Suggested Exercises
- Chapter 5 Performing Privilege Escalation
- Boot or Logon Initialization Scripts
- Creating Malicious Logon Scripts
- Achieving Privilege Escalation with Logon Scripts
- Creating a Logon Script
- Running the Code
- Searching for Logon Scripts
- Identifying Autorun Keys
- Running the Code
- Hijack Execution Flow
- Injecting Malicious Python Libraries
- How Python Finds Libraries
- Creating a Python Library
- Running the Code
- Detecting Suspicious Python Libraries
- Identifying Imports
- Detecting Duplicates
- Running the Code
- Summary
- Suggested Exercises
- Chapter 6 Evading Defenses
- Impair Defenses
- Disabling Antivirus
- Disabling Antivirus Autorun
- Terminating Processes
- Creating Decoy Antivirus Processes
- Catching Signals
- Running the Code
- Hide Artifacts
- Concealing Files in Alternate Data Streams
- Exploring Alternate Data Streams
- Alternate Data Streams in Python
- Running the Code
- Detecting Alternate Data Streams
- Walking a Directory with Python
- Using PowerShell to Detect ADS
- Parsing PowerShell Output
- Running the Code
- Summary
- Suggested Exercises
- Chapter 7 Accessing Credentials
- Credentials from Password Stores
- Dumping Credentials from Web Browsers
- Accessing the Chrome Master Key
- Querying the Chrome Login Data Database
- Parsing Output and Decrypting Passwords
- Running the Code
- Monitoring Chrome Passwords
- Enabling File Auditing
- Detecting Local State Access Attempts
- Running the Code
- Network Sniffing
- Sniffing Passwords with scapy
- Port-BasedProtocol Identification
- Sniffing FTP Passwords
- Extracting SMTP Passwords
- Tracking Telnet Authentication State
- Running the Code
- Creating Deceptive Network Connections
- Creating Decoy Connections
- Running the Code
- Summary
- Suggested Exercises
- Chapter 8 Performing Discovery
- Account Discovery
- Collecting User Account Data
- Identifying Administrator Accounts
- Collecting User Account Information
- Accessing Windows Password Policies
- Running the Code
- Monitoring User Accounts
- Monitoring Last Login Times
- Monitoring Administrator Login Attempts
- Running the Code
- File and Directory Discovery
- Identifying Valuable Files and Folders
- Regular Expressions for Data Discovery
- Parsing Different File Formats
- Running the Code
- Creating Honeypot Files and Folders
- Monitoring Decoy Content
- Creating the Decoy Content
- Running the Code
- Summary
- Suggested Exercises
- Chapter 9 Moving Laterally
- Remote Services
- Exploiting Windows Admin Shares
- Enabling Full Access to Administrative Shares
- Transferring Files via Administrative Shares
- Executing Commands on Administrative Shares
- Running the Code
- Admin Share Management for Defenders
- Monitoring File Operations
- Detecting Authentication Attempts
- Running the Code
- Use Alternative Authentication Material
- Collecting Web Session Cookies
- Accessing Web Session Cookies
- Running the Code
- Creating Deceptive Web Session Cookies
- Creating Decoy Cookies
- Monitoring Decoy Cookie Usage
- Running the Code
- Summary
- Suggested Exercises
- Chapter 10 Collecting Intelligence
- Clipboard Data
- Collecting Data from the Clipboard
- Accessing the Windows Clipboard
- Replacing Clipboard Data
- Clipboard Management for Defenders
- Monitoring the Clipboard
- Processing Clipboard Messages
- Identifying the Clipboard Owner
- Running the Code
- Email Collection
- Collecting Local Email Data
- Accessing Local Email Caches
- Running the Code
- Protecting Against Email Collection
- Identifying Email Caches
- Searching Archive Files
- Running the Code
- Summary
- Suggested Exercises
- Chapter 11 Implementing Command and Control
- Encrypted Channel
- Command and Control Over Encrypted Channels
- Encrypted Channel Client
- Encrypted Channel Server
- Running the Code
- Detecting Encrypted C2 Channels
- Performing Entropy Calculations
- Detecting Encrypted Traffic
- Running the Code
- Protocol Tunneling
- Command and Control via Protocol Tunneling
- Protocol Tunneling Client
- Protocol Tunneling Server
- Running the Code
- Detecting Protocol Tunneling
- Extracting Field Data
- Identifying Encoded Data
- Running the Code
- Summary
- Suggested Exercises
- Chapter 12 Exfiltrating Data
- Alternative Protocols
- Data Exfiltration Over Alternative Protocols
- Alternative Protocol Client
- Alternative Protocol Server
- Running the Code
- Detecting Alternative Protocols
- Detecting Embedded Data
- Running the Code
- Non-Application Layer Protocols
- Data Exfiltration via Non-Application Layer Protocols
- Non-ApplicationLayer Client
- Non-ApplicationLayer Server
- Running the Code
- Detecting Non-Application Layer Exfiltration
- Identifying Anomalous Type and Code Values
- Running the Code
- Summary
- Suggested Exercises
- Chapter 13 Achieving Impact
- Data Encrypted for Impact
- Encrypting Data for Impact
- Identifying Files to Encrypt
- Encrypting and Decrypting Files
- Running the Code
- Detecting File Encryption
- Finding Files of Interest
- Calculating File Entropies
- Running the Code
- Account Access Removal
- Removing Access to User Accounts
- Changing Windows Passwords
- Changing Linux Passwords
- Running the Code
- Detecting Account Access Removal
- Detecting Password Changes in Windows
- Detecting Password Changes in Linux
- Running the Code
- Summary
- Suggested Exercises
- Index
- EULA
CHAPTER 1
Fulfilling Pre-ATT&CK Objectives
Originally, MITRE Pre-ATT&CK was a stand-alone matrix within the MITRE ATT&CK framework. It detailed the various steps that an attacker could take to prepare before attempting to gain initial access to a target environment.
In October 2020, MITRE restructured the ATT&CK framework and condensed MITRE Pre-ATT&CK into two tactics of the ATT&CK matrix. The new version breaks Pre-ATT&CK into Reconnaissance and Resource Development, as shown in Figure 1.1.
Figure 1.1: MITRE Pre-ATT&CK
In this chapter, we will focus on the Reconnaissance tactic of MITRE Pre-ATT&CK. The reason is that while Resource Development can be automated, the details can vary greatly, and this stage of the attack is not visible to the defender. For example, Python could be used for implementing a domain generation algorithm (DGA) for phishing or automating the deployment of web-based services, but these apply only in certain types of attacks and can easily be implemented in other ways.
Reconnaissance, on the other hand, can benefit significantly from automation. Also, Python includes several packages that help with automating reconnaissance, such as scapy and various DNS libraries.
The MITRE Pre-ATT&CK framework includes 10 techniques for Reconnaissance. Here, we will explore the use of Python for the Active Scanning and Search Open Technical Databases techniques.
The code sample archive for this chapter can be found on the Download Code tab at https://www.wiley.com/go/pythonforcybersecurity and contains the following sample code files:
PortScan.pyHoneyScan.pyDNSExploration.pyHoneyResolver.py
Active Scanning
Network reconnaissance can be performed by either active or passive means. Active reconnaissance involves interacting with the target environment, while passive reconnaissance can involve eavesdropping on traffic or taking advantage of publicly available sources of information.
As its name suggests, the Active Scanning technique in MITRE ATT&CK is an example of Active Reconnaissance. It involves performing port or vulnerability scans against a target to determine which IP addresses are active, what services they are running, any vulnerabilities that may exist, and similar intelligence.
Scanning Networks with scapy
Nmap is the most used tool for port scanning. It implements several different types of scans and can be used to detect the versions of operating systems and services and to perform custom vulnerability scans.
In this section, we'll implement a couple of simple scans:
- SYN scan: A SYN scan sends a TCP SYN packet to a port and looks for a SYN/ACK packet in response.
- DNS scan: A DNS scan tests to see whether a DNS server is running on the target system.
To implement these scans, we'll be using the scapy library in Python. scapy makes it easy to create and send custom packets over the network and to sniff network traffic for responses.
PortScan.py
from scapy.all import * import ipaddress ports = [25,80,53,443,445,8080,8443] def SynScan(host): ans,unans = sr( IP(dst=host)/ TCP(sport=33333,dport=ports,flags="S") ,timeout=2,verbose=0) print("Open ports at %s:" % host) for (s,r,) in ans: if s[TCP].dport == r[TCP].sport and r[TCP].flags=="SA": print(s[TCP].dport) def DNSScan(host): ans,unans = sr( IP(dst=host)/ UDP(dport=53)/ DNS(rd=1,qd=DNSQR(qname="google.com")) ,timeout=2,verbose=0) if ans and ans[UDP]: print("DNS Server at %s"%host) host = input("Enter IP Address: ") try: ipaddress.ip_address(host) except: print("Invalid address") exit(-1) SynScan(host) DNSScan(host) The code file PortScan.py implements a simple SYN and DNS scan using scapy. As shown near the top of the file, the code scans some commonly used ports for listening services, including 25, 80, 53, 443, 445, 8080, and 8443.
Implementing a SYN Scan in scapy
To start, take a look at the SynScan function in the code. As shown in Figure 1.2, a SYN scan sends out a SYN packet and looks for a SYN/ACK in response. A SYN/ACK indicates an open port, while a RST/ACK or no response within the two-second timeout indicates that a port is closed.
Figure 1.2: SYN scan in Wireshark
scapy breaks a packet into layers and makes it easy to access the various packet fields at each layer. Implementing a SYN scan in scapy requires setting values at the IP and TCP layers. Necessary values include the following:
- Destination IP address: This is set to the IP address of the target system.
- Source port:
scapyuses a default port of 20, but it's best to set a high ephemeral port value instead. - Destination port:
scapyallows a list of ports to be passed to it and will create a packet for each. - TCP flags: A SYN scan requires the SYN flag to be set.
This can be accomplished with the command IP(dst=host)/TCP(dport=ports,flags="S"). Layers in scapy are specified as classes with the desired values passed as parameters. Any fields in the packet that are not specified by the user are set automatically by scapy.
After building the SYN packet, the SynScan function sends it with the sr function. Here, sr stands for send/receive, meaning that it will transmit the SYN packet and monitor for any responses. Answered SYN scan packets are stored in ans, while unanswered ones are stored in unans.
The sr function in SynScan has a timeout of two seconds. After the time has elapsed or the connection is otherwise closed, it unpacks the contents of ans to look for responses that indicate open ports.
Within ans, SynScan looks at s and r, which are the SYN packets it sent and the responses that it received. With the command s[TCP].dport, the code accesses the TCP layer of a SYN packet it sent out and extracts the destination port to compare with the source port of the received packet. If they match and the received packet has the SYN/ACK flags set, then the port is marked as open.
Performing a DNS Scan in scapy
The only difference between implementing a SYN scan in scapy and a DNS scan is the structure of the packets that the code sends out. A SYN scan is performed at the TCP layer, while a DNS query is usually sent out over UDP and includes a DNS layer.
scapy's ability to set default values for unused fields means that only a few values need to be explicitly set within the DNS request packet:
- Destination IP address: The IP address of the target system.
- UDP port number: Set to 53, which is the default for DNS.
- Recursion desired (
rd): Set this to 1. - Query: A DNSQR structure containing the desired domain (
qname).
This can all be put together in the command IP(sport=33333,dst=host)/ UDP(dport=53)/ DNS(rd=1,qd=DNSQR(qname=" google.com ")).
The DNSScan function also uses scapy's sr function to send out packets and look for responses. However, its code for checking for responses is simpler than the SYN scan. The query will receive a response only if a system is running a DNS server. If the ans variable is not empty, then the scanner has identified a DNS server.
Running the Code
After implementing the SYNScan and DNSScan functions, all that is left is the main function and running the code. PortScan.py uses Python's input function to request an IP address from the user and tests its validity with the ip_address function from the ipaddress Python library.
If the IP address is valid, then the code calls the SYNScan and DNSScan functions to produce the following output. The code must be run with Administrator/root permissions.
>python PortScan.py Enter IP Address: 8.8.8.8 Open ports at 8.8.8.8: 53 443 DNS Server at 8.8.8.8 In the previous example, the IP address points to Google's DNS server. It makes sense that this would be running both a DNS server (port 53) and a web server (port 443).
Now, try running the code with an invalid IP address.
>python PortScan.py Enter IP...
Systemvoraussetzungen
Dateiformat: ePUB
Kopierschutz: Adobe-DRM (Digital Rights Management)
Systemvoraussetzungen:
- Computer (Windows; MacOS X; Linux): Installieren Sie bereits vor dem Download die kostenlose Software Adobe Digital Editions (siehe E-Book Hilfe).
- Tablet/Smartphone (Android; iOS): Installieren Sie bereits vor dem Download die kostenlose App Adobe Digital Editions oder die App PocketBook (siehe E-Book Hilfe).
- E-Book-Reader: Bookeen, Kobo, Pocketbook, Sony, Tolino u.v.a.m. (nicht Kindle)
Das Dateiformat ePUB ist sehr gut für Romane und Sachbücher geeignet – also für „fließenden” Text ohne komplexes Layout. Bei E-Readern oder Smartphones passt sich der Zeilen- und Seitenumbruch automatisch den kleinen Displays an.
Mit Adobe-DRM wird hier ein „harter” Kopierschutz verwendet. Wenn die notwendigen Voraussetzungen nicht vorliegen, können Sie das E-Book leider nicht öffnen. Daher müssen Sie bereits vor dem Download Ihre Lese-Hardware vorbereiten.
Bitte beachten Sie: Wir empfehlen Ihnen unbedingt nach Installation der Lese-Software diese mit Ihrer persönlichen Adobe-ID zu autorisieren!
Weitere Informationen finden Sie in unserer E-Book Hilfe.