Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 11 of 11
Practice & Quiz - Network Security & Reconnaissance
Test your network security knowledge: TCP/IP packet analysis, Nmap reconnaissance, DNS attacks, and ARP poisoning detection with a practical Python packet analysis exercise and 5 quiz questions.
Practical Exercise - Network Packet Analysis with Scapy
from scapy.all import (
Ether, IP, TCP, UDP, ICMP, ARP,
sniff, send, sendp, wrpcap, rdpcap,
get_if_list, conf,
)
import socket, struct, ipaddress
# ─── 1. Build and inspect custom packets ─────────────────────
# Craft a TCP SYN packet (first step of 3-way handshake)
syn_packet = (
IP(src='192.168.1.100', dst='192.168.1.1') /
TCP(sport=12345, dport=80, flags='S', seq=1000)
)
print('=== TCP SYN Packet ===')
syn_packet.show()
print(f'Hex dump: {bytes(syn_packet).hex()}')
# ─── 2. Detect port scan patterns in packet stream ────────────
# A SYN scan sends SYN to many ports quickly - signature of Nmap -sS
def analyze_packets(packets) -> dict:
"""Detect common attack patterns in a packet capture."""
from collections import defaultdict
syn_count = defaultdict(set) # src_ip → set of destination ports
arp_table = {} # ip → mac mapping
arp_conflicts= [] # detect ARP poisoning
dns_queries = []
for pkt in packets:
# Port scan detection: SYN-only packets to multiple ports
if TCP in pkt and pkt[TCP].flags == 0x002: # SYN flag only
src = pkt[IP].src if IP in pkt else 'unknown'
syn_count[src].add(pkt[TCP].dport)
# ARP poisoning detection: same IP, different MAC
if ARP in pkt and pkt[ARP].op == 2: # ARP reply
ip, mac = pkt[ARP].psrc, pkt[ARP].hwsrc
if ip in arp_table and arp_table[ip] != mac:
arp_conflicts.append({'ip': ip, 'old_mac': arp_table[ip], 'new_mac': mac})
print(f'🚨 ARP SPOOFING DETECTED: {ip} changed {arp_table[ip]} → {mac}')
arp_table[ip] = mac
# DNS query logging
if UDP in pkt and pkt[UDP].dport == 53:
dns_queries.append({'src': pkt[IP].src if IP in pkt else '?', 'raw': bytes(pkt)})
# Port scan alert
results = {'arp_conflicts': arp_conflicts, 'dns_queries': len(dns_queries)}
for src_ip, ports in syn_count.items():
if len(ports) > 10: # threshold: >10 unique ports = port scan
print(f'🚨 PORT SCAN: {src_ip} scanned {len(ports)} ports: {sorted(ports)[:10]}...')
results[f'scan_{src_ip}'] = sorted(ports)
return results
# ─── 3. Nmap-equivalent TCP connect scan (educational) ────────
import socket, concurrent.futures
def tcp_connect_scan(target: str, ports: list[int], timeout: float = 0.5) -> dict:
"""TCP connect scan - sends full handshake, detectable in logs."""
results = {'open': [], 'closed': [], 'filtered': []}
def check_port(port: int) -> tuple:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
try:
s.connect((target, port))
# Try banner grab
try:
s.send(b'HEAD / HTTP/1.0\r\n\r\n')
banner = s.recv(1024).decode(errors='ignore').strip()[:80]
except:
banner = ''
return port, 'open', banner
except ConnectionRefusedError:
return port, 'closed', ''
except socket.timeout:
return port, 'filtered', ''
common_ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 3306, 5432, 6379, 8080, 8443]
print(f'Scanning {target}...')
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
futures = {executor.submit(check_port, p): p for p in (ports or common_ports)}
for future in concurrent.futures.as_completed(futures):
port, state, banner = future.result()
results[state].append(port)
if state == 'open':
print(f' Port {port}/tcp OPEN {banner}')
print(f'Scan complete: {len(results["open"])} open, {len(results["closed"])} closed, {len(results["filtered"])} filtered')
return results
# ─── Example: scan localhost (safe, educational) ──────────────
# tcp_connect_scan('127.0.0.1', [22, 80, 443, 8080])Module Quiz
What is the difference between a TCP SYN scan and a TCP connect scan in port scanning?
Tip
Tip
Practice Practice Quiz Network Security Reconnaissance in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Network Security Reconnaissance from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Network Security Reconnaissance is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?