KEMBAR78
1 Introduction | PDF | Domain Name System | Transmission Control Protocol
0% found this document useful (0 votes)
20 views45 pages

1 Introduction

Uploaded by

alinshwan33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views45 pages

1 Introduction

Uploaded by

alinshwan33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Programing for Cybersecurity

Python

Dr. Fawaz Al-Ghfari


Essential Knowledge
The OSI Reference Model

Layer Description Technologies Data Unit

1 Physical USB, Bluetooth Bit

2 Data Link ARP, PPP Frame

3 Network IP Packet

4 Transport TCP Segment

5 Session X255, SCP Data

6 Presentation AFP, MIME Data

7 Application FTP, HTTP, SMTP Data


TCP/IP Model

Layer Description OSI Layer Equivalent


1 Network Access 1, 2
2 Internet 3
3 Transport 4
4 Application 5-7

TCP Handshake
SYN -> SYN-ACK -> ACK
ARP
•Resolves IP address to physical address
Phases of Hacking

1. Reconnaissance - gathering evidence about targets


2. Scanning & Enumeration - obtaining more in-depth information about
targets
3. Gaining Access - attacks are leveled in order to gain access to a system
4. Maintaining Access - items put in place to ensure future access
5. Covering Tracks - steps taken to conceal success and intrusion
1. Introduction: The "Why" of Automation in Cybersecurity
• The Cybersecurity Landscape
• Cyber threats are pervasive and constantly evolving.
• Organizations face risks of multi-million dollar attacks.
• Effective cyber risk management includes:
• Preventing malware infections
• Detecting and remediating attacks
• Ensuring compliance with security policies
• The Role of Automation
• Manual processes are insufficient for large-scale defense.
• Automation is crucial for handling vast amounts of data and responding to
threats efficiently.
• It scales defenses to protect hundreds to thousands of users.
2. Why Python for Cybersecurity?
• Popularity
• Python is a widely adopted language (e.g., ranked highly on TIOBE index).
• High probability students already have some Python knowledge.
• Easier to learn new applications within a known language.
• Ease of Use
• Relatively quick and easy to learn for beginners.
• Facilitates rapid prototyping and development of cybersecurity tools.
2. Why Python for Cybersecurity?

Power and Libraries


•Extensive collection of powerful third-party libraries.
•Simplifies complex tasks (e.g., scapy for network traffic
manipulation, dnslib for DNS).
•Avoids the need to "reinvent the wheel" for common
functionalities.
3. Understanding the MITRE ATT&CK Framework
• What is MITRE ATT&CK?
• A globally accessible knowledge base of adversary tactics and techniques.
• Based on real-world observations of cyberattacks.
• Provides a common language and framework for understanding and
discussing cyber threats.
•.
3. Understanding the MITRE ATT&CK Framework
• Hierarchy of the Framework
• Tactics (Goals): Top-level objectives an attacker aims to achieve (e.g.,
Reconnaissance, Initial Access, Execution, Persistence).
• Techniques (Methods): Specific ways to achieve those goals (e.g., Brute
Force, Network Sniffing).
• Sub-techniques: More detailed descriptions of techniques.
3. Understanding the MITRE ATT&CK Framework
• Why is MITRE ATT&CK Important?
• Provides a clear framework for offensive and defensive cybersecurity tasks.
• Helps map Python applications to specific attack and defense scenarios.
• Offers a wealth of additional resources and in-depth information on each
technique.
• Enables structured learning and application of cybersecurity concepts.
4. Pre-ATT&CK Objectives: Reconnaissance and Resource
Development
Overview of Pre-ATT&CK (Fulfilling Pre-ATT&CK Objectives)
• Originally a standalone matrix, now integrated into the main ATT&CK
framework.
• Focuses on actions attackers take before gaining initial access.
• Comprises two main tactics:
• Reconnaissance: Gathering information about the target.
• Resource Development: Establishing resources to support operations.
• Focus on Reconnaissance
• Highly automatable, making Python particularly useful.
• Involves discovering intelligence about the target environment.
• Techniques include Active Scanning and Search Open Technical Databases.
5. Active Scanning: Offensive & Defensive Applications
• What is Active Scanning? (Active Scanning)
• Direct interaction with the target network.
• Aims to identify active IP addresses, running services, and potential
vulnerabilities.
• Examples: Port scans, vulnerability scans.
Offensive Application: Port Scanning with Python (using scapy)
•SYN Scan: Sends TCP SYN packets; looks for SYN/ACK responses
(open ports).
•DNS Scan: Tests for running DNS servers on target systems.
•scapy Library: Simplifies packet creation, sending, and sniffing at
various network layers.
•Example: IP(dst=host)/TCP(dport=ports, flags="S")
Port Scanning

• Port scanning allows a hacker to determine what all services


are running on the system.
• Identification of vulnerable or insecure services let the
hacker to exploit unauthorized access.
TCP three way handshake connection establishment and
termination
Connection Establishment: SYN, SYN-ACK, ACK
Connection Termination: FIN, ACK-FIN, ACK
TCP Scan Types
1. Ping Scan
2. SYN Scan
3. Full Scan
4. ACK Scan
5. XMAS SCAN
6. UDP Basics
TCP Flag Types
Flag Name Function
SYN Synchronize Set during initial communication. Negotiating of
parameters and sequence numbers
ACK Acknowledgment Set as an acknowledgement to the SYN flag. Always set
after initial SYN
RST Reset Forces the termination of a connection (in both
directions)
FIN Finish Ordered close to communications
PSH Push Forces the delivery of data without concern for buffering
URG Urgent Data inside is being sent out of band. Example is
cancelling a message
5. Active Scanning: Offensive & Defensive Applications
Offensive Application: Port Scanning with Python (using scapy)
•SYN Scan: Sends TCP SYN packets; looks for SYN/ACK responses
(open ports).
•DNS Scan: Tests for running DNS servers on target systems.
•scapy Library: Simplifies packet creation, sending, and sniffing at
various network layers.
•Example: IP(dst=host)/TCP(dport=ports, flags="S")

•In the scapy library, the / (slash) operator is used to layer


protocols on top of each other to build a packet.
•An IP layer is created with the destination host (dst=host).A TCP layer is then
placed on top of that IP layer, with specified destination ports (dport=ports)
and the SYN flag set (flags="S").
5. Active Scanning: Offensive & Defensive Applications
Implementing a SYN Scan in scapy
•Detailed explanation of constructing SYN packets using scapy
(IP(dst=host)/TCP(dport=ports, flags="S")).
•How sr function sends and receives packets.
•Analyzing responses for open ports based on SYN/ACK flags.
Performing a DNS Scan in scapy
•Differences in packet structure (UDP, DNS layer).
•Explicitly setting values like Destination IP, UDP port 53,
Recursion desired (rd=1), and Query
(DNSQR(qname="google.com")).
•Simpler response check: presence of a response indicates a
DNS server.
5. Active Scanning: Offensive & Defensive Applications

Running the Code

•Demonstrates PortScan.py usage.


•Input validation for IP addresses using ipaddress library.
•Example output showing open ports and DNS server detection.
5. Active Scanning: Offensive & Defensive Applications
Network Scanning for Defenders
•Objective: Mislead attackers about open/closed ports.
•Techniques:
•Making legitimately closed ports appear open (e.g., sending
SYN/ACK for honeypot ports).
•Making legitimately open ports appear closed (e.g., sending RST
for valid ports from "blocked" IPs).
Monitoring Traffic with scapy
•scapy.sniff(): Monitors network traffic for specific patterns.
•Berkeley Packet Filter (BPF) syntax: Used to define filters (e.g.,
"dst host "+ip+" and tcp").
•prn argument passes matching packets to a handler function
(analyzePackets).
5. Active Scanning: Offensive & Defensive Applications
Building Deceptive Responses
•Crafting custom packets to mislead scanners.
•Essential fields to match: MAC addresses, IP addresses, Ports (reversed).
•ACK number: Set to sequence number + 1 from the request for TCP
conversations.
•Handling IPv4 vs. IPv6 requests using haslayer function.
•Setting TCP flags ("SA" for SYN/ACK, "RA" for RST/ACK) based on deception
logic.
•Using sendp to send layer 2 packets.
Running the Code
•Demonstrates HoneyScan.py in action against PortScan.py.
•Shows how HoneyScan can make specific ports appear open (honeypots) even if
they are not.
•Discusses race conditions and the ideal deployment of HoneyScan (in-line with
packet filtering).
6. Search Open Technical Databases: Offensive & Defensive
Applications
What are Open Technical Databases? (Search Open Technical
Databases)
•Publicly available sources of information on the Internet.
•Designed for public access and use (e.g., DNS, WHOIS records).
•Can inadvertently reveal valuable intelligence to attackers.
Offensive Application: DNS Exploration with Python
Offensive DNS Exploration
•DNS as a "Phonebook": Maps domain names to IP addresses.
•Purpose: Identify an organization's network architecture and system
purposes (e.g., mail.example.com).
•Tools: Python dns.resolver and socket libraries.
6. Search Open Technical Databases: Offensive & Defensive
Applications
DNS Footprinting
• Ports
• Name lookup - UDP 53
• Zone transfer - TCP 53
• Zone transfer replicates all records
• Name resolvers answer requests
• Authoritative Servers hold all records for a namespace
• DNS Record Types
6. Search Open Technical Databases: Offensive & Defensive
Applications
DNS footprinting is a technique used to gather information about a domain's DNS (Domain
Name System) infrastructure. Here's a breakdown of the components:
Ports
Name lookup - UDP 53:
DNS queries and responses typically use UDP port 53. When you look up a domain name, your computer
sends a query to a DNS server using UDP port 53.
Zone transfer - TCP 53:
DNS zone transfers use TCP port 53. A zone transfer is a process of replicating DNS records from a
primary DNS server to a secondary DNS server to ensure consistency.
Zone Transfer
Zone transfer replicates all records:
During a zone transfer, the secondary DNS server requests a copy of all the DNS records from the
primary DNS server. This process is used to synchronize DNS data between servers.
DNS Record Types
Name Description Purpose
SRV Service Points to a specific service
SOA Start of Authority Indicates the authoritative NS for a
namespace
PTR Pointer Maps an IP to a hostname
NS Nameserver Lists the nameservers for a namespace
MX Mail Exchange Lists email servers
CNAME Canonical Name Maps a name to an A reccord
A Address Maps an hostname to an IP address
• DNS Poisoning - changes cache on a machine to redirect requests to a malicious server
• DNSSEC (Domain Name System Security Extensions) - helps prevent DNS poisoning by
encrypting records
DNS Record Types
• DNS Poisoning - DNS poisoning occurs when an attacker corrupts the DNS cache by
injecting false records, redirecting traffic to malicious sites. By using digital signatures,
• DNSSEC (Domain Name System Security Extensions) -
• is a suite of security protocols that adds an extra layer of security to the Domain Name System (DNS).
• It aims to protect the integrity and authenticity of DNS data, helping to prevent attacks such as DNS
poisoning or cache poisoning.
• How DNSSEC Works
• Cryptographic Signatures
• Verification
• Preventing DNS Poisoning:
SOA Start of Authority Indicates the authoritative NS for a
namespace

• SOA (A start of authority record) Record Fields


o Source Host - hostname of the primary DNS
o Contact Email - email for the person responsible for the zone file
o Serial Number - revision number that increments with each change
o Refresh Time - time in which an update should occur
o Retry Time - time that a NS should wait on a failure
o Expire Time - time in which a zone transfer is allowed to complete
o TTL - minimum TTL for records within the zone
6. Search Open Technical Databases: Offensive & Defensive
Applications
IP Address Management
• ARIN - North America
• APNIC - Asia Pacific
• RIPE - Europe, Middle East
• LACNIC - Latin America
• AfriNIC - Africa
6. Search Open Technical Databases: Offensive & Defensive
Applications
Whois - obtains registration information for the domain
Nslookup - performs DNS queries
nslookup [ - options ] [ hostname ]
interactive zone transfer
nslookup
server
set type = any [set type = any example.com to retrieve
all records for example.com.]
ls -d domainname.com
Dig - unix-based command like nslookup
dig @server name type
WHOIS
WHOIS is a protocol that allows you to query databases containing information about
domain name registrations. When an organization registers a domain, they provide details
that are stored in a WHOIS database.
What is WHOIS?
WHOIS provides the ability to look up information about the owner of a domain name,
including:
•Registrant Name: The individual or organization that owns the domain.
•Registrant Organization: The company or organization associated with the domain.
•Registrant Contact Information: This may include an email address, phone number, and
postal address.
•Administrative Contact: Information about the administrative contact for the domain.
•Technical Contact: Information about the technical contact for the domain.
•Domain Registration Dates: The creation date, expiry date, and last updated date.
•Domain Name Servers: The DNS servers associated with the domain.
How to Use WHOIS?
WHOIS
1.Using Online Tools:
1. There are many online WHOIS lookup tools available. You simply enter the domain name you want to
look up, and the tool will return the WHOIS information.
2.Using Command Line:
1. On many operating systems, you can use the command line to perform a WHOIS query. For example:
whois example.com
1. Domain Name: example.com
2. Registrar: Example Registrar Inc.
3. Registrant Name: John Doe
4. Registrant Organization: Example Corp
5. Registrant Email: john.doe@example.com
6. Creation Date: 2024-11-25
7. Expiration Date: 2054-11-25
8. Name Server: ns1.example.com
9. Name Server: ns2.example.com
Nslookup
nslookup is a command-line tool used for querying the Domain Name System (DNS) to
obtain domain name or IP address mapping information.
It's useful for diagnosing DNS issues and ensuring that DNS records are correctly
configured.
Resolve Domain Names to IP Addresses: nslookup example.com
Resolve IP Addresses to Hostnames: nslookup 192.0.2.1
Components of nslookup Output:
❑ Server: Shows the DNS server that was used to resolve the query.
❑ Address: Displays the IP address of the DNS server used.
❑ Non-authoritative answer: Indicates that the response is from a DNS server that is
not the authoritative source for the domain.
❑ Name: Shows the domain name that corresponds to the IP address.
❑ Address: Displays the resolved IP address for the given domain name.
RIR’s (Regional Internet Registries)
❑ Regional Internet Registries (RIRs) are organizations responsible for managing and
distributing Internet number resources (such as IP addresses and Autonomous System Numbers)
within specific regions of the world. There are 5 RIRs, each serving a different geographic area:
1. AFRINIC (African Network Information Centre):
2. APNIC (Asia-Pacific Network Information Centre):
3. ARIN (American Registry for Internet Numbers):
4. LACNIC (Latin American and Caribbean Internet Address Registry):
5. RIPE NCC (Réseaux IP Européens Network Coordination Centre):->Yemen
• These RIRs work together under the coordination of the Number Resource Organization (NRO) to
ensure the efficient and fair distribution of Internet number resources globally.
RIR’s (Regional Internet Registries)
6. Search Open Technical Databases: Offensive & Defensive
Applications
Searching DNS Records
•Combines a list of common hosts (e.g., dns_search.txt) with a base
domain.
•Iterates through hosts and performs DNS lookups using DNSRequest
function.
•Optionally appends numbers (0-10) to hostnames to find variations
(e.g., ns1.example.com).
Performing a DNS Lookup
•Uses dns.resolver.Resolver.resolve() to query DNS servers.
•Stores results in a dictionary (domains) mapping hostnames to IP
addresses. (forword DNS)
•Calls ReverseDNS on discovered IP addresses to find associated
domains.
6. Search Open Technical Databases: Offensive & Defensive
Applications
Reverse DNS Lookup
•Converts IP addresses back to associated domain names.
•Uses socket.gethostbyaddr().
•Returns hostname and aliases.
•Recursively calls DNSRequest for newly discovered domains.
Running the Code
•Demonstrates DNSExploration.py usage and truncated output.
•Shows successful identification of active hostnames (e.g.,
www.google.com, mail.google.com).
•Highlights discovery of unique, related domains (e.g., 1e100.net)
6. Search Open Technical Databases: Offensive & Defensive
Applications

Defensive Countermeasures: DNS Deception with Python

DNS Exploration for Defenders


•Objective: Control the information exposed via DNS.
•Techniques:
•Selective Exposure: Only publish DNS entries for publicly intended
systems.
•Active Deception (Honeypot DNS):
•Respond with correct IPs for legitimate subdomains.
•Redirect queries for other subdomains to a honeypot IP address.
6. Search Open Technical Databases: Offensive & Defensive
Applications: Defensive Countermeasures: DNS Deception with Python
Handling DNS Requests
•Uses Python dnslib to implement a simple DNS server.
•DNSServer class takes a Resolver class, which processes DNS requests.
•HoneyResolver class handles queries via its resolve function.
•Defines valid subdomains and a honeypot IP.
•Uses request.q.qname.stripSuffix() to extract subdomain for comparison.
Building a DNS Response
•DNSRecord.reply() builds a skeleton response.
•add_answer function adds an RR (Resource Record) instance.
•Sets rname (requested domain), rtype (A record), rclass (Internet namespace),
ttl (cache duration).
•rdata contains the actual IP address (either legitimate or honeypot).
6. Search Open Technical Databases: Offensive & Defensive
Applications
Defensive Countermeasures: DNS Deception with Python

Running the Code:

• Explains how to configure DNSExploration.py to use


HoneyResolver as its DNS server.
• Shows sample output demonstrating how HoneyResolver redirects
unknown subdomains to the honeypot IP, while legitimate ones
resolve correctly.
7. Setting Up Your Anaconda & Python Environment
Virtual Environments
•Recommended for managing dependencies and avoiding conflicts.
Anaconda Installation Guide for Windows

Step 1: Download Anaconda Installer


1.Open your web browser.
2.Go to the official Anaconda website:
👉 https://www.anaconda.com/products/distribution
3.You can install mini Anaconda (35M)
3.Click on "Download" under the Windows section.
4.Choose the 64-bit Graphical Installer (Recommended).
5.Wait for the .exe file to finish downloading.
7. Setting Up Your Anaconda & Python Environment
Step 2: Run the Installer
1.Double-click the downloaded .exe file.
2.If prompted by User Account Control, click Yes.
3.On the setup screen, click Next.
4.Read and accept the license agreement > click Next.
5.Choose "Just Me" unless you're installing for all users > click Next.
6.Choose the installation location (default is fine) > click Next.
7.IMPORTANT:
✔ Check “Add Anaconda to my PATH environment variable”
(optional but helpful).
✔ Check “Register Anaconda as my default Python”.
Then click Install.
8.Wait while Anaconda installs (may take several minutes).
7. Setting Up Your Anaconda & Python Environment
Step 3: Verify Installation
1.Click Finish after installation is complete.
2.Open Start Menu → search for Anaconda Navigator or Anaconda
Prompt.
3.Click to open and verify it starts successfully.

step 4: Test Using Anaconda Prompt


Open Anaconda Prompt from the Start Menu.
Type:

conda --version
If it shows something like conda 24.x.x, the installation was
successful!
7. Setting Up Your Anaconda & Python Environment
Create a New Environment
To create a new Python environment (for example, Python 3.10):

conda create -n myenv python=3.10

Activate it by type :

conda activate myenv


Python's Impact on Cybersecurity

• Python is an ideal choice for cybersecurity automation due to its


popularity, ease of use, and powerful libraries.
• It enables both offensive (reconnaissance, exploitation) and defensive
(monitoring, deception) capabilities.
• Understanding and applying Python within frameworks like MITRE ATT&CK
provides a structured approach to addressing real-world cybersecurity
challenges.
• Hands-on practice with code samples is crucial for mastering these
concepts.
Python's Impact on Cybersecurity
suggested Exercises
1.The SYNScan function in PortScan.py currently checks only if a port is open,
based on if it returns a SYN/ACK packet. Modify the code to differentiate between
closed ports (which return a RST) and ports filtered by a firewall (which return
nothing).
2.Currently, PortScan.py implements SYN and DNS scans. Modify it to include
additional types of scans, such as ACK and XMAS scans.
3.Revise DNSExploration.py to group results by IP address rather than domain
name. This helps to identify systems with multiple functions within an organization.
4.Currently HoneyResolver.py makes it easy to differentiate real and fake results
because all fake results resolve to the same IP address. Modify the code to only
resolve certain fake subdomains with unique IP addresses assigned to each.
5.HoneyResolver.py only sends responses containing A records, which are
inappropriate for some requests. Extend the code to send the correct type of
record for each request.

You might also like