Tuesday, November 24, 2026

Computer Network - Refresher

IIT Bhubaneswar · M.Tech Cyber Security

Networks &
System Security

Complete Course Notes

Lectures 01–15 with Laboratory Sessions 1–7 integrated

November 2026

PART ONE
Networking Foundations
Chapter 1

Lecture 01 — Introduction: networks, IPC, OSI model & layer-wise attacks

Computer Network:

A Network is a group of two or more connected devices that communicate and share data, resources or services.

Inter-Process Communication:

Inter-Process Communication is the exchange of data and signals between two or more independent programs (processes) that run in separate, isolated memory spaces isolated by the operating system.

Examples

Print SpoolerWhen you click "Print" in Microsoft Word, Word sends the document data to a completely separate system program called the Print Spooler, which manages the printer queue.
Database AccessA web application (like WordPress) talking to a separate database management system (like MySQL) to fetch user profile data.
MicroservicesA ride-sharing app where the GPS tracking system constantly sends location updates to a separate payment processing system.

Intra-Process Communication:

Intra-Process Communication is the exchange of data and signals between different threads or components execution units within the same single program, all sharing the exact same memory space.

Examples

Web Browser TabsIn a modern web browser, when you download a file in one tab, a separate background thread inside that same browser updates the visual "Downloads" progress bar in the top corner.
Video Game LogicInside a single running game, the background music thread slows down or speeds up based on signals it receives from the player movement thread (e.g., entering a boss fight).
Text Editor Auto-SaveWhile you are actively typing text in an editor, a silent background thread inside the same application periodically reads your text and saves it to a backup file.

Why Network & Systems Security:

Protecting computers, servers and networks from unauthorized access, attacks and damage.

Domain Name System:

DNS is the phonebook of the internet that translates human-readable web addresses into computer-readable IP addresses.

Open Systems Interconnection (OSI) Layers:

Layer - 7 Application ̅ \

Layer - 6 Presentation >User's Convenience

Layer - 5 Session _/

Layer - 4 Transport ̅ \

Layer - 3 Network _/Software

Layer - 2 Data Link ̅ \

Layer - 1 Presentation _/Hardware

Why Layering:

The OSI model uses layering because it perfectly applies fundamental computer science principles to solve complex networking problems. By breaking the massive job of network communication into seven distinct layers, it makes the entire system manageable.

Here are the four principles explaining why the OSI model uses layering:

1.Divide and Conquer

The ConceptBreaking a complex, overwhelming problem into smaller, highly manageable pieces.
In OSI LayeringInstead of a single piece of software handling everything from the physical wires to the user interface, the job is split into seven distinct tasks.
The BenefitEngineers can focus deeply on solving one specific problem at a time. For example, the creators of a web browser only need to worry about the Application layer (HTTP), while the hardware team only worries about the Physical layer (cables and signals).

2.Encapsulation

The ConceptPackaging data with necessary control information at each step while hiding the internal details of that package.
In OSI LayeringAs data travels down the stack, each layer wraps the data from the layer above it with its own header and trailer (adding IP addresses at the Network layer, MAC addresses at the Data Link layer, etc.).
The BenefitIt prevents data corruption and ensures proper formatting. A layer only needs to read its own specific wrapper to know what to do, without needing to understand the actual payload inside.

3.Abstraction

The ConceptHiding background details so you only have to focus on the high-level logic.
In OSI LayeringEach layer provides a service to the layer above it without that upper layer needing to know how the service is executed.
The BenefitInteroperability and future-proofing. Your web browser does not care if your computer is connected via Wi-Fi, Ethernet, or 5G cellular data. The Physical layer abstracts those details away, meaning you can upgrade your hardware without rewriting your software.

4.Testing & Troubleshooting

The ConceptIsolating components to easily verify correctness and find faults.
In OSI LayeringBecause the layers have strict boundaries, you can test and troubleshoot network issues systematically, either from the bottom-up or top-down.
The BenefitRapid pinpointing of errors. If you cannot connect to a website, a technician can check if the physical cable is plugged in (Layer 1), then if your router gave you an IP address (Layer 3), and finally if the website's port is open (Layer 4). You fix the specific layer rather than tearing down the whole network.

Client Server

7 Application 7 Application

⬇ ⬆

6 Presentation 6 Presentation

⬇ ⬆

5 Session 5 Session

⬇ ⬆

4 Transport 4 Transport

⬇ ⬆

3 Network 3 Network

⬇ ⬆

2 Data Link 2 Data Link

⬇ ⬆

1  Presentation    -------------➡    1  Presentation

The Complete OSI 7-LAYER Reference Model with Security

The Application Layer (Layer 7) - OSI Model Reference

1. Overview & Purpose

The Application Layer is the seventh and highest layer of the Open Systems Interconnection (OSI) model. It serves as the direct interface between the end-user applications and the underlying network architecture. Unlike other layers that focus on moving data across cables and routers, Layer 7 focuses entirely on the software applications that need to communicate.

Key Characteristics:

1.It is the only layer that interacts directly with user software applications.

2.It does not provide services to any other OSI layer; instead, it relies on the services of the Presentation Layer (Layer 6) directly below it.

3.It determines the identity and availability of communication partners for an application with data to transmit.

2. Core Functions

The Application Layer handles high-level network services, which include:

Network Virtual TerminalAllows a user to log into a remote host by creating a software emulation of a terminal at the remote site.
File Transfer, Access, and Management (FTAM)Enables users to access, retrieve, and manage files on a remote computer.
Electronic Mail ServicesProvides the basis for forwarding, storing, and handling emails.
Directory ServicesProvides distributed database sources and access for global information about various objects and services.
Resource SharingHandles the advertising and sharing of local resources (like printers or drives) over a network.

3. Primary Protocols

Layer 7 relies on a robust suite of protocols to execute specific network tasks:

1.HTTP / HTTPS (Hypertext Transfer Protocol / Secure)

a)Purpose: Governs communication between web browsers and web servers.

b)Usage: Fetching HTML documents, images, and API data.

2.DNS (Domain Name System)

a)Purpose: Translates human-readable domain names into IP addresses.

b)Usage: Resolving "example.com" into a machine-readable IP like 192.0.2.1.

3.SMTP / IMAP / POP3 (Email Protocols)

a)Purpose: Standardize how emails are sent, stored, and retrieved.

b)Usage: Moving email text and attachments across mail servers.

4.FTP / SFTP (File Transfer Protocol / Secure)

a)Purpose: Used for transferring files between a client and a server.

b)Usage: Uploading website files or downloading large archives.

5.DHCP (Dynamic Host Configuration Protocol)

a)Purpose: Automatically assigns IP addresses and network configurations to devices on a network.

b)Usage: Allowing a laptop to immediately connect to a Wi-Fi network.

6.SSH / Telnet (Secure Shell)

a)Purpose: Enables secure or unsecure remote command-line access to devices.

b)Usage: Remotely managing network switches, firewalls, and Linux servers.

4. User Interaction vs. Application Layer

A common misconception is that software applications themselves (like Google Chrome, Microsoft Outlook, or Discord) exist inside the Application Layer.

1.The Software: Sits above the OSI model.

2.The Application Layer: Contains the network protocols built into that software.

For example, when you type a URL into Google Chrome, Chrome uses the HTTP/HTTPS protocol (which lives in Layer 7) to format the request and send it down the network stack.

5. Challenges & Security (Layer 7 Attacks)

Because the Application Layer sits closest to the user and handles complex logic, it is a frequent target for cyberattacks:

HTTP Floods (Layer 7 DDoS)Overwhelming a web server with massive volumes of seemingly legitimate HTTP requests until it crashes.
SQL Injection (SQLi)Exploiting vulnerabilities in application code to inject malicious database commands.
Cross-Site Scripting (XSS)Injecting malicious scripts into trusted websites to run on an end-user's browser.

Mitigation: Layer 7 security requires specialized tools like Web Application Firewalls (WAFs) and deep packet inspection, as standard network firewalls operating at Layer 3 or 4 cannot read application-level traffic logic.

The Presentation Layer (Layer 6) - OSI Model Reference

1. Overview & Purpose

The Presentation Layer is the sixth layer of the Open Systems Interconnection (OSI) model. It acts as the network's data translator, ensuring that the information sent by the Application Layer (Layer 7) of one system can be properly read by the Application Layer of another. It manages the syntax and semantics of the data being transmitted.

Key Characteristics:

1.Often referred to as the "Syntax Layer" because it establishes standard rules for data structure.

2.Converts abstract, software-specific data into a universal network format and vice versa.

3.Handles data encryption, decryption, compression, and decompression before handing it off to adjacent layers.

2. Core Functions

The Presentation Layer handles formatting and structural services, which include:

Data TranslationConverts different data representations (e.g., translating EBCDIC to ASCII or managing complex character sets like UTF-8 or UTF-16).
Encryption & DecryptionProtects data by converting it into a secure, unreadable format (ciphertext) for transmission, and reverting it back to plain text upon arrival.
Data CompressionReduces the overall size of data streams to minimize network bandwidth and optimize transmission speeds.
SerializationConverts data structures or object states into a format that can be safely stored or transmitted across the network.

3. Primary Data Formats & Architectures

Layer 6 focuses on standardizing data formats rather than traditional transport protocols:

1.Cryptographic Frameworks (SSL / TLS)

a)Purpose: Secures web, email, and connection streams via cryptography.

b)Usage: Serving as the foundational handshake for secure data exchange.

2.Text and Structured Data (JSON / XML / ASN.1)

a)Purpose: Defines structured data rules so different operating systems can interoperate.

b)Usage: Exchanging API responses, configuration files, and software messages.

3.Multimedia Encoding (JPEG / PNG / GIF / MP3 / MP4)

a)Purpose: Standardizes file layouts so any machine can view images or play media.

b)Usage: Compressing raw sensory streams into universal, highly efficient files.

4. Implementation vs. the OSI Ideal

In theoretical OSI architecture, the Presentation Layer is explicitly separate. However, in practical internet implementations (like the modern TCP/IP model):

1.The Merging: Layer 6 functionality is usually absorbed into the Application Layer.

2.The Reality: Web browsers and applications handle their own encryption (like HTTPS/TLS) and media decoding directly, rather than relying on a separate operating system network layer to do it for them.

5. Challenges & Security (Layer 6 Attacks)

Because Layer 6 is responsible for translating data syntax and parsing complex encryption handshakes, it is highly vulnerable to logic exploits:

SSL/TLS Downgrade AttacksForcing a secure browser connection to fall back to outdated, vulnerable encryption standards to intercept or alter data.
Malformed Data ExploitsFlooding a system with corrupt JSON, XML, or image headers to exploit bugs in parsing software, leading to buffer overflows.
XML External Entity (XXE) InjectionManipulating weak XML parsers to expose internal system files or trigger remote service disruptions.

Mitigation: Enforce strict modern TLS policies (disabling deprecated TLS 1.0/1.1), employ robust input sanitization libraries, and keep system parsing dependencies continually updated.

The Session Layer (Layer 5) - OSI Model Reference

1. Overview & Purpose

The Session Layer is the fifth layer of the Open Systems Interconnection (OSI) model. It is responsible for establishing, managing, synchronizing, and terminating communication sessions between applications running on different host devices. It acts as the coordinator of the dialogue, ensuring that data streams are kept organized, distinct, and properly sequenced.

Key Characteristics:

1.Acts as the "network dialogue manager," setting up the rules for interaction.

2.Provides the mechanisms needed to recover from unexpected connection drops.

3.Manages tokens to ensure that two systems do not attempt to execute the same critical action simultaneously.

2. Core Functions

The Session Layer handles session coordination services, which include:

•Session Establishment, Maintenance, and Termination: Opens a formal connection channel between hosts, monitors its active state, and closes it gracefully to prevent resource leaks.

Dialogue ControlRegulates how systems talk to each other by determining the transmission mode—either Simplex (one-way), Half-Duplex (alternating), or Full-Duplex (simultaneous two-way).
Synchronization & CheckpointingInserts virtual markers into long data streams. If a network failure occurs midway, transmission can resume from the last known checkpoint instead of restarting from the beginning.
Token ManagementPrevents collision of operations by assigning logical tokens for specific actions (e.g., ensuring only one machine prints or modifies a shared database at a time).

3. Primary Protocols

Layer 5 implements protocols that focus on application connection tracking and remote communication requests:

1.RPC (Remote Procedure Call)

a)Purpose: Allows a program on one computer to execute code on a remote server as if it were running locally.

b)Usage: Powering distributed computing, microservices, and database queries.

2.NetBIOS (Network Basic Input/Output System)

a)Purpose: Provides services related to the session layer for applications on local networks to communicate.

b)Usage: Legacy file and printer sharing in Windows networking environments.

3.SOCKS (Sockets Secure Protocol)

a)Purpose: Routes network packets between clients and servers through a proxy server at the session level.

b)Usage: Bypassing firewalls, administrative blocks, or managing identity anonymity.

4.PPTP (Point-to-Point Tunneling Protocol)

a)Purpose: Creates a secure tunnel to encapsulate data sessions.

b)Usage: Forming the connection framework for early Virtual Private Networks (VPNs).

4. Session State vs. the Modern WEB

In the theoretical OSI model, the Session Layer is explicitly separate. However, just like Layer 6, modern internet architectures (TCP/IP) absorb Layer 5 jobs:

1.The TCP/IP View: The modern network layer stack treats the Session Layer as part of the Application Layer.

2.Web Session Handling: Modern web applications do not use standard OSI Layer 5 protocols to track states. Instead, web servers and browsers use HTTP Cookies, JSON Web Tokens (JWTs), and database-backed session IDs managed directly by the software code.

5. Challenges & Security (Layer 5 Attacks)

Because the Session Layer handles the state and authorization of an active communication channel, vulnerabilities here usually result in identity impersonation:

Session Hijacking (Sidejacking)Intercepting a user's active session token or cookie over an unencrypted network to steal their identity without needing their password.
Session FixationForcing a victim to authenticate using a pre-determined, known session ID, allowing the attacker to seamlessly take over the account once the victim logs in.
RPC Injection / ExploitsExploiting flaws in Remote Procedure Call services to execute unauthorized commands or crash the server hosting the session.

Mitigation: Generate complex, cryptographically secure session identifiers, strictly enforce HTTPS to encrypt active tokens, use Secure and HttpOnly cookie flags, and implement short session timeout durations.

The Transport Layer (Layer 4) - OSI Model Reference

1. Overview & Purpose

The Transport Layer is the fourth layer of the Open Systems Interconnection (OSI) model. It serves as the crucial bridge between the upper, software-oriented layers (5, 6, and 7) and the lower, hardware-oriented layers (1, 2, and 3). Its primary purpose is to manage end-to-end communication, ensuring that data is delivered accurately, efficiently, and in the correct sequence from the source host to the destination host.

Key Characteristics:

1.It is the first layer that handles complete, end-to-end data delivery across the entire network path rather than node-to-node links.

2.Uses logical addressing known as "Ports" to track and distinguish multiple different network conversations occurring on the same machine.

3.The basic unit of data at this layer is called a "Segment" (when using TCP) or a "Datagram" (when using UDP).

2. Core Functions

The Transport Layer acts as the quality-control supervisor for data transmission:

Segmentation & ReassemblyBreaks large blocks of application data into smaller, manageable chunks (segments) for network transmission, and systematically reassembles them in the correct order at the receiving end.
Connection ControlOffers two distinct methods of delivery: Connection-Oriented (guaranteed, stable transmission) and Connectionless (fast, unverified transmission).
Flow ControlManages the rate of data transfer between devices. If a high-speed server sends data faster than a slow receiver can process it, Layer 4 signals the sender to slow down to prevent data drops.
Error Control & ReliabilityUses sequence numbers and acknowledgements to verify that every segment arrives intact. If a segment is lost or corrupted in transit, Layer 4 automatically requests a retransmission.

3. Primary Protocols

Layer 4 is dominated by two foundational protocols that power nearly all internet traffic:

1.TCP (Transmission Control Protocol)

NatureConnection-oriented and highly reliable.
MechanicsEstablishes a session using a "3-Way Handshake" (SYN, SYN-ACK, ACK), assigns sequence numbers to packets, and guarantees error-free, orderly delivery.
UsageWeb browsing (HTTP/HTTPS), email (SMTP), file transfers (FTP), and SSH.

2.UDP (User Datagram Protocol)

NatureConnectionless and lightweight.
MechanicsOperates on a "best-effort" delivery basis. It does not establish a formal connection, track packets, check for errors, or guarantee delivery. This eliminates overhead, making it exceptionally fast.
UsageLive video streaming, online gaming, Voice over IP (VoIP), and DNS queries.

4. Multiplexing and Port Addressing

Computers often run multiple network applications simultaneously (e.g., streaming music while browsing a website and downloading a file). Layer 4 handles this via Port Multiplexing:

1.The Mechanism: It appends a Source Port and a Destination Port to every segment.

2.The Result: This allows the operating system to safely deliver arriving network packets to the exact application they belong to, preventing data from overlapping.

5. Challenges & Security (Layer 4 Attacks)

Because Layer 4 controls connection handshakes and processing queues, it is frequently targeted by infrastructure attacks aimed at draining system memory:

TCP SYN Flood (DDoS)Attackers bombard a target server with thousands of connection setup requests (SYN packets) but deliberately ignore the server's responses. This leaves thousands of connections half-open, exhausting the server's memory until it crashes.
UDP Amplification AttacksAttackers exploit connectionless UDP services (like NTP or DNS) by spoofing a victim's IP address. They send tiny queries to public servers, which respond with massive data payloads directed straight at the victim.
Port ScanningMalicious actors sweep thousands of logical ports on a device to discover which services are running and locate potential entry points.

Mitigation: Enable TCP SYN Cookies on servers to track connections without wasting immediate memory, implement strict rate-limiting on firewalls, and block unneeded ports using an access control list (ACL).

The Network Layer (Layer 3) - OSI Model Reference

1. Overview & Purpose

The Network Layer is the third layer of the Open Systems Interconnection (OSI) model. Its primary purpose is to handle host addressing and the routing of data packets across multiple separate, interconnected networks. While Layer 2 handles local delivery within a single neighborhood (LAN), Layer 3 acts as the global postal system, figuring out how to move data across the entire globe from the source network to the final destination network.

Key Characteristics:

1.Operates using logical, software-defined addresses (IP addresses) rather than hardcoded hardware addresses.

2.Primary hardware operating at this layer: Routers and Layer 3 Switches.

3.The basic unit of data at this layer is called a "Packet."

2. Core Functions

The Network Layer is the architectural engine that determines global data paths:

RoutingSelecting the most efficient physical or logical path for data packets across the internet using dynamic routing tables and geometric network paths.
Logical AddressingAssigning unique, structured logical addresses (IPv4 or IPv6) to every host device on a network so they can be identified globally.
Fragmentation & ReassemblyIf a router down the line has a lower Maximum Transmission Unit (MTU) size than the packet it receives, Layer 3 breaks the packet into smaller pieces and reassembles them at the final destination host.
Packet EncapsulationReceives data segments from the Transport Layer (Layer 4) and wraps them with a network header containing source and destination IP addresses.

3. Primary Protocols

Layer 3 relies on a robust mix of addressing, utility, and routing protocols:

1.IP (Internet Protocol - IPv4 / IPv6)

a)Purpose: The core addressing standard used to route packets across the web.

b)Usage: Labeling data with structural source and destination coordinates.

2.ICMP (Internet Control Message Protocol)

a)Purpose: Used by network devices to send error messages and operational info.

b)Usage: Powering basic testing and diagnostic tools like ping and traceroute.

3.IPsec (Internet Protocol Security)

a)Purpose: A suite of protocols used to secure internet protocol communications.

b)Usage: Encrypting and authenticating data packets to form secure VPN tunnels.

4.OSPF / BGP (Routing Protocols)

a)Purpose: Dynamic routing languages that routers use to talk to each other.

b)Usage: Map out internet topology and select the fastest path for traffic.

4. Logical vs. Physical Addressing

Understanding Layer 3 requires distinguishing it from the layer directly below it:

1.Layer 2 (MAC Address): This is the physical burned-in address of a network card. It never changes and is only used to move data inside a local room or switch.

2.Layer 3 (IP Address): This is a logical address assigned by a software system based on where the device is located in the world. It changes when you move to a new Wi-Fi network, allowing global routers to track your general location.

5. Challenges & Security (Layer 3 Attacks)

Because Layer 3 is responsible for tracking IP identities and mapping internet highways, attacks here seek to spoof identities or disrupt regional paths:

IP Address SpoofingAttackers forge the source IP address in a packet's header to hide their true geographic location or impersonate a trusted corporate machine.
ICMP Flooding (Ping Flood)Bombarding a target host with a massive volume of continuous ICMP Echo Request packets to completely choke its inbound bandwidth.
BGP Hijacking / Route PoisoningMaliciously or accidentally altering global internet routing tables to intercept, scan, or completely drop web traffic meant for legitimate enterprises.

Mitigation: Implement Unicast Reverse Path Forwarding (uRPF) to verify packet sources, configure firewalls to rate-limit or disable inbound ICMP requests, and deploy cryptographic BGPsec to secure core internet routing tables.

The Data Link Layer (Layer 2) - OSI Model Reference

1. Overview & Purpose

The Data Link Layer is the second layer of the Open Systems Interconnection (OSI) model. Its primary purpose is to establish and maintain a reliable link over a physical communication medium to move data between directly connected devices. While Layer 3 handles global routing across completely different networks, Layer 2 handles local delivery between devices inside the exact same local neighborhood (Local Area Network).

Key Characteristics:

1.Operates using physical hardware addresses permanently burned into network equipment.

2.Primary hardware operating at this layer: Network Switches, Bridges, and Network Interface Cards (NICs).

3.The basic unit of data at this layer is called a "Frame."

2. Core Functions

The Data Link Layer acts as the bridge between software logic and physical signals:

FramingReceives network packets from Layer 3 and wraps them in a structural frame, adding a header (containing physical addresses) and a trailer (containing error-checking metadata).
Physical AddressingIdentifies unique destination and source hardware coordinates using Media Access Control (MAC) addresses.
Error DetectionUses a Frame Check Sequence (FCS) containing a Cyclic Redundancy Check (CRC) to verify if electrical or wireless data was corrupted during local transmission.
Flow ControlPrevents a fast sending device on the local link from overwhelming a slower receiving device with more data frames than its buffer can handle.
Media Access ControlDictates exactly when a device is allowed to transmit signals over a shared physical medium to prevent data collisions.

3. Two Critical Sublayers

To manage both upper software layers and lower physical hardware, Layer 2 is divided into two distinct sublayers:

1.LLC (Logical Link Control): The upper sublayer. It acts as the interface for the Network Layer protocols, handles error checking, and manages synchronization.

2.MAC (Media Access Control): The lower sublayer. It interfaces directly with the Physical Layer, manages hardware addressing (MAC addresses), and controls access to the transmission media.

4. Primary Protocols

Layer 2 relies on standardized protocols to regulate local network data movement:

1.Ethernet (IEEE 802.3)

a)Purpose: The global standard for wired Local Area Networks (LANs).

b)Usage: Managing data transmission rules over copper and fiber optic cables.

2.Wi-Fi (IEEE 802.11)

a)Purpose: The universal standard for wireless local networking.

b)Usage: Packaging and transmitting local frames via radio frequencies.

3.ARP (Address Resolution Protocol)

a)Purpose: Dynamically maps a known logical IP address to a physical MAC address.

b)Usage: Allowing a computer to find the hardware address of its local gateway.

4.PPP (Point-to-Point Protocol)

a)Purpose: Establishes a direct connection between two networking nodes.

b)Usage: Facilitating direct connections over telephone lines or fiber links.

5. Challenges & Security (Layer 2 Attacks)

Because Layer 2 protocols frequently rely on blind trust within local area networks (LANs), they are highly vulnerable to localized interception and manipulation:

ARP Spoofing / PoisoningAttackers send fraudulent ARP messages across a local network to link their own MAC address with the IP address of a legitimate gateway. This allows them to intercept, read, or modify local network traffic (Man-in-the-Middle).
MAC FloodingBombarding a network switch with thousands of bogus MAC addresses. This overflows the switch's MAC Address Table, forcing it into a "fail-open" mode where it acts like a dumb hub, broadcasting all private traffic to every single port.
VLAN HoppingExploiting misconfigured switch trunk ports to illegally inject traffic into isolated corporate network segments without going through a security router.

Mitigation: Enable Dynamic ARP Inspection (DAI) on switches, enforce DHCP Snooping to track valid IP-to-MAC assignments, and configure Port Security to strictly limit the maximum number of MAC addresses allowed on a single switch port.

The Physical Layer (Layer 1) - OSI Model Reference

1. Overview & Purpose

The Physical Layer is the first and lowest layer of the Open Systems Interconnection (OSI) model. Its primary purpose is to transmit and receive unstructured raw bit streams (0s and 1s) over a physical communication medium. While upper layers deal with complex logical software concepts, protocols, addressing, and data packages, Layer 1 is entirely concerned with the tangible, electrical, mechanical, and functional specifications of hardware.

Key Characteristics:

1.It is the only layer where data is converted into actual physical signals (voltages, light waves, or radio frequencies).

2.Hardware operating at this layer includes cables, connectors, repeaters, hubs, and modems.

3.The basic unit of data at this layer is the "Bit."

2. Core Functions

The Physical Layer defines the hardware rules and signaling mechanisms for transmission:

Bit RepresentationTranslates digital 0s and 1s from the Data Link Layer into physical signals—such as electrical voltage changes on copper, light pulses in fiber optics, or radio waves in the air.
Transmission Rate (Throughput)Defines the maximum speed of the network by specifying the exact number of bits transmitted per second (bps, Mbps, Gbps).
Bit SynchronizationCoordinates the clocks of both the sender and receiver to ensure they agree on exactly when a bit starts and ends, preventing data loss.
Physical TopologySpecifies how network devices are geometrically arranged and cabled together (e.g., Star, Bus, Ring, or Mesh layouts).
Transmission ModeEstablishes the direction of signal flow between devices: Simplex (one-way only), Half-Duplex (two-way but alternating), or Full-Duplex (simultaneous two-way communication).

3. Common Media & Standards

Layer 1 is defined by the physical mediums and engineering standards that guide hardware production:

1.Guided Media (Cables)

Twisted-Pair Copper (CAT5e, CAT6, CAT7)Transmits data via electrical currents.
Fiber Optic Cables (Single-mode, Multi-mode)Transmits data via high-speed light pulses.
Coaxial CablesLegacy copper cables used for cable internet and TV distributions.

2.Unguided Media (Wireless)

–Radio Waves / Microwaves: Transmits data through the air (Wi-Fi, Cellular, Bluetooth).

3.Hardware Connectors

RJ-45Standard 8-pin connector used for wired Ethernet networks.
LC / SC / STStandard connectors used to snap fiber optic lines into place.
BNCLegacy threaded connectors used for coaxial cable setups.

4. Software Data vs. RAW Signals

Understanding Layer 1 requires visualizing how structured data transforms into physical physics:

1.The Upper View: Inside a computer, data exists as organized files, packets, and frames managed by software.

2.The Layer 1 View: The moment data leaves the Network Interface Card (NIC), it is stripped of its structural boundaries. Layer 1 only sees a non-stop, continuous stream of physical energy pulsing down a wire or flying through the air.

5. Challenges & Security (Layer 1 Attacks)

Because Layer 1 deals with tangible media and raw signals, challenges here are entirely physical, involving direct proximity, environmental blockages, or hardware destruction:

RF Signal JammingEmitting targeted radio frequency noise near wireless equipment (like Wi-Fi routers or cellular towers) to completely drown out and block legitimate communications.
Physical WiretappingStripping copper networking cables or micro-bending fiber optic links to intercept raw electrical currents or leaking optical light streams to extract data without leaving trace evidence on the network.
Hardware Theft / VandalismSevering critical undersea internet cables, cutting riser lines in a building, or stealing unsecured network equipment to cause a total service blackout.

Mitigation: Enforce strict physical security controls (locked server rooms, biometric scanners, and surveillance cameras), use shielded twisted-pair (STP) cabling to prevent signal leaking, and deploy wireless intrusion protection systems (WIPS) to detect jamming anomalies.

↑ Back to contents

Chapter 2

Lecture 02 — How the OSI layers work; network vs host; IPv4 classful addressing

How OSI Layer Works

Data travels down the OSI stack at the sender through encapsulation, across intermediate network devices via hop-by-hop routing, and back up the stack at the receiver through decapsulation.

Sender A (EncapsulationTop to Bottom)
Application Layer (L7)The user application creates the raw payload or message (m), such as an HTTP web request.
Presentation Layer (L6)Formats, encrypts, or compresses the message into processed data (C).
Session Layer (L5)Establishes and tracks the communication session between Sender A and Receiver G, passing along the data stream (C).
Transport Layer (L4)Breaks data into segments and appends a header containing:
Source Port (x)An ephemeral client port.
Destination Port (80)Standard web service port targeting the server.
UnitSegment [C | x | 80]

1.Network Layer (L3): Appends end-to-end addressing to form a packet:

Source IP (A)IP address of host A.
Destination IP (G)IP address of Google Server G.
UnitPacket [C | x | 80 | A | G]

2.Data Link Layer (L2): Adds hardware (MAC) addressing to deliver the packet across the local link:

Source MACMAC address of Host A.
Destination MACMAC address of the default gateway router (R₁).
UnitFrame (includes Frame Check Sequence for error detection).

3.Physical Layer (L1): Encodes the frame into raw binary signals (electrical pulses, light, or radio frequencies) onto the physical medium.

2.Intermediate Routers R₁ & R₂ (Hop-by-Hop Routing)

Routers are Layer 3 devices; they only process up to the Network Layer:

1.Physical Layer (L1): Receives the bitstream from the incoming wire.

2.Data Link Layer (L2): Reassembles the frame, verifies frame integrity (CRC), and strips off the incoming MAC headers.

3.Network Layer (L3):

a)Reads the Destination IP (G).

b)Consults the internal Routing Table (NID [Network ID], SM [Subnet Mask], Interface) to determine the next hop.

4.Re-encapsulation (L2 → L1):

a)L3 leaves the original Source IP (A) and Destination IP (G) untouched.

b)L2 rewrites a new frame header with its own MAC as the source and the next hop’s MAC (e.g., R₂ from R₁) as the destination.

c)L1 transmits the bits to the next hop.

Google Server G (DecapsulationBottom to Top)
Physical Layer (L1)Receives the raw bits from the connection link.
Data Link Layer (L2)Verifies the destination MAC matches its interface, validates the CRC, strips the L2 header, and hands the packet up.
Network Layer (L3)Confirms the destination IP is G, strips the IP header, and passes the segment up.
Transport Layer (L4)Inspects the destination port (80) to identify the web service process, performs reassembly, and strips the L4 header.
Session & Presentation Layers (L5–L6)Restores session context, decrypts (e.g., TLS/SSL), and decompresses data back to its original format.
Application Layer (L7)The web server daemon receives the original message (m) and executes the requested action.

Application layer M Application layer

Presentation layer M Presentation layer

Session layer C Session layer

Transport layer    [C | x | 80]                                                   Transport layer
Network layer      [C | x | 80 | Iₛ | Iᵣ]                                       Network layer
Data link layer    [C | x | 80 | Iₛ | Iᵣ | Mₛ | Mᵣ₁]                           Data link layer
Physical layer     [0 1 0 1 1 1 0 0 1 0 1 0 0 1 0 1]                 Physical layer

(S) -------------- (X) -------------- (X) -------------- (X) -------------- (Re)

Sender               R1                 R2                 R3               Receiver

Where:

M= Message
C= Cipher Text
x= Source Port
80= Destination Port
Iₛ= Source IP
Iᵣₑ= Destination/Receiver's IP
Mₛ= Source MAC
Mᵣ₁= Router 1 MAC
Mᵣ₂= Router 2 MAC
Mᵣ₃= Router 3 MAC
Mᵣₑ= Receiver MAC

Question:

If R2 is compromised, what all information will R2 have?

Answer:

① C

② Source port (x), Destination port (80)

③ Source IP (Iₛ), Destination IP (Iᵣₑ)

④ Mac address of R1, R2, R3 (Mᵣ₁, Mᵣ₂, Mᵣ₃)

Network & Hosts

A network is an interconnected group of devices and communication paths, while a host is an individual end-device connected to that network that can send, receive, or process data.

Network ID:

Host ID:

FeatureNetwork (Network ID)Host (Host ID)
DefinitionThe domain or subnet that groups devices together under a common routing path.The specific endpoint or interface operating within that network.
Role in an IPThe prefix portion of an IP address (e.g., the first 3 octets in /24).The remaining suffix portion identifying the machine directly.
Example DevicesNot a physical device itself; represented by subnets, VLANs, LANs, WANs.Laptops, phones, servers, printers, IoT sensors, router interfaces.
Routing PurposeRouters use the Network ID to deliver packets between different sites.Switches and local ARP use the Host ID (paired with MAC) for the final delivery.

How They Work Together in an IP Address

Every standard IPv4 address is split into two parts: [ Network ID ] + [ Host ID ].

IP Addressing

Transport Layer = Process to Process Communication

Network Layer = Host to Host

1.Internet Protocol version 4 (IPv4) is the foundational 32-bit communication protocol used to identify devices and route data packets across the internet

2.Every IPv4 address is actually a 32-bit binary number consisting of a string of 32 ones and zeros.

3.To make them easier to read, we break the 32 bits into four groups of 8 bits (called octets or bytes).

4.IPV4 = 32-bit(Binary Digit) => 4 Octets

5.so for 32 bits, 2³² binary numbers are possible. which is approximately 4.29 Billion possible addresses.

Classful Addressing

1.Classful addressing is an IP address allocation architecture used in the internet from 1981 until the introduction of Classless Inter-Domain Routing (CIDR) in 1993.

2.It divides the entire IPv4 address space into five fixed classes (A, B, C, D, and E) based on the leading bits of the address. The class determines how many bits are allocated for the Network ID (identifying the specific network) versus the Host ID (identifying a specific device on that network).

Successive Halving (Binary Splitting)

Dividing the total 2³² address pool geometrically into Class A, B, C, D, and E:

Class A (First Half: 50% of the entire IPv4 space)

Leading bitFixed to 0
Remaining bits32 - 1 = 31 bits
Total addresses2³¹ addresses
ActionAll addresses with the first bit set to 1 (2³¹ addresses) are passed down to be divided further.
Format0xxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
First Address0.0.0.0
Last Address127.255.255.255

Class B (Half of the remainder: 25% of the total space)

Leading bitsFrom the remaining half (where bit 1 is already 1), the second bit is fixed to 0, making the prefix 10.
Remaining bits32 - 2 = 30 bits
Total addresses2³⁰ addresses
ActionThe remaining portion starting with 11 (2³⁰) is passed on.
Format10xxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
First Address128.0.0.0
Last Address191.255.255.255

Class C (Half of the remainder: 12.5% of the total space)

Leading bitsFixed to 110 (third bit checked from the portion starting with 11)
Remaining bits32 - 3 = 29 bits
Total addresses2²⁹ addresses
ActionThe remaining portion starting with 111 (2²⁹) is passed on.
Format110xxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
First Address192.0.0.0
Last Address223.255.255.255

Class D & Class E (Final split: 6.25% each)

•From the portion starting with 111, the fourth bit is checked:

- Class D (Multicast): Leading bits fixed to 1110, leaving 28 bits → 2²⁸ addresses

Format1110xxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
First Address224.0.0.0
Last Address239.255.255.255

- Class E (Experimental): Leading bits fixed to 1111, leaving 28 bits → 2²⁸ addresses

Format1111xxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
First Address240.0.0.0
Last Address255.255.255.255
**Class A** Starts with 0... -> Decimal 0 – 127
**Class B** Starts with 10... -> Decimal 128 – 191
**Class C** Starts with 110... -> Decimal 192 – 223
**Class D** Starts with 1110... -> Decimal 224 – 239
**Class E** Starts with 1111... -> Decimal 240 – 255

Total Address Space Equation

2³² = 2³¹ (Class A) + 2³⁰ (Class B) + 2²⁹ (Class C) + 2²⁸ (Class D) + 2²⁸ (Class E)

Summary

Each subsequent class takes exactly half of whatever address space remained unassigned from the previous step, until the last remaining block is split equally between Class D and Class E.

Network engineers used a variable-length prefix code, so a router’s hardware logic could determine the class using a simple serial decision tree:

Look at 1st bit:

├── Is it 0? ────▶ STOP. It's Class A.
└── Is it 1? ────▶ Look at 2nd bit:
                    ├── Is it 0? ────▶ STOP. It's Class B.
                    └── Is it 1? ────▶ Look at 3rd bit:
                                        ├── Is it 0? ────▶ STOP. It's Class C.
                                        └── Is it 1? ────▶ Look at 4th bit:
                                                            ├── Is it 0? ──▶ Class D.
                                                            └── Is it 1? ──▶ Class E.

How Network ID (NID) and Host ID (HID) Are Fixed

In classful addressing, the division between the Network ID (NID) and

Host ID (HID) is set along 8-bit octet boundaries:

Class A

Network ID1 octet (8 bits, with 1 fixed bit 0 and 7 variable network bits)
Host ID3 octets (24 bits)
Default Mask255.0.0.0 (/8)
Capacity2⁷ = 128 networks (0–127), each with 2²⁴ - 2 = 16,777,214 usable hosts

Class B

Network ID2 octets (16 bits, with 2 fixed bits 10 and 14 variable network bits)
Host ID2 octets (16 bits)
Default Mask255.255.0.0 (/16)
Capacity2¹⁴ = 16,384 networks, each with 2¹⁶ - 2 = 65,534 usable hosts

Class C

Network ID3 octets (24 bits, with 3 fixed bits 110 and 21 variable network bits)
Host ID1 octet (8 bits)
Default Mask255.255.255.0 (/24)
Capacity2²¹ = 2,097,152 networks, each with 2⁸ - 2 = 254 usable hosts

↑ Back to contents

Chapter 3

Lecture 03 — Casting, network representation, subnetting & CIDR

Types of Casting

1.Unicast: Send a packet from one host to another host.

2.Broadcast: Send a packet from one host to multiple hosts.

a)Limited Broadcast: Send a packet to all the hosts of same network (255.255.255.255)

b)Directed Broadcast: Send a packet to all the hosts of other network (20.255.255.255)

IP Address Transmission Modes & Network Representation

1. Network Representation Rule

1.In network representation, all bits in the Host ID are set to 0.

2.The first IP address of any network block represents the network itself (e.g., 11.0.0.0, 130.20.1.0, 200.10.1.0) and cannot be assigned to an individual host. Example:

IP: 130.20.1.2  ──►  Network ID: 130.20.0.0 (Class B: 16-bit NID)

2.UNICAST (One-to-One Communication)

•Concept: Direct communication between a single sender and a single receiver. Network: 11.0.0.0 Network: 20.0.0.0

┌───────────────┐                       ┌───────────────┐
|   Host (S)    |──────────────────────►|   Host (D)    |
│   11.1.2.3    │                       │   20.1.2.3    │
└───────────────┘                       └───────────────┘

•Packet Format:

┌──────┬──────────────────────┬───────────────────────────┐
│ Data │ Source IP: 11.1.2.3  │ Destination IP: 20.1.2.3  │
└──────┴──────────────────────┴───────────────────────────┘

•Delivery: Only host 20.1.2.3 receives and processes the packet.

3.LIMITED BROADCAST (One-to-All within Local Network)

1.Concept: A host sends a message to ALL hosts inside its own local network.

2.Reserved IP: 255.255.255.255 (all 32 bits set to 1). Network: 11.0.0.0

┌───────────────────────┐
│        ┌───► Host     │
│        │             │
│ Host  ─┼───► Host     │
│11.1.2.3│              │
│        ├───► Host     │
│        └───► Host     │
└───────────────────────┘

•Packet Format:

┌──────┬──────────────────────┬───────────────────────────────┐
│ Data │ Source IP: 11.1.2.3  │Destination IP: 255.255.255.255│
└──────┴──────────────────────┴───────────────────────────────┘

•Router Behavior: Routers NEVER forward packets destined for 255.255.255.255; traffic is strictly contained within the local subnet.

4.DIRECTED BROADCAST (One-to-All in a Remote Network)

1.Concept: A host sends a packet to ALL hosts residing inside a remote network.

2.Structure: Target Network ID retained + all Host ID bits set to 1 (255). Network: 11.0.0.0 Network: 20.0.0.0

┌───────────────┐                       ┌───────────────────────┐
│   Host (S)    │                       │       ┌───► Host      │
│   11.1.2.3    |──────────────────────►|       ├───► Host      |
│               │                       │       ├───► Host      │
│               │                       │       └───► Host      │
└───────────────┘                       └───────────────────────┘

•Packet Format:

┌──────┬──────────────────────┬───────────────────────────────┐
│ Data │ Source IP: 11.1.2.3  │ Destination IP: 20.255.255.255│
└──────┴──────────────────────┴───────────────────────────────┘

•Delivery: Routers forward this across the internet to network 20.0.0.0, where the local router broadcasts it to every machine on that subnet.

What Is Subnetting?

Subnetting is the process of dividing a single large physical or logical

network into two or more smaller, distinct sub-networks, known as subnets.

It is done by "borrowing" bits from the Host ID portion of an IP address

and reallocating them to create a Subnet ID.

How It Works

1.Every standard IP address is divided into two sections:

–[ Network ID ] + [ Host ID ]

2.When you subnet, you introduce a third intermediate level:

–[ Network ID ] + [ Subnet ID ] + [ Host ID ]

The Mathematical Process

1.Borrowing Bits:

If you borrow n bits from the host part, you create 2ⁿ subnets.

2.Remaining Host Bits:

If h bits remain for the host, each subnet will contain 2ʰ total IP addresses

(with 2ʰ - 2 usable addresses for actual devices, after excluding the Subnet ID

and the Directed Broadcast Address).

3.Updating the Mask:

The subnet mask extends to the right by turning the borrowed host bits

from 0s to 1s.

STEP-BY-STEP EXAMPLE: An Organization needs 4 Departments (SALES, IT, HR, OPERATIONS)

Step 1: The Starting Network (Unsubnetted)

1.Base Network : 192.168.1.0/24 (Class C)

2.Subnet Mask : 255.255.255.0

3.Default Layout :

Network bits= 24,
Host bits= 8 (192.168.1. [ H H H H H H H H ])
Total Addresses2⁸ = 256 (from 192.168.1.0 to 192.168.1.255)

Step 2: Borrowing Bits

1.Subnets Needed : 4

2.Formula : 2ⁿ ≥ required subnets

2² = 4  ──►  Borrow n = 2 bits from Host ID

•Bit Division in the 4th Octet:

a)Borrowed bits (Subnet ID) : 2 bits

b)Remaining bits (Host ID) : 8 - 2 = 6 bits

Class C Octet 4: [ S₁ S₂ ] [ H H H H H H ]

└───┬──┘     └──────┬──────┘

Subnet ID Host ID

How the Subnet Mask Is Calculated

A subnet mask always sets all network and borrowed subnet bits to 1,

and all remaining host bits to 0.

For /26 (24 original network bits + 2 borrowed subnet bits):

1.First 3 Octets (24 bits):

All bits are 1s:

11111111.11111111.11111111 ──► 255.255.255

2.The 4th Octet (8 bits):

Has 2 ones (subnet bits) and 6 zeros (host bits):

11000000

Binary: 11111111.11111111.11111111.11000000

3.Converting 11000000 to Decimal:

Using standard binary place values:

Bit Position :  128   64   32   16    8    4    2    1
Bit Value    :    1    1    0    0    0    0    0    0

Calculation : 128 + 64 = 192

Result Mask : 255.255.255.192

Address Capacity PER Subnet

Remaining Host Bits6 bits
Total Addresses2⁶ = 64 addresses per subnet
Usable Host IPs64 - 2 = 62 usable addresses per subnet (excluding Subnet ID and Directed Broadcast ID)

Step 3: Determining the 4 Subnet Combinations

The 2 borrowed bits (S₁ S₂) have 4 possible combinations: 00, 01, 10, and 11.

Subnet 1 (Bits: 00) — Sales

1.Binary Range : 192.168.1. [00 000000] to 192.168.1. [00 111111]

2.Decimal Range: 192.168.1.0 to 192.168.1.63

- Network ID            : 192.168.1.0      (Identifies Sales network)
- Usable Host Range     : 192.168.1.1      to  192.168.1.62 (62 PCs/Printers)

–Directed Broadcast ID : 192.168.1.63 (Broadcasts to all Sales PCs)

Subnet 2 (Bits: 01) — IT

1.Binary Range : 192.168.1. [01 000000] to 192.168.1. [01 111111]

2.Decimal Range: 192.168.1.64 to 192.168.1.127

–Network ID : 192.168.1.64

- Usable Host Range     : 192.168.1.65     to  192.168.1.126

–Directed Broadcast ID : 192.168.1.127

Subnet 3 (Bits: 10) — HR

1.Binary Range : 192.168.1. [10 000000] to 192.168.1. [10 111111]

2.Decimal Range: 192.168.1.128 to 192.168.1.191

–Network ID : 192.168.1.128

- Usable Host Range     : 192.168.1.129    to  192.168.1.190

–Directed Broadcast ID : 192.168.1.191

Subnet 4 (Bits: 11) — Operations

1.Binary Range : 192.168.1. [11 000000] to 192.168.1. [11 111111]

2.Decimal Range: 192.168.1.192 to 192.168.1.255

–Network ID : 192.168.1.192

- Usable Host Range     : 192.168.1.193    to  192.168.1.254

–Directed Broadcast ID : 192.168.1.255

Step 4: How the Router Uses This

When a packet arrives for IP 192.168.1.70, the router determines where to send it by performing a bitwise AND between the destination IP and the subnet mask:

Step-By-Step Bitwise and Calculation

The router uses the bitwise AND logic operation to determine which network

an incoming packet's destination IP address belongs to.

[Destination IP] AND [Subnet Mask] = Network ID

1. the Rule of Bitwise and

1 AND 1= 1 (Only produces 1 if BOTH bits are 1)
1 AND 0= 0
0 AND 1= 0
0 AND 0= 0

2. Setup: IP Address and Mask

1.Incoming Destination IP : 192.168.1.70

2.Subnet Mask : 255.255.255.192

First 3 Octets (Network ID portion):

Each octet is ANDed with 255 (11111111), which preserves the exact value:

192 AND 255= 192
168 AND 255= 168
1 AND 255= 1

4th Octet (Where the subnet boundary lies):

1.Destination IP value = 70

2.Subnet Mask value = 192

3. Execution on the 4TH Octet

Step A: Convert 70 and 192 to 8-bit binary:

Value 70 in binary: 0 1 0 0 0 1 1 0 (64 + 4 + 2 = 70)

Value 192 in binary: 1 1 0 0 0 0 0 0 (128 + 64 = 192)

Step B: Perform bit-by-bit AND from left to right:

Bit 10 AND 1 = 0
Bit 21 AND 1 = 1
Bit 30 AND 0 = 0
Bit 40 AND 0 = 0
Bit 50 AND 0 = 0
Bit 61 AND 0 = 0
Bit 71 AND 0 = 0
Bit 80 AND 0 = 0

Step C: Read the binary result:

Result: 0 1 0 0 0 0 0 0

Step D: Convert the binary result back to decimal:

Bit Position : 128   64   32   16    8    4    2    1
Result Bits  :   0    1    0    0    0    0    0    0

Value : 64

4. Conclusion & Routing Decision

Combining all 4 octets yields:

192.168.1.64

The router matches 192.168.1.64 in its routing table and forwards the packet

directly to the IT Subnet interface.

Instead of running one massive broadcast pool where a single broadcast interrupts all 256 devices, subnetting slices that continuous block into 4 isolated smaller rooms (each with 64 addresses):

Broadcast Containment: When a host in Sales sends an ARP request or local broadcast, the packet hits 192.168.1.63 and stops at the router. The IT, HR, and Operations departments never receive or process that packet.

Granular Administration: Each department gets its own designated gateway interface, its own dedicated address range, and can have its own specific security filtering or firewall rules applied at the router boundary.

Why are we performing AND function here? why dont we just send the packet to the given ip 192.168.1.70?

Why Routers Use Bitwise and (Instead of Direct Host IP Lookups)

1. Core Problem: Scalability

1.Routers do not track individual host devices (192.168.1.70, .71, .72, etc.).

2.Storing every individual device on Earth would require billions of table entries, exhausting router memory and slowing down lookup speeds.

2. Postal Service Analogy

Destination AddressJane Doe, Apartment 4B, 120 Main Street, New York
Sorter in Remote CityLooks ONLY at the City/ZIP code (Network ID).
Local Mail CarrierDelivers to the building, then finds Apt 4B (Host ID).

In Networking:

1.Network ID = The City / Neighborhood

2.Host ID = The specific person / apartment

3. Router's Internal Routing Table

A router stores destination NETWORKS, not hosts:

Destination Network Subnet Mask Exit Interface

------------------- ----------------- ------------------------

192.168.1.0           255.255.255.192     Port 1 (Sales Dept)
192.168.1.64          255.255.255.192     Port 2 (IT Dept)
192.168.1.128         255.255.255.192     Port 3 (HR Dept)
192.168.1.192         255.255.255.192     Port 4 (Operations Dept)

4. Why Bitwise and Is Required

1.Packet arrives with target IP: 192.168.1.70.

2."192.168.1.70" is NOT in the routing table.

3.The router must strip away the host bits and extract the Network ID.

4.Digital hardware uses the bitwise AND operation as an ultra-fast hardware filter ("mask") to isolate network bits:

Destination IP : 192.168.1.70   ──► 11000000.10101000.00000001.01000110
Subnet Mask    : 255.255.255.192──► 11111111.11111111.11111111.11000000
Result (AND)   : 192.168.1.64   ──► 11000000.10101000.00000001.01000000

5. the Delivery Handoff

Network Match192.168.1.64 matches the table entry for "Port 2 (IT Dept)".
Router ActionPacket is forwarded out Port 2.
Local SwitchOnce the packet reaches the IT local switch, Layer 2 (ARP/MAC) delivers the packet directly to machine .70.

Classless Inter-Domain Routing

CIDR is an IP addressing scheme introduced to replace the rigid, wasteful system of classful addressing (Class A, B, and C).

Instead of forcing network boundaries to sit strictly on 8-bit octet boundaries (/8, /16, /24), CIDR allows network prefixes of any arbitrary bit length from /1 to /32.

The Problem CIDR Solved

Under traditional classful addressing, organizations had to pick from rigid block sizes:

1.Class C: 254 usable hosts (often too small).

2.Class B: 65,534 usable hosts (often way too large).

If an organization needed 1,000 addresses, a Class C block was insufficient, so they were granted a Class B block. That single assignment left over 64,000 IP addresses unused and wasted. CIDR eliminated these predefined classes, allowing blocks sized precisely to need (e.g., a /22 block gives exactly 1,024 addresses).

To qualify as a valid CIDR block, an IP range must strictly satisfy 3 fundamental rules:

Rule 1The addresses must be contiguous (continuous).
Rule 2The total number of addresses must be a power of 2 (2ⁿ).
Rule 3The first IP address must be evenly divisible by the block size.

–Because a CIDR block must align properly on binary boundaries, the starting IP's numerical value must be a multiple of the block size.

VERIFYING A VALID CIDR BLOCK: 100.1.2.32 TO 100.1.2.47

A range of IP addresses forms a valid CIDR block if and only if it satisfies

all 3 fundamental rules:

RULE 1: ADDRESSES MUST BE CONTIGUOUS (CONTINUOUS)

Range given100.1.2.32 to 100.1.2.47
StatusAll IP addresses in the sequence exist without any gap.
VerdictPASSED [✔]

RULE 2: TOTAL NUMBER OF ADDRESSES MUST BE A POWER OF 2 (2ⁿ)

FormulaTotal IPs = (Last IP - First IP) + 1
Calculation(47 - 32) + 1 = 15 + 1 = 16
Power of 216 = 2⁴ ──► n = 4 host bits
VerdictPASSED [✔]

RULE 3: FIRST IP MUST BE EVENLY DIVISIBLE BY THE BLOCK SIZE

Method A: Decimal Divisibility

First IP 4th octet= 32
Block size= 16
Calculation32 / 16 = 2 (remainder 0)

•Since 32 is evenly divisible by 16, boundary alignment is valid.

Method B: Binary Bit Boundary Check

1.Block size is 16 (2⁴), meaning the last 4 bits belong to the Host ID.

2.For the first address, all host bits must be zeros (0):

100.1.2. 0 0 1 0 [ 0 0 0 0 ]

└───┬───┘

Last 4 bits = 0000

•Verdict : PASSED [✔]

Final Conclusion

1.Result : The range is a VALID CIDR block.

2.CIDR Prefix : 100.1.2.32/28 (32 total bits - 4 host bits = /28 mask)

↑ Back to contents

Chapter 4

Lecture 05 — Application layer (HTTP, DNS, e-mail, FTP) & transport-layer intro

HTTP (Hypertext Transfer Protocol) Overview

1. Core Concepts & Properties

• Purpose

a)Operates at the Application Layer of the networking stack.

b)Primary role: Fetches web resources (HTML, images, CSS, scripts) from web servers to clients (browsers).

• Port Number

a)Default unencrypted communication: TCP Port 80

b)Secure/Encrypted alternative (HTTPS): TCP Port 443

• Transport Reliability

a)Relies on TCP (Transmission Control Protocol) at the transport layer.

b)Ensures lossless, ordered delivery via 3-way handshakes, retransmissions, and error-checking.

• In-Band Protocol

a)Control signals/commands (e.g., GET /index.html, 200 OK) and payload data (HTML, images) share the exact same TCP connection.

b)Contrasts with out-of-band protocols (e.g., FTP: Port 21 for control, Port 20/dynamic for data).

• Stateless Architecture

a)The server treats every request as an independent transaction; no historical session context is maintained by default.

b)State Management ("Cookies"): Maintained using HTTP cookies, session tokens, and local storage to track persistent states (logins, shopping carts).

2. Key Versions: Persistence

• HTTP 1.0 (Non-Persistent Connection)

a)Opens and tears down a separate TCP connection for every single request/response pair.

b)High latency due to repeated TCP handshakes (e.g., 1 HTML + 10 images = 11 distinct TCP connections).

• HTTP 1.1 (Persistent Connection / Keep-Alive)

a)Reuses a single TCP connection for multiple sequential requests/responses.

b)Significantly reduces round-trip handshake overhead and network latency.

3. Client-Server Interaction Lifecycle

[ CLIENT (Browser) ] [ SERVER (Web Server) ]

**│                                                   │**
**│───── 1. Send HTTP Request ───────────────────────►│**
**│      • Method  : GET, POST, PUT, DELETE           │**
**│      • URL/URI : Target resource path             │**
**│      • Headers : User-Agent, Accept, Cookie, Host │**
**│      • Body    : Payload data (optional)          │**
**│                                                   │**
**│◄──── 2. Return HTTP Response ─────────────────────│**
**│      • Status Code : 200 OK, 404 Not Found, etc.  │**
**│      • Headers     : Content-Type, Set-Cookie     │**
**│      • Body        : HTML, JSON, binary images    │**
**▼                                                   ▼**

HTTP Methods Overview

MethodAction
GETRequests a document from the server
HEADRequests information about a document but not the document itself
PUTSends a document from the client to the server
POSTSends some information from the client to the server
TRACEEchoes the incoming request
DELETERemoves the web page
CONNECTReserved (typically used for SSL/TLS tunneling via proxies)
OPTIONSInquires about available options (supported HTTP methods)

Detailed Breakdown & Technical Context

• GET

a)Safe & Idempotent: Retrieves the specified resource without modifying server state.

b)Carries parameters inside the URL query string (not the request body).

• HEAD

a)Identical to GET, but the server returns ONLY the response headers (status line and headers) without the response body.

b)Useful for checking file sizes ('Content-Length'), cache freshness, or link validity without downloading heavy assets.

• PUT vs. POST

a)PUT: Idempotent replacement. Uploads a resource to a specific URI, completely overwriting whatever exists at that location (or creating it if absent).

b)POST: Non-idempotent submission. Submits data to be processed by the resource identified by the URI (e.g., submitting forms, adding a record to a database, uploading data).

• Delete

↳Idempotent: Requests that the origin server delete the resource identified by the Request-URI.

• TRACE

a)Performs a message loop-back test along the path to the target resource.

b)The recipient reflects the received request message back as the response body; often disabled in production environments due to Cross-Site Tracing (XST) vulnerabilities.

• Connect

↳Reserved for two-way communication pipelines, primarily establishing a bidirectional TCP tunnel (e.g., for HTTPS through an HTTP proxy).

• Options

a)Discovers communication options/capabilities supported by the server for a given target (commonly returns the 'Allow' header listing allowed methods: 'Allow: GET, POST, OPTIONS').

b)Extensively used in CORS (Cross-Origin Resource Sharing) preflight requests by modern web browsers.

HTTP Connections: Non-Persistent vs. Persistent Overview

1. Non-Persistent Connection (HTTP 1.0)

Every requested object requires its own dedicated TCP connection lifecycle.

1.Connect TCP (SYN, SYN-ACK, ACK + HTTP Request)

2.Server transfers "File" (HTML)

3.Close TCP (Teardown handshake)

4.Connect NEW TCP (SYN, SYN-ACK, ACK + HTTP Request)

5.Server transfers "Image"

6.Close TCP (Teardown handshake)

1.Workflow:

a)File Request: Connection opened → File transferred → Connection closed.

b)Image Request: New connection opened → Image transferred → Connection closed.

2.Latency:

↳Incurs 2 RTT (Round Trip Times) per object before data begins streaming.

2. Persistent Connection (HTTP 1.1)

A single TCP connection stays open across multiple consecutive requests.

1.Connect TCP (SYN, SYN-ACK, ACK + HTTP Request)

2.Server transfers "File" (HTML)

3.Send HTTP Request for "Image" (Immediate, NO handshake!)

4.Server transfers "Image"

5.Close TCP (Teardown handshake)

1.Workflow:

a)Initial connection established via 3-way handshake.

b)Base file and subsequent assets (images, scripts, CSS) use the same channel.

c)Connection closes only when session completes or idle timeout is hit.

2.Latency:

↳Subsequent objects require only 1 RTT (Request + Data Transfer).

3. Side-By-Side Comparison

FeatureNon-PersistentPersistent
Default Specification<br />Sockets for N Objects<br />3-Way Handshakes<br />Subsequent Asset Latency<br />Server Socket OverheadHTTP 1.0<br />N distinct sockets<br />Once per object<br />~2 RTT + Transfer<br />High socket churnHTTP 1.1<br />1 shared socket<br />Once per session<br />~1 RTT + Transfer<br />Lower connection churn

DNS (Domain Name System) Overview

1. Core Concepts & Purpose

1.Translation Role

a)Primary function: Maps human-friendly domain names to machine-routable IP addresses (and vice versa).

b)Domains are easy for humans to remember; IP addresses are required by network routing hardware.

2.Port & Transport

↳Default Port: Port 53 (primarily UDP for fast standard queries; TCP for zone transfers and responses exceeding 512 bytes).

3.Dynamic Mapping

↳IP addresses are frequently non-static (due to DHCP, load balancing, cloud hosting, CDNs), requiring a dynamic lookup system rather than hardcoded host files.

2. Types of Domain Names

1.Generic Domains (gTLD)

↳Identifies organizational or thematic categories:

.comCommercial businesses
.eduEducational institutions
.orgNon-profit organizations
.netNetwork infrastructure / providers
.milMilitary entities

2.Country Domains (ccTLD)

↳Two-letter country code delegations:

.inIndia
.usUnited States
.ukUnited Kingdom

3.Inverse Domains (Reverse DNS)

a)Maps an IP address back to its corresponding domain name (Pointer / PTR records).

b)Used for network diagnostics, spam filtering, and server verification.

4.Diagnostic Utility Mentioned

↳nslookup: Command-line tool used to query DNS servers directly (e.g., 'nslookup www.google.com').

3. Hierarchical Domain Space & Architecture

DNS is structured as an inverted distributed tree:

[ Root Server (".") ]

(13 Named Clusters)

┌──────────────┼──────────────┐
▼              ▼              ▼

[ .edu Server ] [ .com Server ] [ .us Server ] (TLD Servers)

┌────┴────┐     ┌────┴────┐          │
▼         ▼     ▼         ▼          ▼

fhda.edu bk.edu mcgraw.com irwin.com ... (Authoritative)

1.Root Servers:

↳13 logical root server addresses (named A through M) distributed globally using Anycast routing.

2.DNS Overhead:

a)For unfamiliar/newly queried domains, the local DNS resolver does not have cached records and must traverse the hierarchy up to the root server.

b)This lookup latency is referred to as "DNS overhead."

3.Local DNS Caching:

↳For frequent or previously resolved domains, the Local DNS Server answers immediately from its local cache, bypassing root and TLD servers.

4. Resolution Methods: Recursive vs. Iterative

Example Scenario:

1.Client (Resolver) : some.anet.com (inside Anet ISP)

2.Target Domain : engineering.mcgraw-hill.com

METHOD A: RECURSIVE RESOLUTION (Chain of Delegation)

Each server contacts the next level on behalf of the requester and passes the

final answer back down the chain.

[Client] ──(1) Query──► [Local Server] ──(2) Query──► [Root Server]
   │                          │                              │ (3) Query
   │                          │                              ▼
   │                          │                     [TLD (.com) Server]
   │                          │                              │ (4) Query
   │                          │                              ▼
   │                          │                     [Authoritative Server]
   │                          │                       (mcgraw-hill.com)
   │                          │                              │
   │                          │ ◄───(7) Answer── [Root] ◄────┴─(6) Answer ◄──(5) Answer
   │                          │
   ◄──────(8) Final IP────────┤
Step 1Client queries the Local ISP DNS Server.
Step 2Local Server queries the Root Server.
Step 3Root Server directly queries the Top-Level Domain (.com) Server.
Step 4.com Server queries the Authoritative Server (dns.mcgraw-hill.com).
Steps 5-7The answer ripples back down the chain in reverse order.
Step 8Local Server returns the final resolved IP to the client.

METHOD B: ITERATIVE RESOLUTION (Referral System)

The Local Server manages the lookup process itself by receiving referrals to

progressively more specific name servers.

[Client] ──(1) Query──► [Local Server] ──(2) Query──────► [Root Server]
   │                          │       ◄──(3) Referral────┘  (points to .com)
   │                          │
   │                          ├────────(4) Query────────► [TLD (.com) Server]
   │                          │       ◄──(5) Referral────┘  (points to mcgraw-hill)
   │                          │
   │                          ├────────(6) Query────────► [Authoritative Server]
   │                          │       ◄──(7) Returns IP──┘  (dns.mcgraw-hill.com)
   │                          │
   ◄──────(8) Final IP────────┤

Step 1: Client to Local DNS Server

1.The client machine (some.anet.com) needs the IP address for engineering.mcgraw-hill.com.

2.It sends a query to its configured Local DNS Server (dns.anet.com).

3.Note: From the client's perspective, this initial request is typically recursive.

Step 2: Local Server to Root Server

1.Assuming the local server has no cached record for this domain, it contacts a Root Server (.).

2.Query sent: "What is the IP address for engineering.mcgraw-hill.com?"

Step 3: Root Server Referral

1.The Root Server does not hold the specific host record for engineering.mcgraw-hill.com.

2.Response returned: A referral containing the IP address of the Top-Level Domain (TLD) .com Server.

Step 4: Local Server to TLD Server

1.The Local Server follows the referral and queries the .com TLD Server.

2.Query sent: "What is the IP address for engineering.mcgraw-hill.com?"

Step 5: TLD Server Referral

1.The .com TLD Server does not have the final host IP, but it knows the registered name server for the target organization's domain.

2.Response returned: A referral providing the IP address of the authoritative name server for mcgraw-hill.com (dns.mcgraw-hill.com).

Step 6: Local Server to Authoritative Server

1.The Local Server queries the McGraw-Hill authoritative server (dns.mcgraw-hill.com).

2.Query sent: "What is the IP address for engineering.mcgraw-hill.com?"

Step 7: Authoritative Answer

1.The authoritative server owns the zone records and holds the specific A record (host-to-IP mapping).

2.Response returned: Supplies the actual destination IP address back to dns.anet.com.

Step 8: Local Server to Client

1.The Local Server saves the record in its local cache (with an associated TTL / Time-To-Live) to accelerate future queries.

2.It delivers the resolved IP address back to the requesting client (some.anet.com) so it can initiate its direct connection.

*Note: In real-world internet architecture, recursive resolution is standard between

the client and the local resolver, while iterative resolution is almost universally

used between the local resolver and the higher-level hierarchy servers.*

Real-World Iterative DNS Resolution: Airtel Network Scenario

1. Actors & Network Identities

1.Client / Source:

a)Your personal device (Laptop or Smartphone).

b)Connected via Wi-Fi to your home router; assigned a private IP (e.g., 192.168.1.5).

2.Local DNS Server:

a)Airtel ISP's recursive DNS resolver (assigned automatically via DHCP when your router connects to Airtel Broadband / Fiber).

b)Replaces "dns.anet.com" from the textbook slide.

3.Destination Target:

a)"www.swiggy.com" (The web service you are trying to reach).

b)Replaces "engineering.mcgraw-hill.com" from the textbook slide.

2. Step-By-Step Resolution Flow

[ Your Laptop ]          [ Airtel DNS ]              [ Root Server ]
192.168.1.5               (Airtel ISP)                     │
     │                         │                           │
     ├──(1) Query─────────────►│                           │
     │   "www.swiggy.com"      │                           │
     │                         ├──(2) Query──────────────► │
     │                         │   "www.swiggy.com"        │
     │                         │                           │
     │                         │◄─(3) Referral─────────────┤
     │                         │      Points to .com TLD   │
     │                         │                           │
     │                         │                  [ .com TLD Server ]
     │                         │                   (Verisign Registry)
     │                         │                           │
     │                         ├──(4) Query───────────────►│
     │                         │                           │
     │                         │◄─(5) Referral─────────────┤
     │                         │      Points to Swiggy's   │
     │                         │      Name Server          │
     │                         │                           │
     │                         │                 [ Authoritative Server ]
     │                         │                  (AWS Route 53 / Cloudflare)
     │                         │                           │
     │                         ├──(6) Query───────────────►│
     │                         │                           │
     │                         │◄─(7) Returns IP───────────┤
     │                         │      (e.g., 49.44.110.12) │
     │                         │                           │
     │◄─(8) Resolved IP─────┤                            │
     ▼                         ▼                           ▼

1.Step 1 (Device to Airtel):

↳Your browser asks Airtel's DNS resolver: "What is the IP of www.swiggy.com?"

2.Step 2 & 3 (Airtel to Root):

a)Airtel's resolver contacts an Internet Root Server cluster (".").

b)Root Server responds: "I don't know Swiggy's IP, but here is the .com TLD server."

3.Step 4 & 5 (Airtel to TLD):

a)Airtel's resolver queries the .com TLD server.

b)TLD Server responds: "Go ask Swiggy's authoritative server (Route 53 / Cloudflare)."

4.Step 6 & 7 (Airtel to Authoritative):

a)Airtel's resolver queries Swiggy's authoritative DNS server.

b)Authoritative server returns the actual destination IP address (A record).

5.Step 8 (Airtel to Device):

a)Airtel stores the mapping in its cache and sends the IP to your device.

b)Your browser can now establish a direct HTTPS connection to Swiggy.

3. Direct Role Mapping

┌───────────────────────┬─────────────────────────┬────────────────────────┐
│ Architecture Role     │ Slide Diagram Label     │ Airtel Context         │
├───────────────────────┼─────────────────────────┼────────────────────────┤
│Client / Requester     │ some.anet.com           │ Your phone or laptop   │
│Local DNS Resolver     │ dns.anet.com (Anet ISP) │ Airtel DNS resolver    │
│Root Name Server       │ Root server (.)         │ Global Root (A to M)   │
│Top-Level Domain (TLD) │ .com Server             │ .com Registry Server   │
│Authoritative Server   │ dns.mcgraw-hill.com     │ Swiggy Name Server     │
│Destination Target     │ engineering.mcgraw-     │ www.swiggy.com         │
│                       │ hill.com                │                        │
└───────────────────────┴─────────────────────────┴────────────────────────┘

SMTP (Simple Mail Transfer Protocol) Overview

1. Key Properties & Architecture

1.Store-and-Forward Model:

a)Unlike FTP (where both client and server must be simultaneously online), email does not require the recipient to be online when the message is sent.

b)Intermediate mail servers store messages until the recipient connects.

2.Push vs. Pull Distinction:

a)PUSH Protocol (SMTP) : Pushes emails from client to server, and relays emails from server to server.

b)PULL Protocol (POP/IMAP): Pulls/downloads stored messages from the destination mailbox server to the end user.

3.Agent Roles:

a)MTA (Mail Transfer Agent) : Transports and relays messages using SMTP.

b)MAA (Mail Access Agent) : Retrieves messages using POP3 or IMAP.

2. Email Delivery Workflow (Alice to BOB)

[ Alice ]                [ Alice's Server ]           [ Bob's Server ]             [ Bob ]
(Sender)                   (Sender MTA)                (Receiver MTA)            (Receiver)
   │                             │                            │                       │
   ├── 1. SMTP Push (MTA) ──────►│                            │                       │
   │   (LAN / WAN)               ├─── 2. SMTP Push (MTA) ────►│                       │
   │                             │    (Over Internet)         │                       │
   │                             │                            ├─ 3. POP/IMAP Pull ───►|
   │                             │                            │    (MAA / Mailbox)    │
   ▼                             ▼                            ▼                       ▼

1.Stage 1 (MTA 1 - SMTP):

↳Alice's client pushes the message to her local outgoing mail server.

2.Stage 2 (MTA 2 - SMTP):

↳Alice's mail server routes the message across the Internet to Bob's server.

3.Stage 3 (MAA - POP/IMAP):

↳Bob logs on and pulls the stored message from his server to his local client.

MIME (Multipurpose Internet Mail Extension) Overview

1. Historical Context & Purpose

1.Original SMTP Constraint:

a)SMTP was built strictly to transmit simple, plain English text formatted in 7-bit NVT ASCII (Network Virtual Terminal ASCII).

b)Incapable of directly handling raw binary files, non-Latin alphabets, audio, images, videos, or document attachments.

2.MIME Solution:

a)Acts as an encoding and decoding bridge.

b)Converts birnay / Non-Text / Non-ASCII data into 7-bit ASCII text for transit, then restores it back to binary on the receiving end.

2. End-To-End Data Flow (Alice to BOB)

[ Alice (Sender) ] [ Bob (Receiver) ]

      │                                                             ▲
      ▼                                                             │
┌───────────┐                                                  ┌──────────┐
│ User Agent│                                                  │User Agent│
└─────┬─────┘                                                  └────▲─────┘
      │ (Non-ASCII code / Binary)                                   │ (Non-ASCII code / Binary)
      ▼                                                             │
┌───────────┐                                                  ┌──────────┐
│   MIME    │                                                  │   MIME   │
└─────┬─────┘                                                  └────▲─────┘
      │ (7-bit NVT ASCII Text)                                      │ (7-bit NVT ASCII Text)
      ▼                                                             │

E-Mail System (SMTP)

Step 1 (Sender)User Agent submits (audio, images, videos etc,.)binary / non-ASCII content.
Step 2 (Encode)MIME transforms binary into 7-bit ASCII (e.g., Base64).
Step 3 (Transit)Standard SMTP servers route the ASCII text message.
Step 4 (Decode)Recipient MIME reconstructs original binary data.
Step 5 (Receiver)User Agent displays/saves the multimedia attachment.

3. Common MIME Headers Used in Practice

MIME-VersionSpecifies the version of MIME being used (e.g., 1.0).
Content-TypeDescribes media type and subtype (e.g., image/png, application/pdf).
Content-Transfer-EncodingMethod used for conversion (e.g., base64, 7bit).

Gmail (Web-based Email) Overview

1. Architectural Concepts

1.Background Mail Processing:

a)The underlying email delivery backbone continues to run standard SMTP servers to route and receive messages across the Internet.

b)Instead of requiring a desktop email client (like Microsoft Outlook or Apple Mail) that communicates directly via POP/IMAP/SMTP, Raw email records and message stores are dynamically converted into browser-readable webpages (HTML, CSS, JavaScript)..

2.Web Server & Client Interaction:

a)Email interface pages reside on a central web server.

b)The client machine accesses, views, and composes emails using standard HTTP / HTTPS within any web browser (eliminating the need for a dedicated desktop mail client).

3.Periodic Updates:

↳The webpage automatically refreshes or polls every few seconds to check for newly arrived messages from the server.

2. Web-Mail Data Flow Comparison

Traditional Mail Client:

[ Desktop App ] ───(POP3 / IMAP / SMTP)───► [ Mail Server ]

Web-Based Mail (Gmail):

[ Web Browser ] ───(HTTP / HTTPS)────────► [ Web Server ] ──► [ SMTP / Mail Backend ]

FTP (File Transfer Protocol) Overview

1. Key Characteristics & Architecture

File Transfer Protocol (FTP): Designed specifically to upload and download files between a client and a remote server.

1.Out-of-Band Separation:

a)Unlike HTTP (which transfers everything over one connection), FTP strictly uses two separate TCP channels running in parallel.

b)Isolates control commands from raw payload data.

2.Practical Implementation:

Server SideRuns FTP server software (e.g., FileZilla Server / FFS).
Client SideRuns an FTP client program (e.g., FileZilla Client).
ConnectionClient connects using the server's IP address and Port 21.

2. the Dual-Connection Model

1.Control Connection (Port 21):

a)Manages command transmissions and server responses.

b)Handles session setup, directory traversal, and user authentication.

c)Remains persistently open throughout the entire active session.

2.Data Connection (Port 20):

a)Dedicated to transferring actual file content between local and remote disks.

b)Created on-demand per transfer and closed immediately upon completion.

3. Architectural Data Flow Diagram

[ Client ] [ Server ]

┌───────────────────────────┐                     ┌───────────────────────────┐
│       User Interface        │                     │                          │
├───────────────────────────┤                     ├───────────────────────────┤
│      Control Process      │◄── Control (21) ───►│      Control Process      │
├───────────────────────────┤     Commands/Reply  ├───────────────────────────┤
│   Data Transfer Process   │◄──── Data (20) ────►│   Data Transfer Process   │
└─────────────┬─────────────┘     File Content    └─────────────┬─────────────┘
              ▼                                                  ▼

[ Local File System ] [ Remote File System ]

Transport-Layer Protocols Overview

1. Primary Responsibility: Process-To-Process Communication

1.Host-to-Host vs. Process-to-Process:

a)Network Layer (IP) is only responsible for host-to-host delivery (delivering packets from machine A to machine B).

b)However, a single computer typically runs dozens of networked applications simultaneously (e.g., a web browser, a mail client, Spotify, Zoom).

c)Transport Layer extends host-to-host delivery to process-to-process communication, ensuring data reaches the exact running software program/process it was meant for.

d)Transport Layer delivers messages directly between specific running processes (applications) on those hosts.

2.Port Numbers:

a)Serve as end-to-end addressing identifiers at the Transport Layer.

b)Allow the operating system to differentiate between traffic for different programs (e.g., HTTP on port 80, DNS on port 53).

3.Multiplexing & Demultiplexing:

a)Multiplexing : Combining data streams from multiple application processes into network-bound packets.

b)Demultiplexing : Reading destination port headers on incoming packets to direct data to the correct application process.

2. Major Transport-Layer Protocols

1.TCP (Transmission Control Protocol):

a)Connection-oriented (uses 3-way handshakes).

b)Provides reliable, ordered, byte-stream delivery with congestion and flow control.

2.UDP (User Datagram Protocol):

a)Connectionless and minimalist.

b)Unreliable/best-effort datagram delivery with minimal latency overhead (ideal for DNS, video streaming, and real-time gaming).

TCP (Transmission Control Protocol) OVERVIEW

1. Key Characteristics

1.Transmission Control Protocol (TCP): A core protocol operating at the transport layer of the Internet protocol suite.

2.Connection-Oriented & Reliable:

a)Requires a logical connection to be established (via a 3-way handshake) before user data can be exchanged.

b)Guarantees that data arrives intact, in sequence, and without duplication, making it suitable for applications where data loss cannot be tolerated (e.g., HTTP/web browsing, email, file transfers).

3.Mechanisms Used:

a)Flow Control / Sliding Window: Employs sliding window techniques akin to Go-Back-N and Selective Repeat (via TCP Selective Acknowledgment / SACK) to control data transmission rates and avoid overwhelming the receiver.

b)Error Control: Uses a 16-bit Checksum field to detect corrupted bits within the header and payload during transit.

TCP Header Format & Breakdown

Every TCP segment consists of a Header followed by optional Data. The header contains the control metadata needed to ensure reliable, ordered transmission.

•Header Length Limits

Minimum Header Length20 bytes (when no optional fields are present).
Options Field0 to 40 bytes.
Maximum Header Length20 + 40 = 60 bytes.

2. 32-BIT Header Structure (Row-by-row)

0                   1                   2                   3

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1

┌───────────────────────────────┬───────────────────────────────┐ ── 4 Bytes
│     Source Port (16 bits)     │   Destination Port (16 bits)  │
├───────────────────────────────┴───────────────────────────────┤ ── 4 Bytes
│                   Sequence Number (32 bits)                   │
├───────────────────────────────────────────────────────────────┤ ── 4 Bytes
│                Acknowledgment Number (32 bits)                │
├───────┬───────────┬─┬─┬─┬─┬─┬─┬───────────────────────────────┤ ── 4 Bytes
│ HLEN  │ Reserved  │U│A│P│R│S│F│                               │
│(4-bit)│  (6-bit)  │R│C│S│S│Y│I│   Window Size / Adv Window    │
│       │           │G│K│H│T│N│N│           (16 bits)           │
├───────┴───────────┴─┴─┴─┴─┴─┴─┴───────────────────────────────┤ ── 4 Bytes
│       Checksum (16 bits)      │     Urgent Pointer (16 bits)  │
├───────────────────────────────┴───────────────────────────────┤
│                     Options (0 to 40 Bytes)                   │ ── 0-40 Bytes
└───────────────────────────────────────────────────────────────┘

3. 1-BIT Control Flags Breakdown

URG (Urgent)Urgent pointer field is valid
ACK (Acknowledge)Acknowledgment number field is valid
PSH (Push)Request to push buffered data immediately to application
RST (Reset)Abort / reset the connection
SYN (Synchronize)Synchronize sequence numbers (connection setup)
FIN (Finish)Sender has finished sending data (connection termination)

Source Port and Destination Port

1. Port Sizing & Numerical Range

1.Field Sizing : Source Port = 16 bits | Destination Port = 16 bits

2.Total Range : 0 to (2¹⁶ - 1) = 0 to 65,535 total available ports

2. Transport Layer Role & Function

1.End-to-End Delivery:

↳Provides end-to-end(process-to-process) communication between applications/hosts.

2.Process Identification:

↳An IP address only delivers packets to a specific device on a network, while the port number identifies the specific running process/application inside that device that should receive the data.

3.Traffic Handling:

↳Facilitates multiplexing (combining outbound traffic streams) and demultiplexing (routing incoming packets to the correct listening process/application).

3. Port Number Ranges & Allocations

┌─────────────────────────┬───────────────────────┬─────────────────────────┐
│ Category                │ Port Range            │ Standard Purpose        │
├─────────────────────────┼───────────────────────┼─────────────────────────┤
│ Well-Known Ports        │ 0 to 1,023            │ Standard server systems │
│                         │                       │ • HTTP  : Port 80       │
│                         │                       │ • Telnet: Port 23       │
│                         │                       │ • FTP   : Port 21       │
│                         │                       │ • SMTP  : Port 25       │
│ Registered / Reserved   │ 1,024 to 49,151       │ User / vendor services  │
│ General Public / Dynamic│ 49,152 to 65,535      │ Ephemeral client ports  │
└─────────────────────────┴───────────────────────┴─────────────────────────┘

Socket Concepts Overview

1. the Need for Combined Addressing

1.TCP Connection State:

↳Connection-oriented; allocates and reserves memory/buffer resources on both endpoints.

2.Flaw of Port-Only Identification:

↳If two separate remote hosts pick identical port numbers, the server cannot differentiate between their data streams.

3.Flaw of IP-Only Identification:

↳Multiple applications or browser tabs running on the same computer share the same IP address; without port numbers, the system cannot route incoming packets to the correct application.

4.Resolution:

↳Full connection tracking requires a 4-tuple:

[ Source IP, Source Port, Destination IP, Destination Port ]

2. Socket Definition & Sizing

1.Definition:

a)Socket = IP Address + Port Number

b)Represents one complete logical endpoint of a two-way network link.

2.48-Bit Composition (IPv4):

IPv4 Address32 bits
Port Number16 bits
Total Socket32 + 16 = 48 bits

3.Connection Uniqueness:

↳A complete TCP connection is uniquely formed by pairing the Client Socket (48 bits) with the Server Socket (48 bits).

TCP Sequence Number & Acknowledgment Number

1. Key Concepts & Definitions

1.Byte Stream Protocol:

a)TCP does not view data as discrete packets or messages; instead, it sees communication as a continuous stream of bytes.

b)Every single byte transmitted across a TCP connection is assigned an incremental numerical sequence number.

c)Data is handled as an unbroken sequence of bytes; every single byte sent across the connection is uniquely numbered.

2.Initial Sequence Number (ISN):

a)The Sequence Number field in the TCP header is 32 bits long, the possible sequence numbers span from 0 to (2³² - 1), i.e., 0 to 4,294,967,295.

b)A connection does not have to start at 0. During the TCP 3-way handshake (SYN packet), TCP selects a pseudorandom number anywhere within the range of 0 to 4,294,967,295 as the starting ISN.

c)Rather than starting at 0 or 1, TCP generates a pseudorandom ISN during connection setup to prevent collision with lingering packets and mitigate spoofing risks.

3.Sequence Number Rule:

a)A segment header carries only the sequence number of the FIRST byte of data contained in that segment.

b)Example: If a segment carries bytes 100 through 150, the Sequence Number in the header is 100.

4.Acknowledgment Number Rule:

a)The Acknowledgment Number sent by the receiver tells the sender which byte the receiver expects to receive next.

b)Formula: Acknowledgment Number = (Last byte sequence number received + 1).

c)Example: If bytes 100 to 150 are received successfully, the receiver replies with ACK = 151.

2. Practical Transmission Flow

[ Sender ] [ Receiver ]

│                                                            │
├─── TCP Segment: Seq = 100 (Contains Bytes 100 to 150) ────►│
│                                                            │ (Processes bytes
│                                                            │  100 through 150)
│                                                            │
│◄── TCP Segment: ACK = 151 ─────────────────────────────────┤
│    ("I received up to 150; send me byte 151 next")         │
▼                                                            ▼

↑ Back to contents

Chapter 5

Lecture 07 — TCP & UDP: headers, handshake, sequence/ACK numbers + Lab 1 (sockets, CRC, NS-2)

TCP Handshake Establishment

Before any application data can be sent, TCP synchronizes sequence numbers and negotiates connection parameters between the client (using an ephemeral port x) and the server (listening on port 80).

1. the 3-WAY Handshake Workflow

CLIENT (Port x) SERVER (Port 80)

│                                                             │
├───── 1. SYN Request ───────────────────────────────────────►│
│      • Seq = 521, SYN = 1                                   │
│      • MSS = 1460 B, Window = 14600 B                       │
│                                                             │
│◄──── 2. SYN + ACK Reply ────────────────────────────────────┤
│      • Seq = 2000, SYN = 1                                  │
│      • Ack Number = 522 (521 + 1), ACK = 1                  │
│      • MSS = 500 B, Window = 10000 B                        │
│                                                             │
├───── 3. Final ACK ─────────────────────────────────────────►│
│      • Seq = 522                                            │
│      • Ack Number = 2001 (2000 + 1), ACK = 1                │
▼                                                             ▼

[ Connection Established / Ready for Data ]

The Three Packets

Packet 1: Connection Request (SYN Packet)

•Client -> Server

SYN= 1: Signals a request to establish a connection and synchronize sequence numbers.
Seq= 521: Client chooses its Initial Sequence Number (ISN).
MSS= 1460 B: Maximum Segment Size; the maximum data payload (excluding TCP/IP headers) the client is willing to receive.
Window= 14600 B: The client's buffer capacity as a receiver (flow control).

Packet 2: Reply Packet (SYN + ACK Packet)

•Server -> Client

SYN= 1, Seq = 2000: Server synchronizes its own sequence stream and picks its starting ISN (2000).
Ack= 1, Ack = 522: Acknowledges receipt of the client's SYN. Since SYN = 1 consumes one sequence number, the server expects byte 521 + 1 = 522 next.
MSS= 500 B, Window = 10000 B: Server advertises its own receive constraints.

Packet 3: Acknowledgment (ACK Packet)

•Client -> Server

a)Seq = 522: Client begins sending from the expected sequence number (522).

b)Ack = 1, Ack = 2001: Acknowledges receipt of the server's SYN. Since the server's SYN consumed sequence number 2000, the client expects byte 2000 + 1 = 2001 next.

At this point, the full-duplex TCP connection is officially established.

2. Sequence Number Consumption & Acknowledgement Rules

┌────────────────────────────────┬──────────────────────────────────────────┐
│ Event / Flag                   │ Sequence Number Consumption              │
├────────────────────────────────┼──────────────────────────────────────────┤
│ SYN = 1 (Handshake)            │ Consumes 1 sequence number               │
│ FIN = 1 (Teardown)             │ Consumes 1 sequence number               │
│ Data Payload                   │ Consumes 1 sequence number per data byte │
│ Pure ACK (No Data / No SYN/FIN)│ Consumes 0 sequence numbers              │
└────────────────────────────────┴──────────────────────────────────────────┘

SYN = 1 consumes 1 sequence number: Even though a pure SYN packet carries 0 data bytes, it occupies exactly 1 sequence number to guarantee reliable delivery and acknowledgment.

FIN = 1 consumes 1 sequence number: Like SYN, a connection termination flag consumes 1 sequence number.

Each data byte consumes 1 sequence number: If a packet carries N bytes of data, it advances the sequence space by N.

Pure ACK consumes 0 sequence numbers: A packet carrying only Ack = 1 without data payload (and without SYN or FIN flags set) consumes no sequence numbers. Its sequence number will be reused by the next data-bearing packet.

3. Piggybacking vs. Pure Acknowledgment

• Piggybacking:

↳Instead of sending a separate control packet just to acknowledge received data, an endpoint embeds the ACK into an outgoing data segment that is already heading back to the sender.

• Pure Acknowledgment:

↳A standalone packet carrying only an ACK header (Ack = 1) without any user data payload.

TCP Data Transfer & Acknowledgment Flow

Client Server

  │                                                                       │
  ├─── 1. Data (100 B: 522 to 621) ──────────────────────────────────────►│
  │       Seq = 522, ACK = 1, ack = 2001                                  │
  │                                                                       │
  │◄── 2. Data (100 B: 2001 to 2100) + Piggybacked ACK ───────────────────┤
  │       Seq = 2001, ACK = 1, ack = 622 (Acknowledges 522-621)           │
  │                                                                       │
  ├─── 3. Pure ACK (0 Bytes Data) ───────────────────────────────────────►│
  │       Seq = 622, ACK = 1, ack = 2101 (Acknowledges 2001-2100)         │
  │       *Notice: Consumes 0 sequence numbers!                           │
  │                                                                       │
  ├─── 4. Data (100 B: 622 to 721) ──────────────────────────────────────►│
  │       Seq = 622, ACK = 1, ack = 2101                                  │
  │       *Seq remains 622 because previous packet was a Pure ACK         │
  │                                                                       │
  │◄── 5. Data (100 B: 2101 to 2200) + Piggybacked ACK ───────────────────┤
  │       Seq = 2101, ACK = 1, ack = 722 (Acknowledges 622-721)           │
  │                                                                       │
  ├─── 6. Pure ACK (0 Bytes Data) ───────────────────────────────────────►│
  │       Seq = 722, ACK = 1, ack = 2201 (Acknowledges 2101-2200)         │
  ▼                                                                       ▼
Segment 1: Client sends 100 Bytes of Data ──► Server
Data Sent100 bytes (spanning byte numbers 522 through 621).
Seq= 522: Sequence number corresponds to the first byte in this payload.
Ack= 1, ack = 2001: Acknowledges the server's previous handshake, expecting server byte 2001 next.
Segment 2: Server replies with 100 Bytes of Data (Piggybacking) ──► Client
Data Sent100 bytes (spanning byte numbers 2001 through 2100).
Seq= 2001: Begins at expected byte 2001.
Ack= 1, ack = 622: The server successfully received bytes 522 to 621, so it confirms receipt and asks for byte 621 + 1 = 622 next. This is piggybacking because data and acknowledgment are bundled together.
Segment 3: Client sends a Pure ACK ──► Server
Seq= 622: Starts at the current client sequence number.
Ack= 1, ack = 2101: Confirms receipt of the server's 100 bytes (2001 through 2100), requesting byte 2101 next.
Key Rule DemonstrationThis is a Pure ACK (no payload data). As established by TCP rules, a pure ACK consumes 0 sequence numbers.
Segment 4: Client sends next 100 Bytes of Data ──► Server
Data Sent100 bytes (spanning byte numbers 622 through 721).
Seq= 622: Notice that Seq is still 622. Because Segment 3 was a pure ACK, the sequence counter did not advance.
Ack= 1, ack = 2101: Re-states acknowledgment for byte 2101.
Segment 5: Server sends next 100 Bytes of Data ──► Client
Data Sent100 bytes (spanning byte numbers 2101 through 2200).
Seq= 2101: Begins at sequence number 2101.
Ack= 1, ack = 722: Acknowledges the client's bytes 622 to 721, requesting byte 721 + 1 = 722 next.
Segment 6: Client sends another Pure ACK ──► Server

a)Seq = 722: Sequence number for the client.

b)Ack = 1, ack = 2201: Acknowledges receipt of server bytes 2101 through 2200, expecting byte 2201 next. Since this is a pure ACK, it consumes no sequence numbers.

TCP SYN & ACK Flag Combinations

┌─────┬─────┬──────────────────────────┬────────────────────────────────────┐
│ SYN │ ACK │ Meaning                  │ Lifecycle Phase                    │
├─────┼─────┼──────────────────────────┼────────────────────────────────────┤
│  1  │  0  │ First / Request segment  │ Handshake Step 1 (Client SYN)      │
│  1  │  1  │ Second / Reply segment   │ Handshake Step 2 (Server SYN + ACK)│
│  0  │  1  │ Ack present in header    │ Handshake Step 3 & ALL Data        │
│     │     │                          │ Transfer (Pure ACKs + Payloads)    │
│  0  │  0  │ Not possible             │ Invalid during normal transfer     │
└─────┴─────┴──────────────────────────┴────────────────────────────────────┘

Detailed Mapping

Row 1: SYN = 1, ACK = 0 (First Segment / Request Segment)

1.Where it occurs:

↳Step 1 of the 3-Way Handshake.

2.What it does:

↳The client initiates connection setup to synchronize sequence numbers.

3.Why ACK = 0:

↳Because no communication has taken place yet, there is no prior sequence number from the server to acknowledge.

Row 2: SYN = 1, ACK = 1 (Second Segment / Reply Segment)

1.Where it occurs:

↳Step 2 of the 3-Way Handshake.

2.What it does:

↳The server acknowledges the client’s request (ACK = 1) and simultaneously initiates sequence number synchronization for its own stream (SYN = 1).

Row 3: SYN = 0, ACK = 1 (ACK is Present in the Header)

1.Where it occurs:

a)Step 3 of the 3-Way Handshake (the client’s final ACK).

b)All data transfer segments: Every subsequent packet sent during the data transfer phase (both data packets and pure ACK packets) has SYN = 0 and ACK = 1.

2.Why SYN = 0:

↳Synchronization is completed during the handshake; SYN is never set again during active data transfer.

3.Why ACK = 1:

↳Once a TCP connection is established, the Acknowledgment Number field is mandatory and active in every single packet to ensure continuous confirmation of delivered data.

Row 4: SYN = 0, ACK = 0 (Not Possible in Established Communication)

⚠ Correction: Not possible in normal flow, but such segments do exist: a RST answering a non-ACK segment, and attack probes (NULL scan = no flags, FIN scan, Xmas scan) used for port scanning / OS fingerprinting.

•Why it is invalid here:

↳In standard TCP connection lifecycle and data transfer, an unacknowledged non-SYN segment has no operational meaning. A packet cannot begin without SYN, nor can ongoing data transfer proceed without an acknowledgment number (ACK = 1).

TCP Connection Termination (4-WAY Teardown)

Client Server

│                                                                       │
├─── 1. FIN + ACK (Client Initiates Close) ────────────────────────────►│
│       Seq = 722, FIN = 1, ACK = 1, ack = 2201                         │
│       *Client announces: "No more data to send"                       │
│                                                                       │
│◄── 2. Pure ACK (Server Acknowledges Client Close) ────────────────────┤
│       Seq = 2201, ACK = 1, ack = 723 (722 + 1)                        │
│       *Pure ACK: Consumes 0 sequence numbers                          │
│       *Client-to-Server direction is closed                           │
│                                                                       │
│◄── 3. FIN + ACK (Server Initiates Close) ─────────────────────────────┤
│       Seq = 2201, FIN = 1, ACK = 1, ack = 723                         │
│       *Seq remains 2201 because previous packet was a Pure ACK        │
│       *Server announces: "No more data to send"                       │
│                                                                       │
├─── 4. Pure ACK (Client Acknowledges Server Close) ───────────────────►│
│       Seq = 723, ACK = 1, ack = 2202 (2201 + 1)                       │
│       *Pure ACK: Consumes 0 sequence numbers                          │
▼                                                                       ▼

[ Connection Fully Terminated / Closed ]

Key Rules Demonstrated

1.FIN = 1 consumes exactly 1 sequence number.

2.Pure ACKs consume 0 sequence numbers, leaving the sender's Seq unchanged.

3.TCP closure is symmetric (each half-duplex direction is terminated independently).

Q\A Practice

Question 1

A TCP segment contains 1,200 bytes of data and has a sequence number

of 10,000. What acknowledgment number should the receiver send if the

segment arrives correctly?

1. Given Values

1.TCP Sequence Number : 10,000

2.Data Payload Length : 1,200 bytes

2. Step-By-Step Derivation

1.Byte Range in Segment:

a)First Byte = 10,000

b)Last Byte = 10,000 + 1,200 - 1 = 11,199

2.Acknowledgment Number Rule:

a)Cumulative acknowledgment: ACK = (Last Byte Received + 1)

b)Ack Number = 11,199 + 1 = 11,200

(Direct formula: Acknowledge Number = Sequence Number + Data Bytes => 10,000 + 1,200 = 11,200)

Final Answer

Acknowledgment Number = 11,200

Question 2

An IPv4 packet contains a TCP segment with these values:

IP Total Length = 1,500 bytes, IP Header Length = 20 bytes,

TCP Header Length = 20 bytes, TCP Sequence Number = 20,000

Calculate the TCP acknowledgment number.

1. Given Values

IP Total Length1,500 bytes
IP Header Length20 bytes
TCP Header Length20 bytes
TCP Sequence Number20,000

2. Packet Structure & Breakdown (from Diagram)

┌───────────────┬────────────────────────────────────────────────────────┐
│               │                        TCP Segment (1480 bytes)        │
│  IP Header    │ ┌──────────────┬──────────────────────────────────────┐|
│  (20 bytes)   │ |  TCP Header  │          TCP Data Payload            ||
│               │ └──────────────┴──────────────────────────────────────┘│
│            | │◄─ 20 bytes ─►││◄──────────── 1460 bytes ───────────►│|
└───────────────┴────────────────────────────────────────────────────────┘
│◄─ 20 bytes ─►││◄──────────────────── 1480 bytes ──────────────────────►│
│◄───────────────────────────── 1500 bytes ─────────────────────────────►│

3. Step-By-Step Derivation

1.Step 1: Total TCP Segment Size (IP Payload)

a)IP Total Length - IP Header Length

b)1,500 - 20 = 1,480 bytes

2.Step 2: Actual TCP Data Payload Size

a)TCP Segment Size - TCP Header Length

b)1,480 - 20 = 1,460 bytes

3.Step 3: Sequence Numbers in this Segment

a)First Byte Sequence Number = 20,000

b)Last Byte Sequence Number = 20,000 + 1,460 - 1 = 21,459

4.Step 4: TCP Acknowledgment Number

a)Formula: Ack Number = Last Byte Received + 1

b)Ack Number = 21,459 + 1 = 21,460

(Direct Method: Sequence Number + Data Bytes = 20,000 + 1,460 = 21,460)

Final Answer

Acknowledgment Number = 21,460

Question 3

A TCP sender transmits segments with sequence numbers 1001, 2001,

and 3001, each carrying 1000 bytes. If the second segment is lost but

the third arrives, what acknowledgment number will the receiver send?

1. Segment Breakdown

1.Segment 1:

Sequence Number1,001
Data Payload1,000 bytes
Bytes Carried1,001 to 2,000
StatusArrived safely

2.Segment 2:

Sequence Number2,001
Data Payload1,000 bytes
Bytes Carried2,001 to 3,000
StatusLOST in transit

3.Segment 3:

Sequence Number3,001
Data Payload1,000 bytes
Bytes Carried3,001 to 4,000
StatusArrived out of order

2. TCP Acknowledgment Mechanics

1.Cumulative Acknowledgment Principle:

a)In standard TCP, the acknowledgment number indicates the sequence number of the NEXT contiguous, in-order byte expected by the receiver.

b)TCP cannot acknowledge received data beyond a missing gap because ACKs are strictly cumulative.

2.Out-of-Order Handling:

a)When Segment 1 is received, the receiver expects byte 2,001.

b)When Segment 3 arrives out-of-order (bytes 3,001 to 4,000), the receiver buffers it, detects the gap (bytes 2,001 to 3,000 missing), and generates a Duplicate ACK reiterating the byte it is still waiting for.

3. Derivation & Calculation

1.Highest contiguous byte received in order = 2,000

2.Next expected byte = 2,000 + 1 = 2,001

Final Answer

Acknowledgment Number = 2,001

Question 4

During a TCP three-way handshake:

1.The client sends a SYN segment with Seq = 5,000

2.The server replies with a SYN-ACK segment with Seq = 8,000.

Find the sequence number and acknowledgment number of the client’s

final ACK segment.

1. Step-By-Step Handshake Analysis

1.Step 1: Client SYN Segment

Client Initial Sequence Number (ISN)= 5,000
RuleA SYN flag consumes exactly 1 sequence number (SYN = 1).
Sequence number space consumed by client5,000.

2.Step 2: Server SYN-ACK Segment

a)Server Initial Sequence Number (ISN) = 8,000

b)Acknowledgment sent by server:

Ack = Client Seq + 1 = 5,000 + 1 = 5,001

c)Rule: The server's SYN flag also consumes exactly 1 sequence number.

d)Sequence number space consumed by server: 8,000.

3.Step 3: Client Final ACK Segment

a)Sequence Number:

The client must use the sequence number expected by the server, which

is the next byte in its stream:

Seq = 5,000 + 1 = 5,001

b)Acknowledgment Number:

The client must acknowledge receipt of the server's SYN segment:

Ack = Server Seq + 1 = 8,000 + 1 = 8,001

2. Handshake Flow Summary

Client (Port x) Server (Port y)

│                                                                │
├─── 1. SYN (Seq = 5000) ───────────────────────────────────────►│
│                                                                │
│◄── 2. SYN-ACK (Seq = 8000, Ack = 5001) ────────────────────────┤
│                                                                │
├─── 3. Final ACK (Seq = 5001, Ack = 8001) ─────────────────────►│
▼                                                                ▼

Final Answer

1.Sequence Number (Seq) = 5,001

2.Acknowledgment Number (Ack) = 8,001

UDP (User Datagram Protocol) Overview

1. Definition & Origin of Name

1.Full Form:

↳User Datagram Protocol.

2.Name Origin:

↳The Transport Layer receives the datagram from lower layers and delivers it directly to the application/user process without connection overhead, hence the name "User Datagram Protocol".

2. the Need for UDP (Why Not Always TCP?)

1.TCP Overhead Avoidance:

↳In specific applications, TCP's connection establishment (3-way handshake), acknowledgments, and retransmission mechanisms introduce unnecessary delay and protocol overhead.

2.Broadcasting & Multicasting Support:

a)TCP is strictly connection-oriented (point-to-point unicast), which requires allocating and maintaining separate connection resources and state buffers for every single connected host.

b)UDP is connectionless, making it capable of efficient one-to-many broadcasting without per-host resource reservation.

3.Speed Over Reliability:

↳Real-time applications (such as live streaming, DNS lookups, online gaming, and VoIP) prioritize low latency and high speed over guaranteed packet delivery.

3. UDP Header Format & Sizing

1.Total Header Size:

↳Exactly 8 bytes (64 bits) fixed size.

2.Field Breakdown (4 fields × 16 bits each):

┌─────────────────────────────────┬─────────────────────────────────┐
│      Source Port (16 bits)      │   Destination Port (16 bits)    │
├─────────────────────────────────┼─────────────────────────────────┤
│         Length (16 bits)        │        Checksum (16 bits)       │
└─────────────────────────────────┴─────────────────────────────────┘

•Field Functions:

Source Port (16 bits)Port of the sending application process.
Destination Port (16 bits)Port of the destination application process.
Length (16 bits)Total length of the UDP segment (Header + Data). Minimum value = 8 bytes (header only).
Checksum (16 bits)Error detection for header, data, and pseudo-IP header.

Network Protocols

Network Layer Broadcasting

1. Broadcast Address Identifiers

1.Limited Broadcast IP Address : 255.255.255.255

a)Used as the destination IP when a host needs to broadcast a datagram to every host on the local network.

b)Routers do not forward packets addressed to 255.255.255.255, containing the traffic within the local physical segment.

2.Broadcast MAC Address: FF:FF:FF:FF:FF:FF

a)The 48-bit hardware broadcast address used at the Data Link Layer.

b)Instructs every network interface card (NIC) on the shared local link to accept and process the incoming frame.

2. Layer-By-Layer Data Encapsulation

1.Application Layer (AL):

↳Payload: Generates the message payload (m).

2.Transport Layer (TL):

a)Adds header with Source Port (x) and Destination Port (y).

b)Segment: [ m | x | y ]

3.Network Layer (NL):

a)Adds Source IP (I_A) and Destination IP (255.255.255.255).

b)Packet: [ m | x | y | I_A | 255.255.255.255 ]

4.Data Link Layer (DLL):

a)Adds Source MAC (M_A) and Destination MAC (FF:FF:FF:FF:FF:FF).

b)Frame: [ m | x | y | I_A | 255.255.255.255 | M_A | FF:FF:FF:FF:FF:FF ]

5.Physical Layer (PL):

↳Transmits the bit stream across the physical medium/bus.

3. Transmission on Shared Media

1.Shared Bus Topology:

↳The frame travels across the shared medium, reaching every connected host on the local link simultaneously.

2.Network Boundary / Router:

↳Routers terminate and block limited broadcast frames from crossing into external networks, isolating broadcast traffic to the local subnet.

🧪 Lab 1.1–1.2 · TCP/IP stack, TCP vs UDP (merged)

The lab's TCP/IP-stack and TCP-vs-UDP sections duplicate Lectures 05 and 07; only the points not already covered above are kept:

PointDetail
Well-known portsFTP 21 · Telnet 23 · SMTP 25 · DNS 53 (UDP) · HTTP 80 · POP3 110 · HTTPS 443. Socket endpoint = {IP + port}.
Loss detection(1) Retransmission timeout (no cumulative ACK before the timer, e.g. 300 ms); (2) three duplicate ACKs → fast retransmit of the missing segment and slow down.
Flow vs congestion controlFlow control = sender never exceeds the receiver's advertised window. Congestion control = adapts to network capacity (shared bottleneck), growing/shrinking the window with load.
UDP datagram sizeMessage-oriented; maximum IPv4 UDP payload = 65,535 − 20 − 8 = 65,507 B (the lab text's "65,500" is approximate).

🧪 Lab 1.3 · Berkeley Socket Programming Concepts in C/C++

Detailed Conceptual Explanation:

A socket is a logical communication object—analogous to a software "door" or adapter—provided by the underlying OS kernel between user-space applications and kernel-space Transport Layer protocols.

1.Unique Socket Identification:

a)Network-wide: Uniquely identified by the tuple {Protocol, Local IP, Local Port, Remote IP, Remote Port}.

b)Locally inside C/UNIX: Represented as a non-negative integer file descriptor (sockid, where >= 0 indicates success and -1 indicates failure).

2.Client vs. Server Dual-Socket Architecture:

a)Client Socket (Active Socket): Initiates communication; uses ONE socket to connect to the server and both send and receive data.

b)Server Sockets (1 Passive Connection Socket + N Data Sockets):

1.Connection (Listening) Socket: Only ONE is created per server service. Bound to a known port (e.g., 8080); passively listens for incoming client connection requests and places them into a pending queue. It NEVER transfers user data.

2.Data Socket: Created dynamically by accept() for EACH accepted client. For example, if 1,000 students check exam results simultaneously on a server configured to serve 100 concurrent clients, the server uses 1 Connection Socket (queuing the remaining 900 requests) and spawns 100 separate Data Sockets (via fork() processes or threads) to transfer result PDFs in parallel.

3.Core TCP Socket System Calls (Step-by-Step C Execution Flow):

1.int sockid = socket(family, type, protocol);

–Allocates a new communication endpoint in the OS kernel.

family (Address Domain)PF_INET / AF_INET (IPv4 dotted-decimal internet addresses) or PF_UNIX (local inter-process communication between two programs on the same machine using file paths/pipes).
typeSOCK_STREAM (reliable 2-way TCP byte stream) or SOCK_DGRAM (unreliable connectionless UDP datagrams).
protocolUsually set to 0 (auto-selects IPPROTO_TCP or IPPROTO_UDP).

2.int status = bind(sockid, (struct sockaddr *)&addrport, sizeof(addrport));

–Server-side call associating the listening socket with a local IP (INADDR_ANY, which binds to any network interface on the host) and a 16-bit port number converted from host byte order to network big-endian byte order using htons(PORT) (Host-to-Network Short).

3.int status = listen(sockid, queueLimit);

–Non-blocking server call marking the socket as passive and defining the maximum queue size (queueLimit, e.g., 3 or 100) of pending client connection requests. Excess requests beyond queueLimit fail.

4.int status = connect(sockid, (struct sockaddr *)&foreignAddr, addrlen);

–Blocking client call initiating the TCP 3-way handshake toward the server's IP (converted from text to binary via inet_pton()) and port.

5.int new_socket = accept(sockid, (struct sockaddr *)&clientAddr, &addrLen);

–Blocking server call (the Synchronization Point). Dequeues the next pending client request from the listening socket, fills clientAddr with the client's IP/port, and returns a NEW integer descriptor (new_socket, the Data Socket) used for all data transfer.

6.send(sockid, msg, msgLen, flags) / write() and recv(sockid, buf, bufLen, flags) / read():

–Blocking calls that transmit and receive raw byte streams over the connected socket. Returns the exact byte count transferred (0 means peer closed connection; -1 means error).

7.close(sockid);

–Terminates the TCP connection (FIN handshake) and frees the OS descriptor.

4.UDP Socket Calls (Connectionless):

–Uses sendto(sockid, msg, len, flags, &foreignAddr, addrlen) and recvfrom(sockid, buf, len, flags, &clientAddr, &addrlen) because there is no persistent connection; destination/source addresses must be passed on every packet. listen(), accept(), and connect() are omitted.

5.Advanced Socket Handling Techniques:

Non-Blocking SocketsCalling fcntl(sockid, F_SETFL, O_NONBLOCK) (or passing MSG_DONTWAIT) prevents socket calls from freezing the process; if an operation cannot complete immediately, it returns -1 and sets errno to EWOULDBLOCK or EINPROGRESS.
Asynchronous I/OUses sigaction() and fcntl(sock, F_SETFL, O_NONBLOCK | FASYNC) so the OS kernel sends a SIGIO signal whenever socket data arrives.
Timeoutsalarm(secs) schedules a SIGALRM signal after secs seconds (errno = EINTR), preventing UDP recvfrom() from waiting forever on lost packets.

a)Multi-Client Concurrency:

1.Multi-Process (fork()): Parent server calls fork() after accept(); the child process (pid == 0) closes the listening socket, serves the client on clntSock, and exits, while the parent closes clntSock and loops back to accept(). Uses waitpid(-1, NULL, WNOHANG) to clean up terminated child "zombie" processes.

2.Multi-Threading (std::thread / pthread): Spawns lightweight threads sharing the same memory address space.

b)Multiple Recipients (UDP Only):

1.Broadcast: Sends one packet to 255.255.255.255 (local broadcast) or directed subnet broadcast (e.g., 169.125.255.255); requires enabling SO_BROADCAST via setsockopt().

2.Multicast: Sends one stream to a Class D IP group (224.0.0.0 to 239.255.255.255) using Time-To-Live (TTL) to limit router hops.

Real-World Example:

Think of a busy bank call center (the Server) with one published customer helpline number (Port 8080 / Connection Socket). When you (the Client) dial that number (connect()), the automated switchboard (listen()) places you in a hold queue and routes you to an available support agent on a private internal extension line (accept() creating a Data Socket). You and the agent now converse privately on that extension while the main helpline number stays free to receive the next caller.

⚠ Correction: listen(): on Linux, connection requests beyond the queue are not "failed" instantly — the SYN is dropped/ignored and the client retransmits.

🧪 Lab 1.4 · Lab Experiment 1A: TCP Client-Server File Transfer (ft_server.c & ft_client.c)

Detailed Walkthrough:

1.Objective: Transfer an arbitrary binary/text file (stalling.pdf or Auditorium.jpeg) from a client program to a server program over TCP Port 8080.

2.Server Code (ft_server.c):

1.Creates TCP socket (socket(AF_INET, SOCK_STREAM, 0)), binds to INADDR_ANY on PORT 8080, and calls listen(server_fd, 3).

2.Blocks at new_socket = accept(...) until the client connects.

3.Opens an empty target file on disk in write-binary mode:

fp = fopen("new_network.jpeg", "wb").

4.Loops reading chunks from the socket and writing to disk:

while ((n = read(new_socket, buffer, MAX)) > 0) { fwrite(buffer, sizeof(char), n, fp); }

5.Closes fp, new_socket, and server_fd.

3.Client Code (ft_client.c):

1.Creates TCP socket, converts "127.0.0.1" via inet_pton(), and calls connect() to port 8080.

2.Opens the local source file in read-binary mode:

fp = fopen("Auditorium.jpeg", "rb").

3.Loops reading chunks from disk and transmitting over the socket:

while ((n = fread(buffer, sizeof(char), MAX, fp)) > 0) { send(sock, buffer, n, 0); }

4.Closes fp and sock.

4.Key Takeaway: Because TCP transfers raw byte streams (character/byte-by-byte), the server needs zero knowledge of PDF formatting or JPEG image headers; saving the received bytes with the proper file extension reconstructs the exact file.

Real-World Example:

This exact chunked fread() -> send() / recv() -> fwrite() mechanism is how scp (Secure Copy), FTP uploads, and web portal document submissions transfer resumes, images, and software packages bit-for-bit across the internet.

🧪 Lab 1.5 · Lab Experiment 1B: Cyclic Redundancy Check (CRC) Error Detection

Detailed Walkthrough:

1.Purpose & Hardware Context:

a)CRC detects accidental bit-flip errors caused by physical channel noise, interference, or faulty hardware (distinct from cryptographic hashes, which protect against intentional tampering).

b)In real Ethernet Network Interface Cards (NICs), CRC is hardcoded directly into silicon using Linear Feedback Shift Registers (LFSR) with a fixed Generator Polynomial G(x). Both sender and receiver must use the exact same generator polynomial.

2.Mathematical Mechanism (Modulo-2 Arithmetic in GF(2)):

a)In GF(2), addition and subtraction are both bitwise XOR (no carries/borrows).

b)Generator Polynomial in Lab Code: g[] = "1101" (degree = 3, length N = 4).

c)Sender (server_crc.c):

1.Reads input binary string t of length a (e.g., 7 bits).

2.Appends N - 1 (3) zeros to t.

3.Performs modulo-2 XOR division (xor() whenever cs[0] == '1') using g = "1101" to obtain a 3-bit remainder (cs, e.g., "001").

4.Replaces the appended zeros with the 3-bit checksum to form the final 10-bit codeword (a + N - 1 bits).

5.Error Injection Menu:

a)Option 1 (Correct Data): Sends the clean codeword untouched.

b)Option 0 (Erroneous Data): Prompts for a bit position e and flips t[e-1] ('0' <-> '1') to simulate physical channel noise before send().

d)Receiver (client_crc.c):

1.Reads the received 10-bit codeword via read().

2.Executes the exact same crc() modulo-2 division algorithm using g = "1101".

3.Checks the 3-bit remainder:

a)All zeros ("000"): Result = No error detected.

b)Any '1' bit present (e.g., "100"): Result = Error detected (triggers retransmission in ARQ protocols).

Real-World Example:

Every Ethernet frame transmitted over your home Wi-Fi or office LAN cable ends with a 32-bit CRC-32 Frame Check Sequence computed in hardware by the NIC. If electrical interference from a motor or loose cable flips even one bit in flight, the receiving switch computes a non-zero CRC remainder and discards the damaged frame immediately.

🧪 Lab 1.6 · NS-2 (Network Simulator Version 2) Overview

Detailed Walkthrough:

1.Dual-Language Architecture:

a)C++ Core: Implements event schedulers, packet forwarding, and queue drop policies (DropTail, RED) for fast execution.

b)OTcl (Object Tcl) Scripting Layer: Configures network topologies, link parameters, and simulation schedules without recompiling C++.

2.Standard 8-Step NS-2 Script Structure:

1.Create Simulator: set ns [new Simulator]

2.Enable Tracing: Open .tr/.nam files (set nf [open out.nam w]; $ns trace-all $nf; $ns namtrace-all $nf). Trace columns record:

event (+ enqueue, - dequeue, r receive, d drop) | time | from_node | to_node | pkt_type | pkt_size | flags | fid | src_addr | dst_addr | seq_num | pkt_id.

Create TopologyDefine nodes (set n0 [$ns node]) and links ($ns duplex-link $n0 $n1 1Mb 10ms DropTail).
Setup Link DynamicsSchedule link failures/recoveries ($ns rtmodel-at 1.0 down $n0 $n1).
Create Transport AgentsPair Agent/TCP with Agent/TCPSink, or Agent/UDP with Agent/Null.
Attach Traffic SourcesBind Application/FTP / Application/Telnet to TCP, or Application/Traffic/CBR (Constant Bit Rate) to UDP.
Post-Processing (proc finish {})Flush traces, close files, launch NAM.
Schedule Events & Run$ns at 0.5 "$cbr start", $ns at 5.0 "finish", $ns run.

Real-World Example:

Before rolling out a new routing protocol or upgrading bandwidth across a university campus backbone, network engineers simulate the exact node-and-link topology in NS-2/NS-3 to observe packet queue drops in NAM and plot throughput in Xgraph under simulated link failures.

↑ Back to contents

Chapter 6

Lecture 09 — ARP, BOOTP, DHCP, ICMP · Security concepts (CIA, X.800, attack types)

Address Resolution Protocol (ARP)

1. Purpose & Layer Placement

1.Primary Function:

↳Converts a known logical IP address into a physical MAC address.

2.OSI Position:

a)Sits between the Network Layer (IP) and the Data Link Layer.

b)An IP packet moves down toward ARP, which resolves the target hardware address before passing the frame to the Data Link Layer for physical delivery.

2. ARP Request (Broadcast)

1.Scenario (Host A wants to send data to Host B):

↳Host A knows the destination IP address (I_B) but does not know the physical hardware MAC address (M_B) of Host B.

2.Packet / Frame Structure:

┌───────────┬──────────────────────┬────────────┬─────────────────────────────┐
│ I_B       │   ? (Query Target)   │    M_A     │     FF:FF:FF:FF:FF:FF       │
├───────────┼──────────────────────┼────────────┼─────────────────────────────┤
│ Target IP | "What is MAC of B?"  │ Source MAC │ Destination MAC (Broadcast) │
└───────────┴──────────────────────┴────────────┴─────────────────────────────┘

•Delivery Type:

a)BROADCAST.

b)Destination MAC is set to FF:FF:FF:FF:FF:FF so every device on the shared local network receives and examines the query.

3. ARP Reply (Unicast)

1.Response from Target (Host B):

a)Only Host B recognizes its own IP address (I_B) within the request payload; all other hosts drop the frame.

b)Host B forms a reply containing its physical hardware address (M_B).

2.Packet / Frame Structure:

┌────────────┬─────────────────┬───────────┬─────────────────────────────┐
│    M_B     │       M_A       │    I_A    │             M_B             │
├────────────┼─────────────────┼───────────┼─────────────────────────────┤
│ Source MAC │ Destination MAC │ Target IP │     MAC Address of Host B   │
└────────────┴─────────────────┴───────────┴─────────────────────────────┘

•Delivery Type:

a)UNICAST.

b)Sent directly back to Host A using M_A as the Destination MAC.

4. Key Takeaways

1.ARP Request ──► Broadcast (FF:FF:FF:FF:FF:FF)

2.ARP Reply ──► Unicast (Direct to requester's MAC)

BOOTP (Bootstrap Protocol)

1. Purpose & Overview

1.Protocol Definition:

↳Bootstrap Protocol (BOOTP) is a host configuration protocol used by a client to discover and obtain its IP address and configuration parameters automatically upon booting up.

2.Transport Protocol:

↳Operates over UDP (Client uses port 68, Server uses port 67).

2. Packet Encapsulation (BOOTP Request)

1.Application Layer (AL):

↳Generates the BOOTP request message (m).

2.Transport Layer (TL):

↳Encapsulates message (m) with UDP header containing source and destination ports.

3.Network Layer (NL):

a)Source IP : 0.0.0.0 (The client does not yet possess an IP address).

b)Destination IP : 255.255.255.255 (Limited broadcast to all local hosts).

4.Data Link Layer (DLL):

a)Source MAC : M_A (Hardware MAC address burned into client's NIC).

b)Destination MAC : FF:FF:FF:FF:FF:FF (Broadcast MAC address).

5.Physical Layer (PL):

↳Transmits the bitstream across the physical network medium.

1. Layer-By-Layer Encapsulation

AL [ m ]

TL [ m | 68 | 67 ] (UDP: Source Port 68, Destination Port 67)

NL [ m | 68 | 67 | 0.0.0.0 | 255.255.255.255 ]

│                │
▼                ▼

Unknown Source IP Destination IP

(Limited Broadcast)

DLL [ m | 68 | 67 | 0.0.0.0 | 255.255.255.255 | M_A | FF:FF:FF:FF:FF:FF ]

│              │
▼              ▼

Source MAC Destination MAC

(Broadcast MAC)

PL   [══════════════════════════════════════════════════════════════════════]
                                   │
                                   ▼ (Physical Bitstream)

2. Network Topology & Relay Agent

Subnet 1 (Local Segment) Other Subnets

                                            ┌──○──○──○──○──○ (Subnet 2)
 ──┬─────┬─────┬─────┬─────────┐            │
   │     │     │     │         │          ┌─┘
   ○     ○     ○     ○         ○          │
 Client             BootP    Router       ├────○───○───●───○ (Subnet 3)
(Source)            Server    [⨂]──┼───┤            │
                                          │       Relay Agent
                                          │         (Proxy)
                                             └─┐
                                        └──○──○──○──○──○ (Subnet 4)

3. Static Mapping Table (BOOTP Server)

• Table Structure

**┌─────────────┬─────────────┐**
**│     MAC     │      IP     │**
**├─────────────┼─────────────┤**
**│**      M₁     **│**      I₁     **│**
**│**      M₂     **│**      I₂     **│**
**│**      M₃     **│**      I₃     **│**
**└─────────────┴─────────────┘**

•Mechanism:

a)The network administrator manually configures a fixed, static binding table on the BOOTP server linking each device's MAC to an assigned IP.

b)When the server receives the request, it looks up M_A in its table and returns the pre-allocated IP address (I_A).

4. Relay Agent Across Routers

1.The Problem:

a)Routers (marked with ⨂) block limited broadcast (255.255.255.255) packets by default to prevent broadcast storms across subnets.

b)A BOOTP request cannot naturally cross into another subnet to reach a central server.

2.The Solution (Relay Agent):

a)A Relay Agent (indicated by the solid node) listens for local broadcasts on its subnet and forwards them as unicast packets across the router directly to the remote BOOTP server.

b)This eliminates the need to deploy a dedicated BOOTP server on every single physical subnet.

BOOTP Protocol & Relay Agent

1. Core Characteristics

1.Address Mapping:

↳Converts a physical MAC address to a logical IP address.

2.Layer Placement:

↳Operates at the Application Layer.

3.Transmission Types:

a)BOOTP Request is a Broadcast.

b)BOOTP Reply is a Unicast.

2. Multi-Network Deployment & Relay Agents

1.Requirement:

↳If a network segment does not host a local BOOTP server, it must have a Relay Agent configured.

2.Architectural Design:

↳Only one central network contains the BOOTP server; all other network subnets deploy Relay Agents.

3. End-To-End Communication Workflow

1.Host Broadcast:

↳The booting host broadcasts a BOOTP request within its local network segment.

2.Relay Agent Interception & Forwarding:

a)The Relay Agent intercepts the local broadcast packet.

b)Because the Relay Agent already knows the IP address of the BOOTP server, it forwards the request across intermediate routers as a Unicast packet.

3.Server Processing & Return Path:

a)The BOOTP server resolves the client's MAC address and generates the assigned IP.

b)The server routes the assigned configuration back to the Relay Agent as a Unicast packet via the router.

4.Final Delivery to Client:

↳The Relay Agent receives the reply from the server and delivers the final Unicast reply directly to the requesting host.

4. Packet Flow Summary

Client                  Relay Agent                 Router                 Bootp Server
  │                          │                         │                         │
  ├── 1. Request (Broadcast)►│                         │                         │
  │                          ├─── 2. Request (Unicast)►│────────────────────────►│
  │                          │                         │                         │
  │                          │◄── 3. Reply (Unicast) ──│◄────────────────────────┤
  │◄─ 4. Reply (Unicast) ────┤                         │                         │
  ▼                          ▼                         ▼                         ▼

DHCP (Dynamic Host Configuration Protocol)

1. Overview & Advancement Over BOOTP

1.Full Form:

↳Dynamic Host Configuration Protocol.

2.Nature of Allocation:

a)Unlike BOOTP (which relies strictly on a fixed, static table), DHCP supports both static and dynamic IP assignment.

b)IP addresses are maintained in an IP address pool and leased dynamically to requesting clients.

2. DHCP Server Table Structure

The DHCP server maintains two distinct allocation tables:

•(a) Static Allocation Table:

a)Fixed MAC-to-IP binding configured by a network administrator.

b)Reserved for mission-critical nodes that must remain permanently reachable and online (e.g., web servers, DNS servers, print servers, gateway routers).

**┌─────────────┬─────────────┐**
**│     MAC     │      IP     │**
**├─────────────┼─────────────┤**
**│**      M₁     **│**      I₁     **│**
**│**      M₂     **│**      I₂     **│**
**│**      M₃     **│**      I₃     **│**
**└─────────────┴─────────────┘**

•(b) Dynamic Allocation Table (Pool-Based Leasing):

a)Unassigned IP addresses reside in a shared "Pool of IP".

b)When a client requests an IP, DHCP pulls an available IP from the pool and assigns it temporarily with a specific "Lease Time" (e.g., 10 minutes).

c)If the device needs the address past the lease expiration, it must send a renewal request. If expired without renewal, the IP returns to the pool.

**┌─────────────┬─────────────┬─────────────┐**
**│     MAC     │      IP     │ Lease Time  |**
**├─────────────┼─────────────┼─────────────┤**
**│**      M_A    **│**     I_A     **│**    10 min   **│**
**└─────────────┴─────────────┴─────────────┘**

3. Layer-By-Layer Packet Encapsulation (DHCP Discover / Request)

AL [ m ]

TL [ m | 68 | 67 ] (UDP: Source Port 68, Destination Port 67)

NL [ m | 68 | 67 | 0.0.0.0 | 255.255.255.255 ]

│                │
▼                ▼

Unknown Source IP Destination IP

(Limited Broadcast)

DLL [ m | 68 | 67 | 0.0.0.0 | 255.255.255.255 | M_A | FF:FF:FF:FF:FF:FF ]

│              │
▼              ▼

Source MAC Destination MAC

(Broadcast MAC)

PL   [══════════════════════════════════════════════════════════════════════]
                                   │
                                   ▼ (Physical Bitstream)

4. Network Topology & Relay Agent Functionality

1.Local Subnet:

a)The client sends an initial broadcast frame (Destination MAC: FF:FF:FF:FF:FF:FF, Destination IP: 255.255.255.255).

b)The local DHCP server responds directly if located on the same segment.

2.Multi-Subnet Architecture:

a)Routers [⨂] drop 255.255.255.255 limited broadcast packets by default.

b)Subnets without a dedicated DHCP server employ a Relay Agent (solid node ●).

c)The Relay Agent intercepts client broadcasts and forwards them as Unicast packets across the router directly to the centralized DHCP server. Subnet 1 (Local Segment) Other Subnets

                                            ┌──○──○──○──○──○ (Subnet 2)
 ──┬─────┬─────┬─────┬─────────┐            │
   │     │     │     │         │          ┌─┘
   ○     ○     ○     ○         ○          │
 Client             DHCP     Router       ├────○───○───●───○ (Subnet 3)
(Source)            Server    [⨂]──┼───┤            │
                                          │       Relay Agent
                                          │         (Proxy)
                                             └─┐
                                        └──○──○──○──○──○ (Subnet 4)

Internet Control Message Protocol (ICMP)

1. Role & Core Purpose

1.Protocol Role:

↳Acts as the companion/assistant to the IP protocol at the Network Layer.

2.Error Handling:

a)Generates and transmits error reports back to the source host whenever an issue occurs during packet transit.

b)If an IP datagram is lost, dropped, or encounters delivery failure, ICMP delivers an error notification response. ✕

    ───►          ───►          ───►   (Drop)
┌───────┐     ┌───────┐     ┌───────┐     ┌───────┐     ┌───────┐
│ ( S ) │─────│ ( X ) │─────│ ( X ) │─────│ ( X ) │─────│ ( R ) |
└───────┘     └───────┘     └───────┘     └───────┘     └───────┘
                 R₁            R₂            R₃
                                ▲             │
                                │             │
                                └─────────────┘

icmp(R₃,S)

2. Feedback & Error Messaging Types

1.TTL Exceeded:

↳Sent when a packet's Time-to-Live counter decrements to 0, terminating routing loops.

2.Source Quench:

↳Flow control and congestion feedback requesting the sender to reduce its transmission rate.

3.Parameter Problem:

↳Dispatched if a router or destination host discovers ambiguous or invalid fields within the IP header.

4.Destination Unreachable:

↳Generated when a packet cannot be routed or delivered to its specified network, host, protocol, or port.

3. Request and Reply Mechanism

1.Diagnostic Reachability:

↳Uses query/response pairs (such as Echo Request and Echo Reply in 'ping') to test end-to-end connectivity.

2.Layer Health Verification:

↳Verifies whether the network layer of the target destination device and intermediate devices are active, functioning, and responsive.

ICMP Error Handling Mechanism

1. Core Rules of ICMP Error Reporting

•Obligation of the Discarding Node:

↳Any intermediate router or destination host that discards an IP packet must generate and send an ICMP error message back to the original

⚠ Correction: Not always: no ICMP error is generated for an ICMP error message, a non-first fragment, multicast/broadcast or special addresses, and routers rate-limit ICMP.

Source host (S).

•Prevention of Infinite Error Loops (No ICMP for ICMP):

a)When an ordinary IP packet is discarded, an ICMP error packet is generated.

b)If an ICMP packet itself is dropped or discarded during transit, NO new ICMP packet is generated.

c)Reason: Generating error packets for failed error packets would risk triggering runaway network congestion and infinite broadcast loops.

2. Topology & Error Flow Diagram

     Forward IP Path (S ──► R)
 ─────────────────────────────────►
( S ) ───► ( R₁ ) ───► ( R₂ ) ───► ( R₃ ) ─ ✕ ─► ( R )
  ▲                                  │    (Dropped)
  │                                  │
  └──────── icmp(R₃, S) ─────────────┘

(ICMP Error Return Path)

3. Step-By-Step Transmission Breakdown

1.Step 1: Forward Transit

a)Source host (S) initiates transmission intended for Receiver (R).

b)The datagram traverses intermediate routers R₁ and R₂ successfully.

2.Step 2: Packet Drop at Router R₃

↳Router R₃ discards the IP datagram (e.g., due to buffer exhaustion, TTL expiry, or MTU/routing issues).

3.Step 3: Generation of ICMP Error Message

a)Upon discarding the packet, R₃ constructs an ICMP error report:

1.Source IP of ICMP packet : R₃ (IP of Router R₃)

2.Destination IP of ICMP packet : S (IP of original Source host S)

b)Notation: icmp(R₃, S) represents an ICMP packet originating at R₃ and routed back to Source S.

ICMP: TTL Exceed & Source Quench

1. TTL Exceed (Time Exceeded)

1.Definition & Rule:

a)Whenever the Time-to-Live (TTL) field decrements to 0 before the packet reaches its final destination, the station/router must discard the IP packet and send an ICMP "Time Exceeded" error message back to the Source.

b)Primary purpose: Prevents packets from circulating indefinitely inside routing loops.

2.Step-by-Step Hop Degradation:

S (Source)Transmits an IP packet initialized with TTL = 2.
Router R₁Receives packet, decrements TTL from 2 to 1, and forwards it.
Router R₂Receives packet, decrements TTL from 1 to 0. Because TTL hits 0 and R₂ is not the destination, R₂ discards the packet and generates an ICMP error message directed back to Source S.

3.Visual Topology & Flow:

 TTL = 2               TTL = 1 (2-1)         TTL = 0 (1-1)
┌───────┐             ┌─────────────┐       ┌─────────────┐
│ ( S ) │ ──────────► │    ( R₁ )   │ ────► │    ( R₂ )   │
└───────┘             └─────────────┘       └─────────────┘
    ▲                        ▲                     │ (Packet Discarded)
    │                        │                     │
    └──────────────── ICMP Error ──────────────────┘

(Routed back hop-by-hop to Source)

2. Source Quench

•Definition & Mechanism:

a)Acts as a feedback and congestion control mechanism.

b)If a sending node (e.g., R₁) transmits a high volume of packets to a receiving router (e.g., R₂) exceeding its processing capacity or buffer limits, R₂ sends an ICMP Source Quench [ICMP(SQ)] message back to R₁.

⚠ Correction: Per Forouzan / RFC 792 the Source Quench goes to the original source host (ICMP always reports to the source), not to R₁. Source Quench is also deprecated (RFC 6633).

↳Primary purpose: Requests the transmitting station to slow down its rate of transmission to relieve buffer overflow and prevent dropped packets.

•Visual Topology & Flow:

High Volume Packet Stream

             ┌───────────────────────────┐
             │  ────────►   ────────►    │
             │  ────────►   ────────►    │
┌───────┐    │                           ▼    ┌───────┐
│ ( S ) │ ───┤          ( R₁ ) ─────────────► │( R₂ ) │
└───────┘    │                                │ Buffer│
             │          ( R₁ ) ◄───────────── │ Full  │
             │                   ICMP(SQ)     └───────┘
             └───────────────────────────────────┘

(Slow down request)

ICMP Request and Reply Message

1. Purpose & Functionality

1.Destination Health Check:

↳Echo Request and Echo Reply messages are used to check whether the Network Layer of the destination device is operational and reachable.

2.Implementation in Diagnostic Tools:

↳The "Ping" command utility is implemented using ICMP Echo Request and Echo Reply.

2. OSI Protocol Stack & Intermediate Routers

1.End Systems (Hosts A and B):

↳Full 5-layer stack present: Application Layer (AL), Transport Layer (TL), Network Layer (NL), Data Link Layer (DLL), and Physical Layer (PL).

2.Intermediate Routers (Nodes X):

a)Operate only up to the Network Layer (NL), utilizing Physical Layer (PL), Data Link Layer (DLL), and Network Layer (NL).

b)Routers do not process Transport (TL) or Application (AL) layers.

3. Layer Stack and Topology Diagram

 Host A                 Router 1              Router 2               Host B
┌──────┐                                                            ┌──────┐
│  AL  │                                                            │  AL  │
│  TL  │                                                            │  TL  │
│  NL  │                ┌──────┐              ┌──────┐              │  NL  │
│ DLL  │                │  NL  │              │  NL  │              │ DLL  │
│  PL  │                │ DLL  │              │ DLL  │              │  PL  │
└──┬───┘                │  PL  │              │  PL  │              └──┬───┘
   │                    └──┬───┘              └──┬───┘                 │
  (A) ──────────────────── (X) ────────────────── (X) ──────────────── (B)
   │                                                                   ▲
   └──────────────────── ICMP Echo Request ────────────────────────────┤
   │                                                                   │
   │◄─────────────────── ICMP Echo Reply ──────────────────────────────┘

4. Core Takeaway

•Reachability Scope:

↳A successful ICMP Echo Reply confirms end-to-end Network Layer (NL) connectivity between the source and the target host, verifying that intermediate routing is fully functional.

Types of Attacks

1. Case 1: Passive Attack / Eavesdropping (Snooping / Interception)

1.Attack Category:

↳Passive Attack (Violation of Confidentiality).

2.Mechanism:

a)Host A transmits sensitive data across a communication link to Host B.

b)An unauthorized third party (C) intercepts and captures a copy of the data in transit without modifying the original transmission.

c)Host B receives the message unaware that it has been read or duplicated.

3.Diagram:

[ Sensitive Data ]

A ──────────────────────────────────────────► B (Authorized)

\ Transmission

\

\ - - - - - - - - - - ┐ (Unauthorized Access)
                      ▼
                   [ Copy ] ──► C (Unauthorized Eavesdropper)

2. Case 2: Active Attack - Modification (Interception & Alteration)

1.Attack Category:

↳Active Attack (Violation of Integrity).

2.Mechanism:

↳Network Manager (D) transmits a legitimate command intended for Server (E):

"Authorization File Update (ADD User G, ADD User H)".

↳Attacker (F) performs unauthorized interception of the packet, alters its contents to:

"Authorization File Update (ADD User I)",

and forwards the altered message to Server (E).

↳Server (E) accepts the message believing it originated directly from D, resulting in unauthorized modifications to its database.

•Diagram:

[ Management Command: Add G, Add H ]

D ───────────────\
                  - - - -► [ Intercepted ]
                                 │
                                 ▼

F (Attacker)

│
▼ [ Altered: Add User I ]
└────────────────────────► E (Server)

(Accepts as from D)

3. Case 3: Active Attack - Fabrication (Spoofing / Forgery)

1.Attack Category:

↳Active Attack (Violation of Authenticity / Integrity).

2.Mechanism:

a)Network Manager (D) does NOT transmit any message across the network (the transmission path remains silent).

b)Attacker (F) independently generates/fabricates a forged message:

"Authorization File Update (ADD User G, ADD User H, ADD User I)".

a)Attacker (F) attaches a forged sender identity claiming to be Manager (D) and injects the spurious packet toward Server (E).

b)Server (E) validates the forged sender identity, accepts the packet as if it came from D, and updates its authorization file.

•Diagram:

D (Silent / Not Sent)

· · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·► E (Server)
                                                            ▲
                                 F (Attacker)               │
                                 │                          │
                                 ▼                          │
                   [ Fabricated Message + Forged ID(D) ] ───┘

Computer Security Concepts

1. the CIA Triad & Extended Security Model

1.Core CIA Triad Objectives:

a)Confidentiality

b)Integrity

c)Availability

2.Extended Concepts:

↳While the CIA triad defines the core foundation, complete information and network security requires two additional objectives:

1.Authentication

2.Accountability

3.Pentagon Relationship Model:

┌─────────────────────────┐
│      CONFIDENTIALITY    │
│       (plus privacy)    │
└────────────┬────────────┘

/ \

/ \

/ \

┌────────────────────────┐       ┌────────────────────────┐
│     ACCOUNTABILITY     │       │       INTEGRITY        │
│                        │       │ (plus data authenticity│
│                        │       │   & non-repudiation)   │
└───────────┬────────────┘       └───────────┬────────────┘

\ /

\ Information & Network /

\        SECURITY           /

\ /

┌───────────────────────┐
│     AVAILABILITY      │
│    & AUTHENTICITY     │
└───────────────────────┘

2. Confidentiality

1.Data Confidentiality:

↳Assures that private or confidential information is not made available or disclosed to unauthorized individuals.

2.Privacy:

↳Assures that individuals maintain control over what personal information related to them can be collected and stored, as well as who collects it and to whom that information may be disclosed.

3. Integrity

1.Data Integrity:

↳Assures that information (both stored on disk and in transmission over a network) can be changed or modified only in a specified and authorized manner.

2.System Integrity:

↳Assures that a computer or network system performs its intended function in an expected, desired manner, completely free from unauthorized manipulation.

4. Authentication & Accountability

1.Authentication:

a)Verifies that users are truly who they claim to be.

b)Confirms that every input, request, or packet arriving at the system originates from an authentic, trusted source.

2.Accountability:

a)Generates the operational requirement that every action performed on a system can be traced uniquely and conclusively to the responsible entity.

b)Directly supports:

1.Non-repudiation (preventing a party from denying their actions)

2.Fault isolation and diagnostic debugging

3.Intrusion detection and prevention

4.After-action recovery, forensics, and legal action

Security Attacks & Taxonomy

1. Broad Classification of Security Attacks

1.Passive Attack:

a)Attempts to learn or make use of information from the system, but does NOT affect or alter system resources.

b)Focuses on snooping, eavesdropping, and monitoring transmissions.

2.Active Attack:

a)Attempts to alter system resources or affect their normal operation.

b)Involves data modification, message replay, unauthorized access, or disruption.

3.Classification Overview:

┌───────────────────────────────┐     ┌───────────────────────────────┐
│        PASSIVE ATTACKS        │     │        ACTIVE ATTACKS         │
├───────────────────────────────┤     ├───────────────────────────────┤
│ • Release of message contents │     │ • Replay                      │
│ • Traffic analysis            │     │ • Data modification           │
│                               │     │ • Masquerade                  │
│                               │     │ • Denial of service           │
└───────────────────────────────┘     └───────────────────────────────┘

2. Passive Attack Categories

1.Release of Message Contents:

↳The goal is to prevent an unauthorized opponent from reading or learning the plaintext contents of sensitive/confidential communications (e.g., telephone conversations, email messages, transferred files).

2.Traffic Analysis:

↳Even when the message content is masked by encryption, an adversary observes external characteristics of the communication channel:

1.Pattern and flow of messages

2.Geographical location of communicating entities

3.Identities/addresses of the communicating hosts

4.Transmission frequency and timing

5.Size and length of message packets

3.Communication & Eavesdropping Diagram:

Internet

                                    ┌───────┐
Sender ─────────────✉──────► │ (🌐) │───────────►✉───────── Receiver
                                    └───┬───┘
                                        │
                                        ▼

Attacker

(Observing Pattern /

Reading Message)

3. Nature, Detection & Prevention of Passive Attacks

1.Detection Difficulty:

a)Extremely difficult (virtually impossible) to detect in real time.

b)Reason: They do not involve any alteration, modification, or injection of data.

c)Traffic flows normally between sender and receiver, leaving both completely unaware that a third party has intercepted the message or analyzed the link.

2.Core Defense Strategy (Prevention over Detection):

a)Because detection is impractical, the primary focus is on PREVENTING successful execution rather than attempting detection.

b)Primary Countermeasure: Strong cryptographic encryption (protecting message content) alongside traffic padding and masking techniques.

Active Security Attacks

1. Definition & Overview

1.Core Definition:

a)An active attack involves the modification of the data stream or the creation of a false/spurious stream.

b)Unlike passive attacks, active attacks directly alter system resources or disrupt their normal operation.

2.Four Primary Types of Active Attacks:

1.Masquerade

2.Replay

3.Modification of message

4.Denial of Service (DoS)

2. Masquerade

1.Operational Mechanism:

a)Occurs when one entity pretends to be a completely different entity.

b)An attacker captures or steals legitimate credentials, exploits spoofed addresses, or presents forged identity tokens to authenticate illegally and gain unauthorized access to target systems or services.

c)Typically incorporates or facilitates other forms of active attacks (e.g., unauthorized data modification).

2.Visual Workflow:

Steals

Credentials

Attacker ────────────► 🔑 ────────► Authenticates ────────► Target System
  (🦹)                 (💳)              (Key)                 (Server)
                                                                  │
Trusted User ─────────────────────────────────────────────────────┘

(🧑‍💼) (Unauthorized Access Granted)

3. Replay Attack

1.Operational Mechanism:

a)Involves the passive interception/capture of a valid data transmission unit and its subsequent retransmission to produce an unauthorized effect.

b)The attacker does not necessarily decrypt or modify the intercepted packet; simply resending a valid transaction (e.g., an authentication token or a financial transaction packet) tricks the destination host into executing the duplicate request.

2.Visual Workflow:

Original Valid Transmission

User ══════════════════════════════════════════════════► Server
 (💻)                   │                              (🖳)
                           │ (Sniff Communication)         ▲
                           ▼                               │
                        Attacker                           │
                          (🦹) ───► [ MITM / Replay Traffic ]

4. Modification of Message

1.Operational Mechanism:

a)Some portion of a legitimate message is altered, delayed, or reordered in transit to produce an unauthorized outcome.

b)Violates data integrity by manipulating the payload before it reaches the intended destination.

2.Example Scenario:

a)Sender (Alice) transmits: "Transfer $1000 to Bob".

b)Attacker (Malls) intercepts the message in transit and alters the body to:

"Transfer $1000 to Mall's Account #98765".

c)Recipient (Bob / Bank) processes the modified message as valid instruction.

3.Visual Workflow:

Sender (Alice) Recipient (Bob)

   [ ✉ ] ──────────►  Attacker (Malls)  ───────────►          [ ✉ ]
"Transfer $1000        (Intercepts &          "Transfer $1000 to
   to Bob"                Modifies)             Mall's Acct #98765"

5. Denial of Service (DoS)

1.Operational Mechanism:

a)Prevents or inhibits the normal use or management of communications facilities and network resources.

b)Can target a specific service (e.g., suppressing all traffic directed toward a particular port, service, or server) or broadly degrade network infrastructure.

2.Execution Forms:

a)Suppression / Disruption: An entity suppresses, drops, or blocks all messages directed toward a specific destination.

b)Flooding / Amplification: An attacker floods a target host with amplified traffic loads, overwhelming its processing buffers and rendering it unavailable to legitimate requests.

3.Visual Workflow:

Sender (Alice) ───✕ (Blocked)
                  │
                  ▼
               Attacker ══════════════════════════════► Recipient (Bob)
                 (🦹)      [ Amplified Request Flood ]     (OVERLOADED /

Unavailable)

Security Services (X.800)

1. Classification Overview

•The security services define capabilities to protect system and network transmissions, divided into categories:

1.Authentication

2.Access Control

3.Data Confidentiality

4.Data Integrity

5.Non-repudiation

6.Availability

2. Authentication

1.Peer Entity Authentication:

a)Provided for use at connection establishment and at times during the data transfer phase of a connection.

b)Attempts to provide confidence that the communicating entity is not performing either a masquerade or an unauthorized replay.

2.Data Origin Authentication:

a)Provides the validation of the source/originator of an individual data unit.

b)Does not provide protection against duplication or modification of data units.

c)Application Example: Supports connectionless applications such as email, where there are no prior interactions between communicating entities.

3. Access Control

1.Core Definition:

↳The ability to limit and control access to host systems and applications via communications links.

2.Precondition:

↳To achieve access control, each entity attempting to gain access must first be identified or authenticated.

4. Data Confidentiality

1.Core Definition:

↳The protection of transmitted data from passive attacks (such as snooping and eavesdropping).

2.Scope:

↳With respect to the content of data transmission, several levels of protection can be identified (e.g., full message protection, selected fields, or traffic-flow masking).

5. Data Integrity

•Core Definition & Granularity:

a)Assures that data has not been altered, inserted, deleted, or replayed in an unauthorized manner.

b)Can be applied to:

1.A continuous stream of messages

2.A single isolated message

3.Selected individual fields within a message

6. Non-Repudiation

1.Core Definition:

↳Prevents either the sender or the receiver from denying a transmitted message once the transaction has occurred.

2.Two-Way Proof Mechanism:

a)Non-repudiation of Origin: When a message is sent, the receiver can prove that the sender sent the message.

b)Non-repudiation of Destination/Delivery: When a message is received, the sender can prove that the receiver received the message.

7. Availability

1.Core Definition:

↳A system resource must remain accessible and usable upon demand by an authorized system entity, in accordance with performance specifications for the system.

2.Impact of Attacks:

↳A variety of active security attacks (such as Denial of Service or resource suppression) can result in the loss of or reduction in system availability.

Relationship Between Security Services and Mechanisms (X.800)

1. Matrix Mapping Table

The following table maps X.800 Security Services to the specific Security

Mechanisms that implement or enforce them (marked with 'Y'):

┌────────────────────────────┬───┬───┬───┬───┬───┬───┬───┬───┐
│                            │ E │ D │ A │ D │ A │ T │ R │ N │
│                            │ n │ i │ c │ a │ u │ r │ o │ o │
│                            │ c │ g │ c │ t │ t │ a │ u │ t │
│                            │ i │ i │ e │ a │ h │ f │ t │ a │
│                            │ p │ t │ s │   │ e │ f │ i │ r │
│                            │ h │ a │ s │ I │ n │ i │ n │ i │
│                            │ e │ l │   │ n │ t │ c │ g │ z │
│                            │ r │   │ C │ t │ i │   │   │ a │
│                            │ m │ S │ o │ e │ c │ P │ C │ t │
│                            │ e │ i │ n │ g │ a │ a │ o │ i │
│                            │ n │ g │ t │ r │ t │ d │ n │ o │
│                            │ t │ n │ r │ i │ i │ d │ t │ n │
│                            │   │ a │ o │ t │ o │ i │ r │   │
│                            │   │ t │ l │ y │ n │ n │ o │   │
│                            │   │ u │   │   │   │ g │ l │   │
│                            │   │ r │   │   │ E │   │   │   │
│                            │   │ e │   │   │ x │   │   │   │
│ SERVICE                    │   │   │   │   │ c │   │   │   │
├────────────────────────────┼───┼───┼───┼───┼───┼───┼───┼───┤
│ Peer entity authentication │ Y │ Y │   │   │ Y │   │   │   │
│ Data origin authentication │ Y │ Y │   │   │   │   │   │   │
│ Access control             │   │   │ Y │   │   │   │   │   │
│ Confidentiality            │ Y │   │   │   │   │   │ Y │   │
│ Traffic flow conf.         │ Y │   │   │   │   │ Y │ Y │   │
│ Data integrity             │ Y │ Y │   │ Y │   │   │   │   │
│ Nonrepudiation             │   │ Y │   │ Y │   │   │   │ Y │
│ Availability               │   │   │   │   │   │   │   │   │
└────────────────────────────┴───┴───┴───┴───┴───┴───┴───┴───┘

2. Summary of Service-To-Mechanism Associations

1.Peer Entity Authentication:

↳Encipherment, Digital Signature, Authentication Exchange

2.Data Origin Authentication:

↳Encipherment, Digital Signature

3.Access Control:

↳Access Control mechanisms

4.Confidentiality:

↳Encipherment, Routing Control

5.Traffic Flow Confidentiality:

↳Encipherment, Traffic Padding, Routing Control

6.Data Integrity:

↳Encipherment, Digital Signature, Data Integrity mechanisms

7.Nonrepudiation:

↳Digital Signature, Data Integrity mechanisms, Notarization

8.Availability:

↳Supported operationally via physical redundancy, fault tolerance, and protocol-level safeguards rather than standard cryptographic primitives.

Model for Network Security

1. Architectural Model Diagram

Trusted Third Party

(e.g., arbiter, distributer

of secret information)

                 ▲   │   ▲
                 │   │   │
┌────────────────┘   │   └────────────────┐
│                    ▼                    │
│           [Information Channel]         │
│           ═════════════════════         │
│                     │                   │
▼                     ▼                   ▼

Sender Recipient

┌───────┐                                          ┌───────┐
│       │   Security-related                       │       │
│       │    transformation                        │       │
│       │          ○                               │       │
│       │          │                               │       │
│   M   │          ▼                 ○             │   M   │
│   e   │       ┌─────┐           ┌─────┐          │   e   │
│   s   │──────►│  S  │──────────►│  S  │─────────►│   s   │
│   s   │       │  e  │  Channel  │  e  │          │   s   │
│   a   │       │  c  │ (Tunnel)  │  c  │          │   a   │
│   g   │       │  u  │           │  u  │          │   g   │
│   e   │       │  r  │           │  r  │          │   e   │
│       │       │  e  │           │  e  │          │       │
│       │       │     │           │     │          │       │
│       │       │  M  │           │  M  │          │       │
│       │       └─────┘           └─────┘          │       │
└───────┘          ▲                 ▲             └───────┘
                   │                 │

Secret Information Secret Information

2. Core Components of the Model

1.Message (Plaintext):

↳The original data or message created by the Sender to be securely delivered to the Recipient.

2.Security-Related Transformation:

↳An encryption, hashing, or scrambling process applied to the plaintext at the sender side, and reversed (decryption/verification) at the recipient.

3.Secret Information:

↳Key material (e.g., symmetric key, private key) supplied to the transformation algorithm to convert plaintext into secure ciphertext.

4.Information Channel:

↳The physical or logical path across the network through which the secure message travels, susceptible to attacks or interception.

5.Trusted Third Party (TTP):

↳An independent, trusted entity (such as an arbiter, certificate authority, or key distribution center) that facilitates secure communication by distributing secret keys or arbitrating disputes between principals.

3. Four Essential Tasks in Designing a Security Service

1.Algorithm Design:

a)Design an algorithm for performing the security-related transformation.

b)The algorithm must be constructed such that an opponent cannot defeat its purpose (e.g., computationally infeasible to break).

2.Secret Information Generation:

↳Generate the secret information (keys, initialization vectors, seeds) to be used alongside the algorithm.

3.Distribution & Key Sharing:

↳Develop robust methods and protocols for securely distributing and sharing the secret information between authorized endpoints.

4.Protocol Specification:

↳Specify a formal protocol to be used by the two communicating principals that coordinates the security algorithm and the shared secret information to achieve the targeted security service.

ITU-T / OSI Recommendation X.800

1. Definition & Purpose

1.Official Title:

a)ITU-T Recommendation X.800 (also standardized as ISO 7498-2).

b)"Security Architecture for Open Systems Interconnection (OSI) for CCITT Applications."

2.Primary Objective:

a)Provides a systematic, architectural framework for defining and standardizing where and how security can be applied across the 7 layers of the OSI reference model.

b)Acts as the foundational baseline used across computer networking literature to categorize:

1.Security Attacks (Passive vs. Active)

2.Security Services (What capabilities are required to counter attacks)

3.Security Mechanisms (How those capabilities are implemented technically)

2. the Three Core Pillars of X.800

┌─────────────────────────┐
│     SECURITY ATTACK     │  Action that compromises the security of information.
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│     SECURITY SERVICE    │  Processing/communication capability that counters
└───────────┬─────────────┘  attacks to secure systems (e.g., Confidentiality,
            │                Integrity, Authentication).
            ▼
┌─────────────────────────┐
│   SECURITY MECHANISM    │  Concrete technical algorithm, protocol, or device
└─────────────────────────┘  designed to enforce a service (e.g., Encipherment,

Digital Signatures, Access Control lists).

3. Key Classifications Defined by X.800

1.Security Services (5 Main Categories):

AuthenticationPeer entity authentication and data origin authentication.
Access ControlRegulating access to resources via communication paths.
Data ConfidentialityProtecting data against unauthorized inspection.
Data IntegrityDetecting unauthorized modification, deletion, or replay.
Non-repudiationProving message transmission and receipt to prevent denial.

*(Availability is recognized as a critical property often grouped alongside).*

2.Specific Security Mechanisms:

a)Encipherment (symmetric/asymmetric encryption)

b)Digital Signatures

c)Access Control mechanisms

d)Data Integrity mechanisms (checksums, MACs, hashes)

e)Authentication Exchange (handshakes, challenge-response)

f)Traffic Padding (mitigating traffic analysis)

g)Routing Control (selecting secure paths)

h)Notarization (trusted third-party audit/assurance)

↑ Back to contents

PART TWO
Network Attacks, Defences & Security Tools
Chapter 7

Lecture 11 — Data-link, network & transport-layer attacks (MAC/ARP, DHCP, SYN flood, hijacking) + Lab 4.3 (Ettercap)

X.800 Attack Taxonomy Mapped to the Data Link Layer (Layer 2)

Note on X.800 Classification

The X.800 attacks (Passive & Active) are high-level conceptual categories that

manifest at EVERY OSI layer. At the Data Link Layer (Layer 2), they take

specific technical forms operating on MAC addresses, Ethernet frames, ARP,

and switches:

1. Passive Attacks at Data Link Layer

1.Release of Message Contents:

a)Layer 2 Manifestation: Promiscuous-Mode Sniffing / Wiretapping.

b)Mechanism: Setting a Network Interface Card (NIC) to promiscuous mode or using a network tap/SPAN port to capture raw unencrypted Ethernet frames (e.g., reading HTTP, Telnet, or FTP payloads directly off the local LAN).

2.Traffic Analysis:

a)Layer 2 Manifestation: MAC Frame & Topology Profiling.

b)Mechanism: Even if upper-layer payloads are encrypted (e.g., TLS/HTTPS or WPA3), Layer 2 frame headers remain visible. An attacker observes source and destination MAC addresses, frame sizes, and transmission bursts to map active hosts, vendor types (via OUI), and communication patterns on the LAN.

2. Active Attacks at Data Link Layer

1.Masquerade:

a)Layer 2 Manifestation: MAC Spoofing & ARP Spoofing / Poisoning.

b)Mechanism:

1.MAC Spoofing: Changing a device's hardware MAC address to impersonate an authorized host and bypass MAC-based switch port security or NAC.

2.ARP Spoofing: Sending forged ARP Reply frames linking the attacker's MAC address to the default gateway's IP address, masquerading as the router.

2.Modification of Message:

a)Layer 2 Manifestation: Layer 2 Man-in-the-Middle (MITM) via ARP Poisoning.

b)Mechanism: Once ARP poisoning redirects LAN frames through the attacker's machine, the attacker intercepts, alters the payload or headers of the frames, recalculates the FCS (Frame Check Sequence / CRC), and forwards them to the true destination.

3.Replay:

a)Layer 2 Manifestation: Frame Replay / ARP & EAPOL Replay Attacks.

b)Mechanism: Capturing valid Layer 2 frames (such as ARP packets to generate new Initialization Vectors in legacy WEP/Wi-Fi, or raw control frames) and retransmitting them onto the shared medium without alteration.

4.Denial of Service (DoS):

a)Layer 2 Manifestation: MAC Flooding, DHCP Starvation, & Deauthentication Floods.

b)Mechanism:

MAC Flooding (CAM Table Overflow)Flooding a switch with thousands of frames containing random source MAC addresses until its CAM table fills up, forcing the switch to fail-open into hub mode (broadcasting all traffic) or drop legitimate frames.
DHCP StarvationExhausting the DHCP IP pool using spoofed MAC addresses at Layer 2 so legitimate hosts cannot obtain network access.
Wi-Fi Deauthentication FloodSending spoofed 802.11 management frames to forcefully disconnect wireless clients from an Access Point.

3. Summary Mapping Table

┌──────────────────────────────┬────────────────────────────────────────────┐
│ X.800 Attack Category        │ Equivalent Data Link Layer (L2) Attacks    │
├──────────────────────────────┼────────────────────────────────────────────┤
│ Release of Message Contents  │ Promiscuous-mode frame sniffing / tapping  │
│ Traffic Analysis             │ MAC address & frame-timing profiling       │
│ Masquerade                   │ MAC spoofing, ARP spoofing / poisoning     │
│ Modification of Message      │ ARP-poisoned MITM frame alteration         │
│ Replay                       │ Raw Ethernet / 802.11 frame replay         │
│ Denial of Service (DoS)      │ MAC flooding (CAM overflow), 802.11 deauth │
└──────────────────────────────┴────────────────────────────────────────────┘

Network Layer Attacks (Layer 3)

1. Recap: Dynamic Host Configuration Protocol (DHCP)

1.Core Purpose & Layer:

a)DHCP is an Application Layer protocol used to dynamically assign IP addresses and network configuration parameters (Default Gateway IP, DNS Server IP) to newly connected hosts.

b)A DHCP server maintains:

1.Static IP mappings (reserved 24/7 for fixed infrastructure like email/web servers).

2.A Dynamic IP Pool (leased temporarily to client machines for a fixed lease time).

↳Once a lease expires, the client must renew or request a new IP address.

2.The 4-Step DORA Handshake:

1.DHCP DISCOVER (Broadcast):

a)Client (A) does not know its own IP or the DHCP server's IP.

b)Source IP: 0.0.0.0 | Destination IP: 255.255.255.255 (Broadcast).

c)Destination MAC: FF:FF:FF:FF:FF:FF (Layer 2 Broadcast).

2.DHCP OFFER (Broadcast):

↳DHCP Server picks an available IP (e.g., IP_A) from its dynamic pool and broadcasts an offer containing IP_A, gateway, and DNS settings.

3.DHCP REQUEST (Broadcast):

↳Client explicitly requests the offered IP address (IP_A).

4. DHCP ACK / Reply

↳DHCP Server confirms the lease allocation of IP_A to Client A.

•DORA Flow & Relay Agent Topology:

Client (A) DHCP Server

┌───────────┐                                      ┌───────────┐
│  (0.0.0.0)│── 1. DHCP DISCOVER (Broadcast) ─────►│  [Static] │
│           │◄─ 2. DHCP OFFER (IP_A, Broadcast) ───│  [ Pool ] │
│           │── 3. DHCP REQUEST (IP_A) ───────────►│           │
│  (IP_A)   │◄─ 4. DHCP ACK / REPLY ────────────── │           │
└───────────┘                                      └───────────┘

↳Cross-Network Operation (DHCP Relay Agent):

•If the DHCP server resides on a different network, a local Relay Agent (configured with the DHCP server's unicast IP) intercepts the client's broadcast and forwards it to the remote DHCP server.

2. Network Layer Attack 1: DHCP Starvation Attack

1.Attack Mechanism:

a)An attacker continuously floods the DHCP server with massive numbers of DHCP DISCOVER / REQUEST packets (using spoofed/unique MAC addresses).

b)The DHCP server grants leases until its entire dynamic IP address pool is completely exhausted.

c)Result (Denial of Service): When a legitimate DHCP client joins the network and broadcasts a DISCOVER packet, the server has no free IPs left to lease.

2.Starvation Diagram:

Legitimate Client          DHCP Server                 Attacker
 ┌───────────────┐        ┌───────────┐            ┌──────────────┐
|  [ Client ]   |── X ──►| [ Pool ]  |◄─ DISCOVER | [ Attacker ] |
└───────────────┘        │ Exhausted │◄─ DISCOVER │              │
(Cannot get IP)          │           │◄─ DISCOVER │              │
                         └───────────┘            └──────────────┘

1.Defense Analysis (Can MAC Limiting Help?):

a)Same-Network Mitigation (MAC Limiting):

•On a local LAN, the switch/server can enforce MAC limiting (restricting how many IP leases a single MAC address/port can request).

b)Cross-Network Limitation (Why Layer 2 MAC Limiting Fails):

1.If the DHCP server is located on a different network behind a router/relay agent, the incoming frame's Layer 2 source MAC address belongs to the default router—not the attacker.

2.Therefore, Layer 2 MAC limiting on the server side cannot distinguish attackers from legitimate clients.

3.Solution: Inspect/validate the Client Hardware Address (CHADDR) inside the DHCP Application Layer payload rather than relying solely on Layer 2 headers.

2.Worked Numerical Problem (DHCP Starvation):

a)Given:

Total DHCP Pool Size= 254 addresses
Normal Active Usage= 150 addresses
Remaining Free Pool= 254 - 150 = 104 addresses
Average Lease Time= 24 hours
Attacker Flood Rate= 500 DHCPDISCOVER messages/minute (unique MACs)

b)Question 1: How long will it take to exhaust the remaining 104 addresses?

Time= Remaining Addresses / Request Rate
Time= 104 requests / 500 requests per minute = 0.208 minutes
In seconds0.208 × 60 = 12.48 seconds ≈ 12.5 seconds. (Note: Slide text contains a unit typo printing "12.5 minutes"; the exact value confirmed in class is 12.5 seconds).
⚠ Correction: The slide prints "0.208 min = 12.5 minutes"; the correct value is 0.208 min = 12.48 seconds (as recorded here).

↳Question 2: How does the situation change if lease time is 1 hour instead of 24 hours?

1.Initial Exhaustion Time: Unchanged (still takes 12.5 seconds to drain the 104 available addresses).

2.Attack Duration Impact: With a 1-hour lease, spoofed leases expire and return to the available pool much faster, significantly reducing the duration of the denial-of-service window if the flood stops.

3. Network Layer Attack 2: DHCP Spoofing Attack (Rogue DHCP Server)

1.Attack Mechanism:

a)Because networks can legitimately run multiple DHCP servers, a client accepts the first DHCP OFFER it receives and ignores subsequent offers.

b)When a legitimate client broadcasts a DHCP DISCOVER, an attacker on the network races to reply first with a forged DHCP OFFER, impersonating a legitimate DHCP server.

2.Spoofing Diagram:

DHCP Client              Attacker (Rogue)         Legitimate DHCP Server
┌──────────┐             ┌──────────────┐            ┌──────────────┐
│          │── DISCOVER ─┼──────────────┼───────────►│              │
│          │             │              │            │              │
│          │◄─ OFFER ────│ (Replies 1st)│            │   (Too Late) │
└──────────┘             └──────────────┘            └──────────────┘

1.Why DHCP Spoofing is Extremely Dangerous:

a)Beyond assigning an IP address, a DHCP OFFER dictates the client's:

1.Default Gateway (Router) IP

2.DNS Server IP

b)Downstream Impact:

1.Malicious Default Gateway: All outbound client traffic is routed directly through the attacker's machine (Man-in-the-Middle).

2.Malicious DNS Server: When the victim visits a legitimate domain (e.g., a bank website), the rogue DNS resolves it to a spoofed phishing server IP, allowing the attacker to harvest OTPs, passwords, and credit card details.

2.Defense Mechanism:

↳Trusted Ports (DHCP Snooping):

1.Configure network switches to designate only the specific physical switch port connected to the legitimate DHCP server as a "Trusted Port".

2.Any DHCP OFFER packet arriving on an untrusted client port is automatically dropped.

4. Recap: TCP Connection Lifecycle & Random Sequence Numbers

•3-Way Handshake (Connection Establishment):

1. Client (A) ── SYN (Random Initial Seq No) ──► Server (B)
2. Server (B) ── SYN + ACK ────────────────────► Client (A)
3. Client (A) ── ACK ──────────────────────────► Server (B)

1.Why TCP Uses a Random Initial Sequence Number:

a)Purpose: To distinguish packets belonging to a newly established connection from delayed/retransmitted stray packets arriving from a previous closed connection between the exact same two hosts/ports.

b)If sequence numbers always started at 0, a delayed packet from an old session could collide with and corrupt a newly opened session.

2.Connection Termination (FIN vs. RST):

a)Graceful Close (FIN):

1.Client sends FIN; Server replies with ACK.

2.This closes only the client-to-server direction (half-close); the server can still continue transmitting data until the server sends its own FIN.

b)Abrupt Abort (RST - Reset):

•If either side sends an RST flag (e.g., upon receiving an unexpected packet), the connection is terminated immediately and buffers are freed.

5. Transport Layer Attack 1: TCP SYN Flood Attack

1.Attack Mechanism (Half-Open Connection Exhaustion):

a)When a server receives a SYN packet, it allocates memory buffers and stores connection state parameters (window size, MSS, etc.) in its half-open connection queue (SYN backlog), then replies with SYN+ACK.

b)Normally, receiving the final ACK moves the connection out of the backlog into full data-transfer memory.

c)In a SYN Flood (a Denial-of-Service attack), the attacker sends a massive stream of SYN packets and intentionally NEVER sends the final ACK.

d)The server's half-open connection queue fills up completely, preventing legitimate visitors from establishing new connections.

2.Why It Is Called a "Half-Open" Attack:

↳The 3-way handshake stops halfway: SYN and SYN+ACK are exchanged, but the final ACK is never sent, leaving connections stuck in the half-open state.

3.SYN Flood Diagram:

Attacker                 Server (SYN Backlog)         Legitimate Visitor
┌─────────┐              ┌────────────────────┐        ┌────────────────┐
│         │── SYN ──────►│ [Allocates Buffer] │        │                │
│         │── SYN ──────►│ [Allocates Buffer] │        │                │
│         │◄─ SYN+ACK ───│ Waiting for ACK... │        │                │
│(Ignores │              │ (Queue Full!)      │◄─ SYN ─│                │
| SYN+ACK)|              |  X Conn. Exhausted |        |   (Rejected)   |
└─────────┘              └────────────────────┘        └────────────────┘

1.IP Spoofing & Botnet Dynamics in SYN Floods:

1.Single Unspoofed Attacker IP:

↳Easily blocked via basic IP filtering using the 4-tuple (Source IP, Destination IP, Source Port, Destination Port).

2.Spoofing an Active Valid User's IP (e.g., Alice / IP_V):

a)Attacker sends SYN with Source IP = Alice.

b)Server sends SYN+ACK to Alice (not the attacker).

c)Because Alice never initiated a SYN, Alice's OS automatically replies with an RST packet, causing the server to immediately clear the memory.

d)Thus, spoofing an active online user fails unless that host is offline.

3.Using a Botnet (Distributed DoS):

a)Attacker uses a network of compromised computers (botnets) or spoofs botnet IPs.

b)When the server sends SYN+ACK to the botnet hosts, the compromised machines are programmed to silently ignore the packet (suppressing RST and withholding ACK), keeping the server's backlog locked.

2.Defense Mechanisms Against TCP SYN Flood:

1.Filtering:

↳Drop suspicious or malformed SYN flood packets before they reach and exhaust the server's half-open connection queue.

2.Ingress Filtering:

↳Configured on edge routers to drop incoming packets whose spoofed Source IP address does not match the expected IP prefix/subnet of the network interface it arrived on.

3.SYN Cookies (TCP Cookies):

a)Server allocates ZERO memory when a SYN arrives.

b)Instead, the server cryptographically encodes the connection state (Source/Dest IPs & ports, timestamp, MSS, and a secret key) directly into the 32-bit Initial Sequence Number of its SYN+ACK.

c)When a legitimate client replies with the final ACK (acknowledging ISN + 1), the server recomputes/verifies the cookie, reconstructs the connection parameters, and only then allocates full connection state.

3.Worked Numerical Problem (SYN Backlog Exhaustion):

a)Given:

Maximum half-open connections (B)= 8,192
Attacker SYN flood rate (R)= 50,000 SYNs/second
SYN-received timeout= 30 seconds

b)(a) How quickly will the backlog fill?

1.Time (t) = Backlog Capacity (B) / Arrival Rate (R)

2.t = 8,192 / 50,000 = 0.16384 seconds ≈ 0.164 seconds.

c)(b) Does reducing the timeout from 30 seconds to 5 seconds significantly change this?

1.No — it has no significant effect.

2.Reason: Under a continuous flood of 50,000 SYNs/sec, the backlog fills completely in 0.164 seconds—long before either the 30-second or 5-second timeout can expire any half-open entry. (A timeout would only help if it were shorter than 0.164 seconds).

6. Transport Layer Attack 2: TCP Session Hijacking

1.Attack Mechanism:

a)An attacker takes over an already-established TCP session between two legitimate hosts (C and D) by injecting forged packets containing the valid 4-tuple (Source IP, Dest IP, Source Port, Dest Port) and correctly predicted Sequence and Acknowledgement numbers.

b)Because TCP relies solely on IP/port tuples and seq/ack numbers once a handshake finishes, the target trusts the injected packets as authentic.

2.Step-by-Step Execution:

1.Sniffing:

↳Attacker monitors traffic between C and D (e.g., via a compromised router or ARP spoofing) to learn active IPs, ports, and current seq/ack values.

2.Desynchronization:

↳To prevent the legitimate client (C) from interfering or sending conflicting ACKs/RSTs, the attacker either floods client C with traffic or sends a forged RST/FIN packet to desynchronize C's connection state.

3.Packet Injection:

↳Attacker spoofs C's IP address and injects malicious command packets with the exact predicted seq/ack numbers expected by Server D.

3.Session Hijacking Diagram:

Client (C)              Attacker (Sniffing/MITM)         Server (D)
┌────────┐              ┌──────────────────────┐        ┌──────────┐
│        │◄════════════►│ (Monitors Seq/Ack)   │◄══════►│          │
│        │◄─ Forged RST─│                      │        │          │
│(Out of │              │                      │        │          │
│ Sync)  │              │── Forged Packet ─────┼───────►│(Accepts) │
└────────┘              │   (Spoofed C + Seq)  │        └──────────┘
                        **└──────────────────────┘**

7. Transport Layer Attack 3: TCP Session Spoofing

1.Attack Mechanism:

↳Unlike Session Hijacking (which takes over an existing session), Session Spoofing establishes a brand-new TCP connection with Server (B) while forging the Source IP address to impersonate a trusted host (A).

2.Requirements & Execution Steps:

1.Bring Down Trusted Host (A):

↳The attacker must first take trusted host A offline (e.g., via a DoS attack). If A is online, it will receive B's SYN+ACK and immediately kill the spoofed session with an RST packet.

2.Forged SYN:

↳Attacker sends SYN to Server B with Source IP = A and Initial Seq = X.

3.Blind Sequence Prediction & Final ACK:

a)Server B sends SYN+ACK (Seq = Y, Ack = X+1) back to offline host A.

b)Because the attacker cannot see B's reply directly (blind spoofing), the attacker must predict or infer B's Initial Sequence Number (Y) to send a valid final ACK (Ack = Y+1) and complete the 3-way handshake.

3.Session Spoofing Diagram:

Trusted Host (A)         Attacker                        Server (B)
┌──────────────┐        ┌────────┐                      ┌──────────┐
│  [ OFFLINE ] │        │        │── SYN (Src: A, X) ──►│          │
│      ▲       │        │        │                      │          │
│      └───────┼────────┼────────┼── SYN+ACK (Y, X+1) ──│          │
│  (Dropped)   │        │        │── ACK (Y+1) ────────►│(Session  │
└──────────────┘        └────────┘  (Predicted Seq Y)   │ Opened!) │
                                                        └──────────┘

🧪 Lab 4.3 · Network Sniffing & ARP Spoofing with Ettercap

Detailed Conceptual Explanation:

1.LAN Traffic Isolation: Hubs vs. Switches:

a)Legacy Hub (Layer 1): Repeats every incoming frame out of every physical port; passive sniffing requires zero special configuration.

b)Modern Switch (Layer 2): Maintains a CAM (Content Addressable Memory) Table mapping device MAC addresses to specific physical switch ports, forwarding frames only to the intended recipient's port. Sniffing across a switched LAN requires active Man-in-the-Middle (MitM) intervention.

2.Address Resolution Protocol (ARP) Security Flaw:

a)Switches forward frames by MAC address (Layer 2), while applications use IP addresses (Layer 3). Hosts broadcast ARP Requests ("Who has 192.168.1.1?") and receive unicast ARP Replies ("192.168.1.1 is at 00:AA:BB:CC:DD:EE").

b)Core Flaw: ARP is stateless and completely unauthenticated. Computers blindly accept and cache unsolicited ARP replies (Gratuitous ARP) even when they never sent a request, overwriting legitimate IP-to-MAC mappings.

3.Ettercap Architecture, Target Syntax, & Commands:

a)Open-source LAN analysis and active MitM tool (available on Kali Linux/macOS) combining packet capture, live protocol parsers (extracting plaintext HTTP, FTP, POP3 credentials), plugins (dns_spoof, remote_browser), and live packet-alteration filters.

b)Target Specification Format: /IP-Range//MAC-Address//IPv6-Range//Ports/

Target all hosts on LAN// //
Target single workstation/192.168.1.50///
Target HTTP/HTTPS ports on IP range/192.168.1.100-110///80,443/

c)Two-Way ARP Poisoning Command (Victim <-> Gateway Router):

sudo ettercap -T -i eth0 -M arp:remote /192.168.1.1/ /192.168.1.50/ (-T = text CLI mode, -G = GUI mode, -q = quiet, -i = interface, -M arp:remote = bidirectional ARP spoofing, -w file.pcap = save capture).

d)Real-Time Payload Injection via etterfilter:

1.Script (text_swap.filter):

if (ip.proto == TCP && tcp.src == 80) { if (search(DATA.data, "Welcome Guest")) { replace("Welcome Guest", "AUTHORIZED USER"); } }

2.Compile & Execute:

etterfilter text_swap.filter -o binary.ef sudo ettercap -T -i eth0 -F binary.ef -M arp:remote // //

4.Defenses Against ARP Spoofing & MitM Attacks:

Dynamic ARP Inspection (DAI)Enterprise switch security feature that validates ARP packets against a trusted DHCP snooping binding database and drops forged ARP replies at the switch port.
Static ARP TablesHardcoding fixed IP-to-MAC entries for critical servers and default gateways so spoofed ARP broadcasts are ignored.
Mandatory TLS/HTTPSEnd-to-end encryption prevents MitM attackers from reading or modifying intercepted HTTP payloads.

Real-World Example:

On a poorly configured public café or campus Wi-Fi network lacking client isolation and DAI, an attacker runs Ettercap ARP spoofing to position their laptop between victims and the Wi-Fi gateway, harvesting plaintext login credentials from unencrypted HTTP portals and injecting malicious scripts into unencrypted web pages.

↑ Back to contents

Chapter 8

Lecture 13 — Application-layer attacks (DNS, pharming, amplification) & firewalls

Application Layer Attacks (Layer 7)

1. Recap: Domain Name Service (DNS) Architecture

1.Core Function:

↳Converts human-readable domain names (e.g., engineering.mcgraw-hill.com) into machine-routable IP addresses.

2.Iterative Resolution Workflow (from Slide Diagram):

1.Resolver (Client) queries its Local DNS Server (dns.anet.com).

2.If not cached locally, the Local DNS Server queries the Root Server.

3.The Root Server does not know the final IP, so it replies with the IP address of the Top-Level Domain (TLD) Server (.com server) via a Glue Record.

4.Local DNS Server queries the .com TLD Server.

5.TLD Server replies with the IP address of the Authoritative Name Server (dns.mcgraw-hill.com).

6.Local DNS Server queries the Authoritative Name Server.

7.Authoritative Name Server returns the final IP address of the destination.

8.Local DNS Server caches the mapping and returns the IP to the Resolver.

3.DNS Hierarchy & Resolution Diagram:

[ Root Server ]

/ | \

/ | \

[ .edu ] [ .com ] [ .us ]

/ \

/ \

[ mcgraw.com ] [ irwin.com ]

Resolver ──(1)──► Local DNS (dns.anet.com)
                     │  ▲
                     ├──┼──(2/3)──► Root Server (returns TLD IP)
                     ├──┼──(4/5)──► .com TLD Server (returns Auth IP)
                     ├──┼──(6/7)──► Authoritative Server (returns Final IP)
                     │
Resolver ◄──(8)──────┘

•Key Fields in DNS Messages:

a)Request Message : Contains a 16-bit Transaction ID field used to match incoming replies to outgoing queries.

b)Reply Message : Contains Glue Information (Glue Records) providing the IP address of the next name server to contact.

2. Application Layer Attack 1: Pharming, Phishing, & Glue Record Poisoning

1.Pharming:

↳An attack where hostname-to-IP address mapping is altered maliciously (e.g., mapping bank.com to an attacker-controlled IP address) either by compromising a DNS server or spoofing DNS replies.

2.Phishing (Working Hand-in-Hand with Pharming):

a)Once Pharming redirects the victim to the attacker's IP, the attacker hosts an identical-looking replica of the legitimate website (e.g., a bank portal).

b)The victim unknowingly submits sensitive credentials (account numbers, passwords, OTPs) directly to the attacker's machine.

3.Cross-Domain Glue Record Poisoning (IIT Kharagpur / IIT Bhubaneswar Scenario):

a)Scenario Setup:

1.The Authoritative Name Server of IIT Kharagpur is hacked by an attacker.

2.A user visits IIT Kharagpur's website, causing their Local DNS Server to query IIT Kharagpur's compromised Authoritative Name Server.

b)Injection Mechanism:

1.Along with the legitimate DNS answer for IIT Kharagpur, the hacked server attaches malicious Glue Information claiming that IIT Bhubaneswar's website resides at the attacker's IP address.

2.Because basic DNS blindly caches unsolicited glue records without checking if they belong to the queried domain, the Local DNS Server stores the poisoned IIT Bhubaneswar mapping.

c)Impact & Defense:

1.Later, when the innocent user attempts to access IIT Bhubaneswar, the Local DNS routes them directly to the attacker's machine.

2.Defense (Bailiwick Checking / Filtering): A DNS resolver must filter out and discard glue records that belong to unrelated third-party domains.

4.Glue Record Poisoning Diagram:

User ──► Local DNS ──(1. Queries IIT Kharagpur)──► Hacked Auth Server
             │                                       (IIT Kharagpur)
             │◄─(2. Legit Answer + Malicious Glue: ────────┘
             │      "IIT Bhubaneswar = Attacker IP")
             │
User ──(3. Accesses IIT Bhubaneswar)──► Routed to Attacker's IP!

3. Application Layer Attack 2: On-Path vs. Off-Path DNS Cache Poisoning

1.Core Condition for Accepting a DNS Reply:

↳A Local DNS Server accepts a DNS reply only if it matches:

1.Source & Destination IP addresses

2.Source & Destination UDP port numbers

3.The 16-bit Transaction ID from the original DNS request

2.Case A: On-Path Attack:

a)The attacker sits directly on the network path and can sniff/observe the outgoing DNS request packet in transit.

b)Because the attacker directly sees the Transaction ID and port numbers, constructing and racing a forged DNS reply so the Local DNS Server installs the malicious cache entry is trivial.

3.Case B: Off-Path Attack (Blind Spoofing):

a)The attacker is NOT on the communication path and cannot see the outgoing DNS request packet.

b)Guessing the source/destination IPs and ports is relatively easy, so the attacker's primary challenge is guessing the 16-bit Transaction ID.

4.Step-by-Step Off-Path Attack Execution (Sequential ID Vulnerability):

1.Attacker triggers a lookup by asking the victim's Local DNS Server to resolve an attacker-owned domain (www.eve.com).

2.The Local DNS Server sends a DNS query with Transaction ID = ID to the Authoritative Name Server of eve.com (controlled by the attacker).

3.The attacker reads the exact Transaction ID from the incoming query.

4.Immediately afterward, the victim requests bank.com. If the Local DNS Server uses sequential IDs, the new request uses Transaction ID = ID + 1.

5.Before the genuine bank.com server can respond, the off-path attacker forges a spoofed reply carrying ID + 1 and a malicious IP, poisoning the Local DNS cache.

5.Off-Path DNS Poisoning Diagram:

Attacker ──(1. Query www.eve.com)──► Local DNS
   ▲                                   │  │
   └──(2. Query with ID)───────────────┘  │
          (Attacker reads ID)             │
                                          │──(3. Query bank.com, ID+1)──► Auth DNS
Attacker ──(4. Forged Reply, ID+1)───────►│ (Poisoned before real reply!)  (bank.com)

4. Defense Mechanisms Against DNS Spoofing / Cache Poisoning

1.Random Transaction IDs:

↳Replace predictable sequential IDs with cryptographically random 16-bit Transaction IDs so off-path attackers cannot infer the next ID.

2.Source Port Randomization (16-bit ID + 16-bit Random Source Port):

a)Combine the 16-bit random Transaction ID with a 16-bit random UDP source port for every outbound DNS query.

b)Increases the search space from 2¹⁶ (65,536) possibilities to 2³² (over 4.29 billion) combinations, making blind guessing practically impossible.

3.DNSSEC (Domain Name System Security Extensions):

a)Certificate- and public-key-based cryptographic solution.

b)Authoritative servers digitally sign DNS records; resolvers verify the cryptographic signatures to guarantee data origin authenticity and integrity, rejecting any forged or altered responses.

5. Application Layer Attack 3: Amplification Attack (DDoS)

1.Core Definition:

↳A Distributed Denial-of-Service (DDoS) attack in which an adversary sends small, spoofed requests to open third-party public servers (acting as unwitting reflectors/amplifiers), causing those servers to transmit much larger responses to the victim.

2.Step-by-Step Mechanism (facebook.com Example):

1.Attacker crafts small DNS (or NTP/SSDP) request packets with the Source IP spoofed to the victim's IP address (e.g., facebook.com).

2.Attacker sends these small requests to numerous misconfigured open Public Servers (acting like a reflector botnet).

3.Each Public Server processes the query and sends a massive response payload (amplification factor) back to the spoofed Source IP (facebook.com).

4.The victim's network bandwidth and server resources are completely overwhelmed by the amplified flood.

3.Amplification Attack Diagram:

                                   ┌──► [ Public Server ] ═══╗
Attacker ──(Small Spoofed Req)─────┼──► [ Public Server ] ═══╬══► Victim
(Src: Victim IP)                   ├──► [ Public Server ] ═══╣  (facebook.com)
                                   └──► [ Public Server ] ═══╝  (Overwhelmed by

Huge Replies)

Firewalls (Packet Filters, Stateful Filters, & Application Gateways)

•Content: Firewall Fundamentals, Properties, Attack Context, & Traditional (Stateless) Packet Filters (with ACL Tables & Policy Examples), Stateful Packet Filters (Connection Tables & UDP Handling) & Application Gateways (Proxy Firewalls, Workflow, & Drawbacks).

1. Firewall Fundamentals & Motivation

1.Why Organizations Need Firewalls:

↳Most organizations (universities, enterprises) connect their internal networks to the public Internet, exposing them to external adversaries attempting to:

1.Infect internal machines with malware.

2.Steal/obtain corporate secrets.

3.Map internal network configurations and topology.

4.Launch Denial-of-Service (DoS) attacks.

2.Definition & Core Function:

a)A Firewall is a combination of hardware and software that controls access between an organization's internal network and the public Internet.

b)Inspects both inbound and outbound traffic, permitting authorized packets and blocking unauthorized packets according to a defined Security Policy.

c)Dual Protection Goal:

1.Prevents external intruders from attacking the internal network.

2.Prevents confidential internal data from leaking outside.

3.Essential Properties of a Firewall:

Single Choke PointAll traffic from outside-to-inside and inside-to-outside must pass through the firewall.
Policy EnforcementOnly authorized traffic explicitly defined by the network administrator's security policy is permitted; all else is blocked.
Hardened SystemThe firewall itself is hardened to resist compromise, with all unnecessary services removed and security policies updated regularly.

4.Deployment Implementations:

HardwareDeployed as a dedicated standalone security appliance.
SoftwareInstalled on a hardened host PC.
Router-IntegratedMany network routers support built-in basic firewall filtering capabilities.

5.Network Attacks Mitigated by Firewalls (Lecture Context):

ICMP AttacksDestination Unreachable exploits, ICMP Redirect abuse, and network mapping via Traceroute (incrementing IP TTL values: 1, 2, 3... to discover intermediate router hops via ICMP Time Exceeded replies).
TCP SYN Flood AttacksHalf-open connection queue exhaustion.
DNS AttacksUnauthorized DNS queries, spoofing, or tunneling.

2. Three Main Types of Firewalls

1.Traditional Packet Filter (Stateless)

2.Stateful Packet Filter

3.Application Gateways (Proxy Firewalls)

3. Traditional Packet Filter (Stateless Firewall)

1.Operational Mechanism:

a)Examines each packet in complete isolation and decides whether to allow or drop it.

b)Stateless Design: Does NOT store any memory/state of past packets or active connections; relies strictly on static rules configured by the network administrator.

c)Different rule sets are applied to packets entering vs. leaving the network and across different router interfaces.

2.Packet Header Fields Inspected:

a)Source IP address and/or Destination IP address

b)Protocol Type (TCP, UDP, ICMP, etc.)

c)TCP or UDP Source Port and Destination Port

d)TCP Flag bits (SYN, ACK, FIN, RST, etc.)

e)ICMP Message Type (e.g., Echo Request, TTL Expired)

3.Policy-to-Firewall Configuration Examples:

┌──────────────────────────────────────────┬──────────────────────────────────────────┐
│ Security Policy                          │ Firewall Rule / Setting                  │
├──────────────────────────────────────────┼──────────────────────────────────────────┤
│ No outside web access                    │ Drop all outgoing packets to any IP      │
│                                          │ address with Destination Port = 80       │
├──────────────────────────────────────────┼──────────────────────────────────────────┤
│ No incoming TCP connections except those │ Drop all incoming TCP SYN packets (SYN=1,│
│ for organization's public web server     │ ACK=0) to any IP except 130.207.244.203  │
│                                          │ on Destination Port = 80                 │
├──────────────────────────────────────────┼──────────────────────────────────────────┤
│ Prevent audio-video streaming traffic    │ Drop all UDP packets, except DNS packets │
│ from eating up available bandwidth       │ (Port 53)                                │
├──────────────────────────────────────────┼──────────────────────────────────────────┤
│ Prevent internal network topology from   │ Drop all outgoing ICMP TTL Expired       │
│ being mapped via Traceroute              │ (Time Exceeded) traffic                  │
└──────────────────────────────────────────┴──────────────────────────────────────────┘

•Additional Rule Logic Scenarios:

a)Scenario A (Restricted Telnet List):

1.Policy: Permit internal hosts to initiate or accept Telnet connections to/from only a pre-specified list of external hosts.

2.Configuration: Forward only TCP packets with Port 23 (Telnet) where the external IP matches the pre-specified whitelist.

b)Scenario B (Outbound-Only TCP Initiation):

1.Policy: Allow internal hosts to initiate TCP connections to external hosts, but prevent external hosts from initiating TCP connections to internal hosts.

2.Configuration: Exploit TCP handshake flags — the very first packet (SYN) in every TCP connection has ACK = 0, while all subsequent packets in an established session have ACK = 1. Drop all incoming TCP packets with ACK = 0.

4. Worked Access Control List (ACL) Example (Network 222.22/16)

•Scenario:

↳An organization owns IP block 222.22/16. Evaluate the following stateless Access Control List (ACL) rules top-to-bottom:

┌────────┬────────────────┬────────────────┬──────────┬──────────┬───────────┬──────┐
│ Action │ Source Address │ Dest. Address  │ Protocol │ Src Port │ Dest Port │ Flag │
├────────┼────────────────┼────────────────┼──────────┼──────────┼───────────┼──────┤
│ allow  │ 222.22/16      │ outside        │ TCP      │ > 1023   │ 80        │ any  │
│        │                │ 222.22/16      │          │          │           │      │
├────────┼────────────────┼────────────────┼──────────┼──────────┼───────────┼──────┤
│ allow  │ outside        │ 222.22/16      │ TCP      │ 80       │ > 1023    │ ACK  │
│        │ 222.22/16      │                │          │          │           │      │
├────────┼────────────────┼────────────────┼──────────┼──────────┼───────────┼──────┤
│ allow  │ 222.22/16      │ outside        │ UDP      │ > 1023   │ 53        │  —   │
│        │                │ 222.22/16      │          │          │           │      │
├────────┼────────────────┼────────────────┼──────────┼──────────┼───────────┼──────┤
│ allow  │ outside        │ 222.22/16      │ UDP      │ 53       │ > 1023    │  —   │
│        │ 222.22/16      │                │          │          │           │      │
├────────┼────────────────┼────────────────┼──────────┼──────────┼───────────┼──────┤
│ deny   │ all            │ all            │ all      │ all      │ all       │ all  │
└────────┴────────────────┴────────────────┴──────────┴──────────┴───────────┴──────┘

•Rule-by-Rule Interpretation:

a)Rules 1 & 2 Together:

1.Rule 1 allows internal users (ephemeral source port > 1023) to send HTTP requests (dest port 80) to external web servers.

2.Rule 2 allows external web servers (source port 80) to send replies back ONLY if the TCP ACK bit is set to 1 (blocking external SYN packets with ACK=0).

3.Combined Effect: Internal users can surf the external web, but external hosts cannot initiate TCP connections to internal machines.

b)Rules 3 & 4 Together:

1.Rule 3 allows internal hosts to send outbound UDP DNS queries (dest port 53).

2.Rule 4 allows external DNS servers (source port 53) to return DNS replies.

c)Rule 5 (Default Deny):

•Blocks all other traffic (e.g., external SSH/Telnet, UDP video streams).

5. Limitation of Traditional (Stateless) Packet Filters

1.Security Vulnerability in the Previous ACL:

a)In the stateless ACL (Rule 2), the firewall blindly permits ANY incoming packet from outside 222.22/16 as long as Source Port = 80 and the TCP ACK flag = 1.

b)Because the stateless filter has no memory of past packets, it never verifies whether an internal host actually initiated that TCP connection.

c)Exploit: An attacker can craft malformed packets with Source Port = 80 and ACK = 1 (e.g., for scanning, OS fingerprinting, or bypassing the firewall) and send them directly to internal systems.

2.Why Modifying the Stateless ACL Fails:

↳If the administrator simply modifies Rule 2 to block all incoming packets with Source Port = 80 and ACK = 1, internal users will no longer receive responses from legitimate external websites—completely breaking web browsing.

6. Stateful Packet Filter

1.Core Concept:

↳A Stateful Packet Filter overcomes stateless limitations by:

(a) Actively tracking all ongoing TCP connections in a dynamic Connection

Table.

(b) Using that session state knowledge to make context-aware filtering

decisions.

2.Dynamic TCP Connection Tracking Table:

↳Because the firewall observes TCP 3-way handshakes (SYN) for connection setup and FIN/RST packets for termination, it maintains an active state table:

┌─────────────────┬─────────────────────┬─────────────┬──────────────────┐
│ Source Address  │ Destination Address │ Source Port │ Destination Port │
├─────────────────┼─────────────────────┼─────────────┼──────────────────┤
│ 222.22.1.7      │ 37.96.87.123        │ 12699       │ 80               │
│ 222.22.93.2     │ 199.1.205.23        │ 37654       │ 80               │
│ 222.22.65.143   │ 203.77.240.43       │ 48712       │ 80               │
└─────────────────┴─────────────────────┴─────────────┴──────────────────┘

•Updated Stateful Access Control List (With "Check Connection" Column):

↳The stateful ACL adds a "Check Connection" column (marked with 'X' on inbound rules) instructing the firewall to verify against the Connection Table before allowing return traffic:

┌────────┬────────────┬────────────┬──────────┬──────────┬───────────┬──────┬────────────┐
│ Action │ Src Addr   │ Dest Addr  │ Protocol │ Src Port │ Dest Port │ Flag │ Check Conn │
├────────┼────────────┼────────────┼──────────┼──────────┼───────────┼──────┼────────────┤
│ allow  │ 222.22/16  │ outside    │ TCP      │ > 1023   │ 80        │ any  │            │
│ allow  │ outside    │ 222.22/16  │ TCP      │ 80       │ > 1023    │ ACK  │     X      │
│ allow  │ 222.22/16  │ outside    │ UDP      │ > 1023   │ 53        │  —   │            │
│ allow  │ outside    │ 222.22/16  │ UDP      │ 53       │ > 1023    │  —   │     X      │
│ deny   │ all        │ all        │ all      │ all      │ all       │ all  │            │
└────────┴────────────┴────────────┴──────────┴──────────┴───────────┴──────┴────────────┘

1.Worked Packet Scenarios (Stateful Evaluation):

a)Case 1: Malformed Attack Packet (Dropped)

1.Attacker sends packet: Src IP = 150.23.23.155, Src Port = 80, Dest Port = 12543, Flag = ACK.

2.Firewall matches Rule 2, sees Check Connection = X, queries the Connection Table, finds NO matching active session, and immediately drops the packet.

b)Case 2: Legitimate Internal Web Surfing (Allowed)

1.Internal host sends TCP SYN to external web server (Port 80); firewall records the 4-tuple in the Connection Table.

2.Web server replies with ACK = 1; firewall checks the Connection Table, confirms an active session is in progress, and permits the packet.

2.Handling Connectionless UDP Traffic in Stateful Firewalls:

a)Challenge: Unlike TCP, UDP does not use 3-way handshakes (SYN) or teardown flags (FIN).

b)Solution: To track UDP flows (such as DNS queries on Port 53), a stateful filter records the 4-tuple (Source IP, Destination IP, Source Port, Destination Port) upon seeing an outbound UDP query and keeps the state open temporarily (using a short timeout) to accept the matching reply.

7. Application Gateways (Proxy Firewalls)

1.Why Packet Filters Are Not Enough:

a)Both traditional and stateful packet filters inspect only Layer 3 and Layer 4 headers (IP, TCP, UDP, ICMP).

b)They cannot inspect Application Layer payloads or verify user identities.

c)Policy Example Requiring an Application Gateway:

1.Allow outbound Telnet (Port 23) to external hosts ONLY for a restricted, privileged set of internal users.

2.Require those privileged users to authenticate themselves first before establishing external Telnet sessions.

3.Block all inbound Telnet connections from external hosts.

2.Definition & Architecture:

a)An Application Gateway is an application-specific proxy server through which all application-layer traffic must pass.

b)Makes security policy decisions based directly on Application Layer data (usernames, passwords, commands, URLs).

3.Application Gateway Architecture Diagram:

Internal Host           Application Gateway          Router & Filter         External Host
┌───────────┐           ┌─────────────────┐          ┌─────────────┐         ┌───────────┐
│           │─(1)Telnet►│                 │          │             │         │           │
│           │  Session  │  Authenticates  │          │  Allows ONLY│         │           │
│           │◄─(2)Auth──│  User & Checks  │          │  Telnet from│         │           │
│           │  Prompt   │  Permissions    │          │  App Gateway│         │           │
│           │           │                 │─(3)New──►│  IP Address │─Telnet─►│           │
│           │◄══════════│  Relays Data    │═Telnet═══│             │═Session═│           │
└───────────┘           └─────────────────┘ Session  └─────────────┘         └───────────┘

1.Step-by-Step Workflow (Telnet Application Gateway):

1.Router Configuration:

↳The perimeter router's packet filter is configured to block ALL Telnet connections except those originating directly from the IP address of the Application Gateway (automatically blocking external inbound Telnet).

2.Host-to-Gateway Session & Authentication:

a)An internal user wishing to Telnet externally must first open a Telnet session with the Application Gateway.

b)The gateway prompts the user for a username and password and checks if the user is on the authorized list. If unauthorized, the gateway terminates the connection immediately.

3.Gateway-to-External Session & Relaying:

↳If authorized, the gateway prompts for the target external hostname, initiates a separate Telnet connection from itself to the external host (which the router filter permits), and relays traffic between the two connections.

2.Drawbacks of Application Gateways:

1.Application-Specific Overhead: A separate, dedicated application gateway must be built and maintained for each distinct application protocol (e.g., one for Telnet, one for HTTP, one for FTP).

2.Performance Penalty: Because every packet must be processed up to the Application Layer and relayed across two separate connections, significant latency/throughput overhead is incurred.

↑ Back to contents

Chapter 9

Lab 5 — Security assessment & IDS/IPS tools (tcpdump, httprobe, nmap, Snort 3)

🧪 Lab 5.1 · Virtual Lab Environment & Operational Workflow

Detailed Technical Explanation:

1.Two-VM Sandbox Setup:

1.Kali Linux VM (Attacker / Analyst Machine): Executes reconnaissance, packet capture, and intrusion detection tools (tcpdump, httprobe, nmap, snort).

2.Ubuntu Server VM (Target / Vulnerable Machine): Hosts target network services.

2.Operational Best Practices:

a)Use the VM sidebar clipboard + Ctrl + Shift + V for pasting commands; refresh browser tab if VM session disconnects.

b)Open multiple terminal tabs (Ctrl + T) when running blocking listeners (like tcpdump or python3 -m http.server 80) alongside traffic generators (curl).

c)Work inside user home (cd ~) rather than root (/) when writing .txt or .pcap files to avoid permission errors.

Real-World Example:

Penetration testers and SOC engineers maintain isolated multi-VM lab networks (Kali attacker + vulnerable Ubuntu/Windows targets) to validate exploit signatures and firewall rules safely before deploying changes in production.

🧪 Lab 5.2 · tcpdump: Command-Line Packet Analysis & Traffic Monitoring

Detailed Technical Explanation:

1.Six-Stage Packet Capture Pipeline (Built on libpcap & Kernel BPF):

1.Network Interface (eth0, wlan0, lo, or any) receives physical frames.

2.OS Capture Mechanism copies frames from the NIC driver.

3.libpcap provides a low-level packet capture interface.

4.BPF (Berkeley Packet Filter) filters packets inside the kernel, discarding unmatched traffic before user-space copying for high speed.

5.tcpdump decodes headers and payloads into human-readable output.

6.Output / Storage displays to terminal or writes raw packets to .pcap.

2.Requires root (sudo) privileges; enables Promiscuous Mode by default to capture all local segment traffic regardless of MAC address (disable with -p).

3.Essential Flags & BPF Filter Expressions:

Syntax: sudo tcpdump [OPTIONS] [BPF FILTER EXPRESSION]

-i <iface>Select interface (eth0, lo, any).
-nnDisable DNS hostname (-n) and port-name (-nn) resolution—critical in security analysis to prevent outbound DNS leaks and speed up capture.
-c <count>Exit after capturing <count> packets.
-APrint payloads in ASCII (exposes plaintext HTTP headers/cookies).
-XPrint payloads in Hexadecimal + ASCII.
-v / -vvvIncrease header verbosity (TTL, IP ID, checksums, TCP options).
-s 0Set snaplength to 0 to capture full packets without truncation.
-w <file.pcap> / -r <file.pcap>Write raw packets to file / read offline.

–Key Security & Lab Commands:

1.Capture HTTP traffic on port 80 in ASCII:

sudo timeout 120 tcpdump -i any -nn -A 'tcp port 80'

2.Isolate all traffic to/from a specific host into a PCAP file:

sudo tcpdump -i any -nn host 192.168.56.10 -s 0 -w capture.pcap

3.Monitor DNS traffic (UDP 53): sudo tcpdump -i eth0 -nn 'udp port 53'

4.Subnet filter excluding SSH: sudo tcpdump 'src net 192.168.56.0/24 and not port 22'

5.Bitwise TCP Flag Detection (SYN Floods / RST Spikes):

sudo tcpdump 'tcp[tcpflags] & tcp-syn != 0' sudo tcpdump 'tcp[tcpflags] & tcp-rst != 0'

4.Wireshark Integration: Capture raw traffic on headless servers with tcpdump -w evidence.pcap, transfer the .pcap file to a workstation, and inspect visually in Wireshark.

Real-World Example:

When a headless production API server experiences intermittent connection drops, an engineer runs sudo tcpdump -i eth0 -nn -w api_drop.pcap 'port 443', downloads the .pcap file, and opens it in Wireshark to see repeated TCP [R] (RST) packets coming from an upstream load balancer.

⚠ Correction: tcp[tcpflags] & tcp-syn != 0 also matches SYN-ACK. To capture only initial SYNs use tcp[13] & 0x12 == 0x02. tcpdump prints relative sequence numbers unless -S is given.

🧪 Lab 5.3 · httprobe: HTTP/HTTPS Service Discovery & Web Reconnaissance

Detailed Technical Explanation:

1.Purpose & Six-Stage Pipeline:

–Written in Go by Tom Hudson (tomnomnom), httprobe accepts lists of domains/subdomains via standard input (stdin), resolves DNS, initiates TCP/TLS handshakes on ports 80 and 443 (plus custom ports) concurrently, and prints reachable http:// and https:// URLs to stdout.

2.Key CLI Flags & Pipeline Commands:

Standard pipelinecat domains.txt | httprobe | tee live_hosts.txt
`-p <protoport>: Probe non-standard web ports (-p http:8080 -p https:8443`).
-sSkip default ports 80 and 443 (probe only -p custom ports).
--prefer-httpsTest HTTPS first and skip HTTP if HTTPS responds.
-c <num>Set concurrency workers (default 20; e.g., -c 50).
-t <ms>Set probe timeout in milliseconds (e.g., -t 15000).

3.Limitations: Requires DNS resolution; does not crawl pages, scan non-HTTP ports, or test for CVEs.

Real-World Example:

During an external attack-surface assessment, an analyst pipes 3,000 discovered subdomains into cat subdomains.txt | httprobe -p http:8080 -p https:8443 --prefer-https and immediately discovers http://legacy-hr.company.com:8080 running unencrypted HTTP on an alternate port.

🧪 Lab 5.4 · Nmap: Network Discovery, Port Scanning, & Security Auditing

Detailed Technical Explanation:

1.Six Nmap Port States:

1.open (service actively accepting connections)

2.closed (host reachable, responds with RST, no service listening)

3.filtered (firewall drops probes or sends ICMP unreachable)

4.unfiltered (reachable via ACK scan -sA, open/closed undetermined)

5.open|filtered (no response in UDP/FIN/NULL/Xmas scans)

6.closed|filtered (only in IP ID Idle scans)

2.Essential Nmap Scan Commands:

a)Host discovery (Ping scan): nmap -sn 192.168.56.0/24 (skip ping: -Pn)

b)TCP SYN Half-Open Scan (-sS, default with sudo; sends SYN -> gets SYN/ACK -> sends RST):

sudo nmap -sS 192.168.56.10

c)TCP Connect Scan (-sT, non-root full 3-way handshake): nmap -sT 192.168.56.10

UDP Scan (-sU)sudo nmap -sU --top-ports 20 192.168.56.10
Firewall ACK Scan (-sA)sudo nmap -sA -p 22,80,443 192.168.56.10
Port Selection-p 22,80,443 | -p 1-1024 | -p- (all 65,535) | -F (top 100)
Service & Version Detection (-sV)nmap -sV -p 22,80,443 192.168.56.10

a)OS Fingerprinting (-O, analyzes TCP ISN/window/options/IP ID):

sudo nmap -O --osscan-guess 192.168.56.10

b)Nmap Scripting Engine (-sC default Lua scripts, --script <name>)

c)Aggressive Scan (-A, bundles -O -sV -sC --traceroute): sudo nmap -A -T4 192.168.56.10

d)Timing Templates (-T0 Paranoid to -T5 Insane) & Outputs (-oN, -oX, -oG, -oA).

Real-World Example:

A hospital security team runs sudo nmap -sS -sV -O -oA clinic_audit 10.50.0.0/24 and discovers an unauthorized rogue Raspberry Pi on the clinical network running an outdated OpenSSH server and unauthenticated Telnet on port 23.

🧪 Lab 5.5 · Snort 3: Network Intrusion Detection & Prevention System (IDS/IPS)

Detailed Technical Explanation:

1.Passive IDS vs. Active IPS:

a)Passive IDS (out-of-band SPAN/mirror port): Inspects copied traffic and generates alerts without delaying or dropping packets (zero production risk).

b)Active IPS (inline direct path): Sits directly in the traffic flow and actively drops malicious packets in real time (carries false-positive risk).

2.Detection Methodologies: Signature-Based (known patterns), Anomaly-Based (baseline deviations; catches zero-days), and Stateful Protocol Analysis.

3.Snort 3 Architecture & Pipeline:

a)Multi-threaded C++ engine configured via Lua (snort.lua), replacing single-threaded Snort 2 (snort.conf).

b)5-Stage Pipeline: DAQ (libpcap passive, afpacket Linux inline IPS, pcap offline file) -> Packet Decoder -> Preprocessors/Inspectors (stream reassembly/normalization) -> Detection Engine -> Output & Action Modules (alert_fast, alert_json for SIEM, alert_syslog).

4.Snort Rule Syntax & Actions:

a)Structure: [Action] [Protocol] [SrcIP] [SrcPort] -> [DstIP] [DstPort] ([Options])

b)Example (/etc/snort/rules/local.rules):

alert icmp any any -> any any (msg:"LAB - ICMP Echo Request Detected"; itype:8; sid:1000001; rev:1;)

c)Actions: alert, log, pass (IDS/IPS); drop, block, reject (Inline IPS only).

d)Options: msg, content, nocase, flow:established,to_server, itype:8, sid (>= 1000000), rev.

5.Key CLI Commands:

Test snort.lua syntaxsudo snort -c /etc/snort/snort.lua -T
Live Passive NIDSsudo snort -c /etc/snort/snort.lua -R local.rules -i eth0 -A alert_fast
Live Inline NIPSsudo snort -c /etc/snort/snort.lua --daq afpacket -i eth0 --mode inline -A alert_fast
Offline PCAP Analysissudo snort -c /etc/snort/snort.lua -R local.rules -r capture.pcap -A alert_fast

Real-World Example:

An online banking platform places Snort 3 inline in front of its web farm. When an attacker sends an HTTP payload containing a known remote code execution exploit string, Snort's detection engine matches the signature and executes drop in microseconds before the packet ever reaches the web application.

⚠ Correction: Snort 3 inline mode is -Q (or --daq-mode inline) with an interface pair, e.g. --daq afpacket -i eth0:eth1 -Q; --mode inline is not a Snort 3 option. drop/block/reject act only inline.

↑ Back to contents

PART THREE
Cryptography & Secure Protocols
Chapter 10

Lecture 15 — Introduction to symmetric cryptography & classical ciphers + Lab 2 (LFSR, RC4)

Introduction to Symmetric Cryptography & Cryptanalysis

•Content: Cryptography Fundamentals, Symmetric Architecture, Kerckhoffs' Principle, Quantum Impact (Grover's Algorithm), & Cryptanalysis, Classical Ciphers (Additive, Multiplicative, Affine, Keyless/Keyed Transposition), Stream vs. Block Ciphers, & the 3-Pass Lock Puzzle.

1. Introduction & Evolution of Cryptography

1.Core Analogy (Hiding Large Data with Small Secrets):

a)Cryptography hides a massive volume of data (e.g., terabytes) by protecting a tiny piece of secret data (a byte-sized key)—just like locking an entire house and only needing to hide a small physical key.

b)Also powers Secure Multi-Party Computation (e.g., three parties computing their combined total salary without revealing individual salaries), digital signatures, secure email, and blockchain systems.

2.Historical Shift (Art to Science):

a)Pre-20th Century: Treated primarily as an art using manual ciphers without formal mathematical definitions or security proofs.

b)Late 20th Century–Present: Evolved into a rigorous mathematical science.

3.Two Broad Categories of Cryptography:

1.Symmetric-Key Cryptography: Uses a single shared secret key for both encryption and decryption.

2.Asymmetric-Key (Public-Key) Cryptography: Uses a key generation algorithm to produce a mathematically linked pair—a Public Key and a Private Key.

2. Symmetric-Key Cipher Model & Mathematical Correctness

•General Architecture:

Alice (Sender) Bob (Receiver)

┌───────────────┐     Secure Key-Exchange Channel       ┌───────────────┐
│  Plaintext P  │ ───► [ Shared Secret Key K ] ◄─────── │               │
│      │        │                                       │               │
│      ▼        │                                       │               │
│ [ Encryption ]|                                       │ [ Decryption ]|
│  C = E_k(P)   │                                       │  P = D_k(C)   │
│      │        │                                       │      │        │
│      ▼        │         Insecure Channel              │      ▼        │
│ Ciphertext C  ├──────────────────────────────────────►│  Plaintext P  │
└───────────────┘        (Adversary Monitors)           └───────────────┘

1.Mathematical Formulation & Correctness Property:

EncryptionC = E_k(P)
DecryptionP = D_k(C)
Correctness RequirementDecrypting an encrypted message must always recover the exact original plaintext:

D_k(E_k(x)) = E_k(D_k(x)) = x

Proof: P_1 = D_k(C) = D_k(E_k(P)) = P.

2.Real-Life Numerical Analogy:

a)Alice and Bob privately agree on a random secret key K = 300.

b)To send her bank balance (P = 70,000), Alice computes C = 70,000 + 300 = 70,300 and sends 70,300 over an insecure channel.

c)An eavesdropper sees 70,300 but cannot distinguish whether it is 50,000 + 20,300 or 70,000 + 300 without knowing K. Bob subtracts K = 300 to recover 70,000.

3. Core Terminology & Adversary Models

1.Essential Definitions:

PlaintextThe original readable message/data (P).
CiphertextThe scrambled/coded message produced after encryption (C).
Enciphering / EncryptionTransforming plaintext into ciphertext.
Deciphering / DecryptionRestoring original plaintext from ciphertext.
Cryptographic System / CipherThe complete scheme (plaintext space, ciphertext space, key space, encryption & decryption algorithms).
CryptanalysisTechniques used to break a cipher or recover plaintext/keys without prior knowledge of the secret key.
CryptologyThe combined study of Cryptography + Cryptanalysis.
AdversaryA malicious entity attempting to compromise the communication.

2.Passive vs. Active Adversaries:

a)Passive Adversary (Figure 1.1):

•Only eavesdrops on ciphertext y sent from Alice to Bob to infer the plaintext or key (violates Confidentiality).

b)Active Adversary (Figure 1.2):

•Possesses stronger capabilities to disrupt or manipulate traffic:

(a) Tampering / Modification: Alters ciphertext y into y' before Bob

receives it (violates Data Integrity).

(b) Impersonation / Masquerade: Pretends to be Alice (while Alice is

inactive) and sends forged ciphertext y' to Bob (violates Authenticity).

(c) Unauthorized Redirection: Intercepts y intended for Bob and forwards

it to an unauthorized third party, Charlie.

4. Security Requirements, Kerckhoffs' Principle, & Key Size

1.Two Fundamental Security Requirements:

1.Strong Encryption Algorithm:

a)Minimum: An opponent who knows the algorithm and captures ciphertexts cannot decrypt them.

b)Stronger Form: Even if given multiple valid plaintext-ciphertext pairs (M_1, C_1), (M_2, C_2), the opponent still cannot discover K or forge/decrypt a new valid pair.

2.Secure Key Distribution & Session Keys:

a)Sender and receiver must exchange and store the secret key securely.

b)If K is compromised, all past and future messages encrypted under K are exposed; therefore, systems use Session Keys rotated periodically.

2.Kerckhoffs' Principle:

a)"Everything (the encryption and decryption algorithms) is public except for the secret key."

b)Why: Keeping large algorithms secret is impractical—if an insider leaks a secret algorithm, the entire system must be redesigned from scratch. If security relies solely on a random secret key K, a compromised key can simply be revoked and replaced with a new random key.

3.One-Time Pad (OTP) & True Randomness:

a)Example: Alice picks a 1-bit message P ∈ {0, 1} and a truly random 1-bit key K ∈ {0, 1}, computing C = P XOR K.

b)Even if an attacker sees C = 1 and knows the algorithm is XOR, C = 1 could come from (0 XOR 1) or (1 XOR 0) with equal 50% probability—achieving Perfect Secrecy even against infinite computational power.

4.Key Sizes & Post-Quantum Impact (Grover's Algorithm):

DES (56-bit key)Broken via brute force (cracked in ~22 hours); keys ≤ 64 bits are obsolete.
AES VariantsAES-128 (10 rounds), AES-192 (12 rounds), AES-256 (14 rounds). AES-128 is the standard balance of speed and security.
Post-Quantum Effect (Grover's Algorithm)A quantum computer reduces a classical b-bit symmetric security level to roughly b/2 bits:

1.AES-128 (2¹²⁸ classical steps) drops to 2⁶⁴ quantum steps.

2.AES-256 (2²⁵⁶ classical steps) drops to 2¹²⁸ quantum steps (remaining secure).

5. Three Independent Dimensions of Cryptographic Systems

Type of OperationsSubstitution (replacing symbols) vs. Transposition (reordering symbols), ensuring no information is lost.
Number of Keys UsedSymmetric-key (1 shared key) vs. Asymmetric-key (2 keys).
Plaintext Processing MethodBlock cipher (fixed-size chunks) vs. Stream cipher (one bit/symbol at a time).

6. Cryptanalysis & the Four Attack Models

1.Brute-Force Attack (Exhaustive Key Search):

↳Tries every possible key in the key space on a ciphertext until readable plaintext appears. Defended by using a large key space (> 64 bits).

2.Four Theoretical Cryptanalysis Attack Models (Ordered by Increasing Attacker Power):

┌───┬──────────────────────────┬────────────────────────────────────────────────────────┐
│ # │ Attack Model             │ Information / Capabilities Available to Adversary      │
├───┼──────────────────────────┼────────────────────────────────────────────────────────┤
│ 1 │ Ciphertext-Only (COA)    │ Only one or more ciphertexts C.                        │
├───┼──────────────────────────┼────────────────────────────────────────────────────────┤
│ 2 │ Known-Plaintext (KPA)    │ Ciphertexts PLUS one or more fixed plaintext-ciphertext│
│   │                          │ pairs (M_1, C_1), (M_2, C_2) created with the key.     │
├───┼──────────────────────────┼────────────────────────────────────────────────────────┤
│ 3 │ Chosen-Plaintext (CPA)   │ Encryption Oracle (black box): Adversary chooses any   │
│   │                          │ plaintext M_i and receives its ciphertext C_i.         │
├───┼──────────────────────────┼────────────────────────────────────────────────────────┤
│ 4 │ Chosen-Ciphertext (CCA)  │ Decryption Oracle (black box): Adversary chooses any   │
│   │                          │ ciphertext C_i and receives its decrypted plaintext M_i│
│   │                          │ (alongside encryption access). Hardest security level. │
└───┴──────────────────────────┴────────────────────────────────────────────────────────┘

7. Traditional Substitution Ciphers (Modular Arithmetic in Z_26)

•Core Concept:

a)Replaces each plaintext symbol with another symbol.

b)Monoalphabetic Cipher: Strict one-to-one mapping between a plaintext

character and a ciphertext character (e.g., plaintext "hello" ──► "KHOOR",

where both 'l' characters map to 'O').

↳Polyalphabetic Cipher: A single plaintext character can map to different

ciphertext characters depending on position (e.g., plaintext "hello" ──►

"ABNZF", where the two 'l' characters map to 'N' and 'Z'). Examples

mentioned: Vigenère cipher, Hill cipher.

•Numerical Encoding Table (Z_26 = {0, 1, ..., 25}):

┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│a/A│b/B│c/C│d/D│e/E│f/F│g/G│h/H│i/I│j/J│k/K│l/L│m/M│
│00 │01 │02 │03 │04 │05 │06 │07 │08 │09 │10 │11 │12 │
├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤
│n/N│o/O│p/P│q/Q│r/R│s/S│t/T│u/U│v/V│w/W│x/X│y/Y│z/Z│
│13 │14 │15 │16 │17 │18 │19 │20 │21 │22 │23 │24 │25 │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

1.Scheme 1: Additive Cipher (Shift Cipher / Caesar Cipher):

SpacesPlaintext P ∈ Z_26, Ciphertext C ∈ Z_26, Key k ∈ Z_26.
EncryptionC = (P + k) mod 26
DecryptionP = (C - k) mod 26
Note on Caesar CipherSpecific case where k = 3 (e.g., "hello" ──► "KHOOR").

a)Worked Example from Lecture:

GivenPlaintext P = 'l' (11), Shared Key k = 20.
EncryptC = (11 + 20) mod 26 = 31 mod 26 = 5 ──► 'F'.
DecryptP = (5 - 20) mod 26 = -15 mod 26 = (-15 + 26) mod 26 = 11 ──► 'l'.

b)Cryptanalysis:

•Completely insecure against Ciphertext-Only brute-force attacks because there are only 26 keys (and k = 0 is useless since C = P, leaving only 25 effective keys).

2.Scheme 2: Multiplicative Cipher:

SpacesPlaintext P ∈ Z_26, Ciphertext C ∈ Z_26, Key k ∈ Z_26*.
EncryptionC = (P × k) mod 26
DecryptionP = (C × k⁻¹) mod 26 (where k⁻¹ is the multiplicative inverse of k modulo 26 such that k × k⁻¹ ≡ 1 mod 26).

a)Invertibility Condition (Z_26*):

1.Not every integer in Z_26 has a multiplicative inverse (e.g., even numbers and 13 have no inverse).

2.A key k is invertible in Z_26 if and only if gcd(26, k) = 1.

3.Valid keys in Z_26*: {1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25} (only 12 keys total, given by Euler's totient function φ(26) = 12).

4.Example: 3 and 9 are inverses because (3 × 9) mod 26 = 27 mod 26 = 1.

b)Cryptanalysis:

•Even weaker against brute force than the Additive Cipher because its key space is smaller (only 12 keys, or 11 non-trivial keys since k = 1 leaves plaintext unchanged).

3.Scheme 3: Affine Cipher (Combination of Multiplicative + Additive):

SpacesPlaintext P ∈ Z_26, Ciphertext C ∈ Z_26, Key Pair (k_1, k_2) where k_1 ∈ Z_26* and k_2 ∈ Z_26.
EncryptionT = (P × k_1) mod 26 ──► C = (T + k_2) mod 26 Combined: C = (P × k_1 + k_2) mod 26
DecryptionT = (C - k_2) mod 26 ──► P = (T × k_1⁻¹) mod 26 Combined: P = ((C - k_2) × k_1⁻¹) mod 26
Key Space Sizeφ(26) × 26 = 12 × 26 = 312 total keys.

↳Cryptanalysis:

•Still broken easily via brute force (312 keys) and Statistical Frequency Analysis.

4.General Monoalphabetic Substitution & Statistical Attacks:

a)Arbitrary Permutation Table: Mapping the 26 letters via a random lookup table expands the key space to 26! (26 factorial), defeating brute-force key search.

b)Statistical / Frequency Analysis Attack: Because each plaintext letter always maps to the exact same ciphertext symbol, an attacker analyzes letter frequencies in the ciphertext (e.g., 'E' is the most frequent letter in standard English) to deduce the substitution mapping without brute force.

8. Transposition Ciphers (Reordering Symbols)

1.Core Concept:

↳Instead of replacing characters, a transposition cipher preserves the exact original characters and scrambles their positions.

2.Method 1: Keyless Transposition Cipher (Matrix Row/Column Reordering):

↳Example ("meet me at the park"):

1.Sender and receiver agree on a fixed row width (e.g., 4 characters per row).

2.Write plaintext row-by-row (padding incomplete rows if needed):

m e e t

m e a t

t h e p

a r k z (bogus padding character 'z')

3.Read ciphertext column-by-column: "MMTA EEHR EAEK TTPZ".

4.Decryption: Receiver writes the ciphertext column-by-column into a 4-column grid (or jumps by steps of 4) and reads row-by-row to recover the message.

3.Method 2: Keyed Transposition Cipher (Block Permutation):

↳Worked Example ("Enemy attacks tonight"):

1.Group into 5-character blocks and pad the final block with 'z':

Block 1e n e m y
Block 2a t t a c
Block 3k s t o n
Block 4i g h t z

2.Shared Permutation Key:

Encryption Rule : [ 3  1  4  5  2 ] ──► [ 1  2  3  4  5 ]

(3rd char moves to 1st, 1st moves to 2nd, 4th to 3rd, 5th to 4th, 2nd to 5th)

3.Resulting Ciphertext Blocks:

"EEMYN"  "TAACT"  "TKONS"  "HITZG"  ──► "EEMYNTAACTTKONSHITZG"

4.Decryption Key (Inverse Permutation):

Decryption Rule : [ 2  5  1  3  4 ] ──► [ 1  2  3  4  5 ]

•Method 3: Combined Keyless + Keyed Transposition:

↳Writes plaintext row-by-row into a 2D table, permutes the columns using a key (e.g., 3 1 4 5 2), and reads out column-by-column ("ETTHEAKIMAOTYCNZNTSG").

9. Stream Ciphers vs. Block Ciphers

1.Stream Cipher:

a)Encrypts and decrypts data one symbol (1 bit or 1 character) at a time using a continuous keystream K = (k_1, k_2, k_3, ...).

b)Examples: RC4, Salsa20, ChaCha20, LFSR-based ciphers.

2.Block Cipher:

a)Divides plaintext into fixed-size blocks of m symbols (m > 1) and encrypts each entire block together under a single shared key K.

b)Padding: If the final plaintext chunk is shorter than the required block size, padding bits/bytes (e.g., PKCS#7 padding) are appended before encryption.

c)Examples:

DES64-bit block size (56-bit key, 16 rounds).
AES-128128-bit block size (128-bit key, 10 rounds).
AES-192128-bit block size (192-bit key, 12 rounds).
AES-256128-bit block size (256-bit key, 14 rounds).

1. Solution to the Lecture Puzzle (Three-pass Protocol / Double-Lock BOX)

1.The Puzzle:

↳Alice (in Allahabad) wants to send a secret note in a locked box to Bob (in Bengaluru) via an untrusted courier, without ever sharing or shipping her physical key.

2.The 3-Pass Solution (Shamir's No-Key Protocol Concept):

1. Pass 1 (Alice ──► Bob): Alice puts the secret inside the box, locks it

with her own padlock (Lock A), keeps Key A, and ships the box to Bob.

2. Pass 2 (Bob ──► Alice): Bob cannot open Lock A, so he attaches his own

padlock (Lock B) onto the box alongside Lock A, keeps Key B, and ships

the doubly-locked box back to Alice. (Courier still cannot open it).

3. Pass 3 (Alice ──► Bob): Alice unlocks and removes her own padlock (Lock A)

using Key A, leaving Lock B intact, and ships the box back to Bob. Bob

uses Key B to unlock Lock B and reads the secret.

🧪 Lab 2.1–2.2 · Cryptology terminology, attack models & perfect secrecy (merged)

Kerckhoffs' principle, the four attack models, the shift cipher and the one-time pad are covered in Lecture 15 above. Points the lab adds:

PointDetail
Cryptosystem 5-tuple(P, C, K, E, D): plaintext space, ciphertext space, key space, encryption functions ek: P→C, decryption functions dk: C→P with dk(ek(x)) = x.
TaxonomySymmetric → stream (LFSR, RC4) and block (DES, AES/Rijndael, IDEA, RC6); asymmetric = public/private key pair (encrypt/verify vs decrypt/sign).
Monoalphabetic substitutionKey = any permutation of 26 letters, |K| = 26! ≈ 4×1026 ≈ 288. Brute force infeasible, but letter frequencies survive → frequency analysis (E ≈ 12.7%, T ≈ 9.1%, A ≈ 8.2%).
Vigenère (polyalphabetic)Repeating keyword k = (k1…km) ∈ (Z26)m; flattens single-letter frequencies across m positions.
TranspositionRail fence (write column-wise, read row-wise) or block permutation π, decrypted with π−1.
One-way securityGiven c = Enc(k, m), no efficient algorithm recovers all of m — weak if the message space is tiny ("buy"/"sell").
Perfect secrecy (Shannon)Pr[X = x | Y = y] = Pr[X = x]; equivalently Pr[Enc(m1,k) = c] = Pr[Enc(m2,k) = c] for all m1, m2, c. OTP: Pr[Enck(m) = c] = 2−n.
Shannon's key-length theoremPerfect secrecy needs |K| ≥ |M| and no key reuse: c1 ⊕ c2 = m1 ⊕ m2 leaks plaintext. Hence stream ciphers expand a short seed with a PRNG.
ExampleEnigma (WWII): design known to Bletchley Park; security rested on daily rotor/plugboard settings (the key). Moscow–Washington hotline used paper OTP tapes.

🧪 Lab 2.3 · Linear Feedback Shift Registers (LFSR)

Detailed Conceptual Explanation:

1.Hardware Architecture & Clock Mechanics:

a)An L-stage LFSR consists of L 1-bit flip-flop registers (z_0, z_1, ..., z_{L-1}) initialized with an L-bit secret seed.

b)On each clock tick:

1.Output bit is tapped from z_0.

2.Remaining bits shift one stage left (z_1 -> z_0, z_2 -> z_1, ..., z_{L-1} -> z_{L-2}).

3.New feedback bit entering z_{L-1} is computed as the XOR (addition mod 2) of tapped registers: z_new = sum(c_j * z_j) mod 2.

c)Maximum sequence period before repeating is 2^L - 1 bits.

2.Reconstruction Attack (Why Pure LFSRs Fail):

a)Because feedback is strictly linear over GF(2), an attacker who captures 2L consecutive output bits (e.g., 8 bits for a 4-bit LFSR) can form L linear equations and algebraically solve for all feedback coefficients c_j and the internal seed state.

b)Historical Multi-LFSR Schemes (All Broken):

DVD Content Scrambling System (CSS)40-bit (5-byte) disk key split into LFSR-17 (16 bits + '1') and LFSR-25 (24 bits + '1'), combined via bit-inversion and mod-256 addition.
GSM Mobile Encryption (A5/1, A5/2)3 irregularly clocked LFSRs.
Bluetooth (E0)4 LFSRs.

Real-World Example:

Every 1990s DVD player contained a hardware chip running two LFSRs (17-bit and 25-bit) to descramble movie bytes using a 40-bit disk key. In 1999, researchers exploited the linear feedback math to publish DeCSS, allowing any PC to crack DVD encryption in seconds.

🧪 Lab 2.4 · RC4 Stream Cipher (KSA, PRGA, & Cryptanalysis)

Detailed Walkthrough:

1.Overview: Designed by Ron Rivest (1987), made public in 1994. A byte-oriented stream cipher (processes 8-bit bytes rather than single bits) with variable key size (40–256 bits; e.g., 128-bit = 16-byte seed), renowned for very fast software execution.

2.Step 1: Initialization of State Vector (S) & Temporary Vector (T):

a)S[0..255]: 256-byte array initialized sequentially (S[0] = 0, S[1] = 1, ..., S[255] = 255).

b)T[0..255]: 256-byte array filled by repeating the secret seed key K of byte length keylen until full: T[i] = K[i mod keylen] for i = 0..255.

3.Step 2: Key-Scheduling Algorithm (KSA) - Shuffling S:

j = 0
for i = 0 to 255:
    j = (j + S[i] + T[i]) mod 256
    SWAP(S[i], S[j])

–Permutes S pseudo-randomly using T; once finished, T and K are discarded.

•Step 3: Pseudo-Random Generation Algorithm (PRGA) - Generating Keystream Bytes:

i = 0, j = 0
while (true):
    i = (i + 1) mod 256
    j = (j + S[i]) mod 256
    SWAP(S[i], S[j])
    t = (S[i] + S[j]) mod 256
    Output keystream byte k = S[t]   // Ciphertext_byte = Plaintext_byte XOR S[t]

–Theoretical period for a 128-bit key exceeds 10^100 bytes.

•Cryptanalysis & Deprecation:

a)Initial Output Bias (Second-Byte Bias): If S[2] = 0 and S[1] != 2 after KSA, the 2nd PRGA output byte is guaranteed to be 0 with probability 1 (across random states, Pr[2nd output = 0] ~ 2/256 instead of 1/256).

b)Although dropping early bytes (RC4-drop[768]) mitigates initial biases, cumulative statistical biases led to RC4 being banned in modern TLS/HTTPS in favor of AES block ciphers.

Real-World Example:

Early Wi-Fi WEP security concatenated a 24-bit Initialization Vector with the network password and fed it directly into RC4 without dropping initial bytes. By capturing ~40,000 encrypted Wi-Fi packets, tools like Aircrack-ng exploited RC4's early-byte statistical biases to recover any WEP Wi-Fi password in under 60 seconds.

🧪 Lab 2.5 · Lab Experiment 2: RC4 Chat, Wireshark, Nmap, & Traceroute

Detailed Walkthrough:

•RC4 Encrypted Chat (server_rc4.cpp & client_rc4.cpp):

a)Three terminals on TCP Port 8080: a multi-threaded C++ relay server forwards raw bytes between Client 1 and Client 2.

b)Clients exchange Diffie-Hellman public values (BASE = 3, MOD = 19) to derive shared_secret, initialize their local 256-byte RC4 state arrays, and encrypt/decrypt messages locally while the relay server sees only gibberish.

WiresharkGUI network packet analyzer capturing live NIC traffic or opening .pcapng files to inspect timestamps, source/dest IPs, protocols, and payloads.
NmapActive network mapper scanning active hosts and open ports (nmap 127.0.0.1, nmap 192.168.1.0/24).
TracerouteMaps the router-by-router path to a destination (traceroute <host> on Linux/macOS, tracert <host> on Windows; -6 for IPv6, -m for max hops).

Real-World Example:

When troubleshooting an outage between a branch office and a cloud server, a network engineer runs traceroute to pinpoint which ISP router is dropping packets, runs nmap to verify the server's application ports are open, and inspects the raw packet handshake in Wireshark.

↑ Back to contents

Chapter 11

Lab 3 — Diffie-Hellman & RSA: man-in-the-middle

🧪 Lab 3.1 · Man-in-the-Middle (MitM) Attack on Diffie-Hellman (Brute-Force DLP)

Detailed Conceptual Explanation:

1.How Diffie-Hellman (DH) Key Agreement Works:

–Diffie-Hellman enables two endpoints (Client 1 and Client 2) to establish a shared secret symmetric key over a completely public, untrusted network without ever transmitting the secret key itself.

Public Domain ParametersGenerator base g = 3 and prime modulus p = 19.
Step 1Client 1 picks a random private exponent a, computes its public half-key A = (3^a) mod 19, and sends A to the relay server to pass to Client 2.
Step 2Client 2 picks a random private exponent b, computes its public half-key B = (3^b) mod 19, and sends B to the relay server to pass to Client 1.
Step 3Both clients independently raise the received half-key to their own private exponent modulo 19:

1.Client 1 computes: K = (B^a) mod 19 = (3^(b*a)) mod 19

2.Client 2 computes: K = (A^b) mod 19 = (3^(a*b)) mod 19

Both arrive at the exact same integer K and feed it into RC4 as their symmetric encryption seed.

2.How the Untrusted Relay Server Executes the MitM Exploit:

a)Mathematical Weakness: Diffie-Hellman security depends on the Discrete Logarithm Problem (DLP) being computationally infeasible—given g, p, and A = (g^a) mod p, finding a should take millennia. Because the lab uses a tiny prime (p = 19), the DLP is trivial to break.

b)Step-by-Step Server Attack Workflow:

1.Half-Key Interception: When Client 1 sends A (e.g., A = 5), the server records A while forwarding it transparently to Client 2 so neither client detects any interruption.

2.Brute-Force Discrete Logarithm Loop: The server runs a for loop testing every candidate exponent exp from 1 to p - 1 (1 to 18):

if (modExp(3, exp) == halfKey) -> recovers Client 1's private secret a (e.g., finding exp = 6 in 6 iterations).

3.Deriving the Shared Secret: Once Client 2 sends its public half-key B (e.g., B = 11), the server computes:

K_server = (B^exp) mod 19 = (11^6) mod 19 = 18 (matching both clients).

4.Real-Time Eavesdropping: Whenever Client 1 or Client 2 sends an RC4-encrypted message, the server forwards the ciphertext untouched to the recipient AND decrypts a local copy using K_server to read the plaintext live.

3.Passive MitM (Sniffing) vs. Active MitM (Tampering):

a)Passive MitM reads intercepted traffic silently without modifying packets.

b)Active MitM intercepts, decrypts, alters message contents (e.g., changing a bank account number), re-encrypts with the stolen key, and forwards it.

4.Real-World Countermeasures:

1.Use cryptographically large prime moduli (>= 2048 bits or 4096 bits) so brute-forcing the Discrete Logarithm Problem is computationally impossible.

2.Authenticate public half-keys using digital signatures / X.509 certificates (Authenticated Diffie-Hellman / ECDHE).

Real-World Example:

In 2015, security researchers uncovered the Logjam vulnerability affecting thousands of HTTPS web and mail servers. Legacy TLS configurations allowed an active MitM attacker to downgrade Diffie-Hellman key exchanges to weak 512-bit "export-grade" prime numbers. Using precomputed discrete logarithm tables, attackers could recover the shared session key in seconds and silently decrypt HTTPS web sessions in real time.

⚠ Correction: Arithmetic in the worked example is wrong. Powers of 3 mod 19 are 3, 9, 8, 5, 15, 7, 2, 6, 18, 16, 10, 11… So A = 5 ⇒ a = 4 (found in 4 iterations, not 6; 3⁶ mod 19 = 7). With B = 11: K = 11⁴ mod 19 = 11 (and 11⁶ mod 19 = 1, not 18). Check: b = 12, 5¹² mod 19 = 11 ✔.

🧪 Lab 3.2 · RSA Public-Key Client-Server Encryption

Detailed Conceptual Explanation:

1.Asymmetric Key Pair Architecture:

a)Unlike symmetric ciphers (RC4) that use one shared secret key, RSA relies on two mathematically linked keys derived from two large secret prime numbers p and q (n = p * q):

1.Public Key (e, n): Shared openly with any connecting client; used exclusively to encrypt outgoing messages (or verify signatures).

2.Private Key (d, n): Kept strictly confidential on the server; used exclusively to decrypt incoming ciphertexts (or create signatures).

b)Security relies on the computational hardness of Prime Factorization:

multiplying p * q takes microseconds, but factoring a 2048-bit modulus n back into p and q is infeasible on classical computers.

c)C/C++ Implementation Note: Requires linking OpenSSL cryptographic libraries during compilation (g++ server.cpp -lssl -lcrypto).

2.Client-Server Execution Workflow:

Server Key Generation & ListeningServer generates an RSA private/public key pair and opens a listening TCP socket.
Public Key DistributionWhen a client connects (connect()), the server transmits its RSA Public Key to the client.
Randomized Padding & Encryption (Client Side)Before encrypting a short plaintext (e.g., "hello"), the client applies random padding (such as OAEP or PKCS#1 padding) to fill the required RSA block bit-length and ensure encrypting "hello" twice produces two completely different ciphertexts. It encrypts the padded block using the server's Public Key and transmits the ciphertext over the socket.
Decryption (Server Side)Server receives the ciphertext and decrypts it using its Private Key to recover the original plaintext.

3.Unauthenticated RSA MitM Risk & Key Length Standards:

a)Active MitM on Unauthenticated RSA: If a client blindly accepts whatever public key arrives over the socket without verifying a trusted Certificate Authority (CA) signature, an attacker in the middle can intercept the server's public key, send their own public key to the client, decrypt the client's message with their own private key, read/modify it, and re-encrypt it with the real server's public key.

b)Industry Key Size Standard: Minimum 2048-bit (2^11 bits) modulus is required today (or 4096-bit for high-security root certificates).

Real-World Example:

Every time you connect to a cloud Linux server via SSH (ssh ubuntu@server-ip) or load an HTTPS banking portal, your client verifies the server's RSA/ECDSA public key certificate and uses public-key cryptography to securely establish the session without ever sending passwords in plaintext.

↑ Back to contents

Chapter 12

Lab 6 — IP Security (IPsec)

🧪 Lab 6.1 · SSL/TLS vs. IPsec & Core Security Databases (SPD & SAD)

Detailed Conceptual Explanation:

1.Architectural Layer Placement & System Impact:

a)SSL / TLS (Secure Sockets Layer / Transport Layer Security):

1.Operates at the Socket Layer (between the Application Layer and Transport Layer, residing inside user space).

2.Provides encryption, integrity, and authentication with a relatively simple specification.

3.Requires modifications at the application level (each application—such as Chrome, Outlook, or a custom client—must explicitly implement TLS libraries), but requires ZERO changes to the OS kernel.

b)IPsec (Internet Protocol Security):

1.Operates at the Network Layer (IP Layer) inside the OS kernel and gateway routers.

2.Provides encryption, integrity, and authentication across all IP traffic.

3.Requires configuration/changes at the OS kernel or network gateway level, requiring ZERO changes to user applications—any protocol running over IP (HTTP, FTP, SMTP, SSH, or custom UDP apps) automatically inherits network-layer protection transparently.

4.Primarily deployed in Virtual Private Networks (VPNs) to establish encrypted tunnels between branch offices or remote employees.

5.Trade-off: Significantly more complex specification than SSL/TLS, historically presenting interoperability challenges across vendors.

2.Six Core Security Services Provided by IPsec:

Data Content ConfidentialityEncrypts IP packet payloads using symmetric ciphers (e.g., AES, 3DES, DES) so eavesdroppers cannot read data.
Connectionless IntegrityUses cryptographic Message Authentication Codes (HMAC-SHA1, HMAC-SHA256, HMAC-MD5) to verify each individual packet was not altered in transit, without requiring connection-state tracking.
Data Origin AuthenticationCryptographically proves the packet came from the authenticated peer holding the shared secret key.
Anti-Replay ProtectionPrevents an attacker from capturing a valid encrypted packet and re-transmitting it later using monotonically increasing 32-bit Sequence Numbers verified against a sliding receiver window.
Partial Data PrivacyProtects private internal IP addresses and sequence metadata from external inspection.

6.Limited Traffic Flow Confidentiality / Masking: Hides internal host-to-host communication patterns by encapsulating traffic behind gateway IPs and adding variable-length padding in Tunnel Mode.

3.Two Major Operational Components of IPsec:

1.IKE (Internet Key Exchange): Negotiates cryptographic parameters, performs mutual authentication, and establishes shared symmetric session keys via Diffie-Hellman key exchange in two phases before data flows.

2.Security Protocols (AH & ESP): Encapsulate, authenticate, and/or encrypt IP packets using the negotiated Security Associations.

4.Two Essential IPsec Kernel Databases (Maintained at Both Endpoints/Gateways):

1.SPD (Security Policy Database):

a)An ordered table of security rules consulted by the OS IP stack for every inbound and outbound IP packet (using selectors such as Source IP, Destination IP, and transport protocol).

b)Three Possible Policy Actions:

DiscardDrop the packet immediately.
Bypass IPsecTransmit or accept the packet in plaintext without IPsec processing (e.g., local LAN management traffic).
Apply IPsecProtect the packet using a specific Security Association (SA) from the SAD.

2.SAD (Security Association Database):

a)Stores the active cryptographic state and parameters for each established Security Association (SA)—a simplex (one-way) logical connection. Because SAs are directional, two hosts (M1 and D1) require TWO separate SAs: one for outbound (M1 -> D1) and one for inbound (D1 -> M1).

b)Unique SA Identifier Tuple (3 Parameters):

SPI (Security Parameters Index)A unique 32-bit integer/hex tag chosen by the receiving host/router and stamped into every IPsec header so the receiver knows which SAD entry to look up.
Destination IP AddressTarget host or VPN gateway IP address.
IPsec Protocol Identifier51 for AH or 50 for ESP.

c)Stored SAD Entry Attributes: Encryption algorithm & key, authentication (HMAC) algorithm & key, key lifetimes, 32-bit Sequence Number counter, Sequence Number overflow flag, Anti-Replay Window size, IPsec Mode (Transport vs. Tunnel), and Path MTU.

Real-World Example:

A hospital group links its main diagnostics center in Hyderabad with three satellite clinics over the public internet. Instead of rewriting 25 legacy radiology and patient-record applications to add SSL/TLS encryption, the IT team configures IPsec on the edge routers. The SPD automatically catches all inter-clinic IP traffic and encrypts it via the SAD tunnel keys before it touches the public ISP network.

⚠ Correction: Service 5 ("Partial Data Privacy") is not an RFC term. RFC 4301 lists: access control, connectionless integrity, data-origin authentication, anti-replay, confidentiality, limited traffic-flow confidentiality.

🧪 Lab 6.2 · IPv4 Header Review: Mutable vs. Immutable Fields

Detailed Conceptual Explanation:

1.Why Field Mutability Matters for Packet Authentication:

a)To authenticate an IP packet, the sender passes the packet through a cryptographic HMAC function using a shared secret key to generate an ICV (Integrity Check Value / MAC) and embeds it in the IPsec header.

b)Upon arrival, the receiver runs the exact same HMAC calculation over the received packet and verifies that its computed MAC matches the received ICV.

c)However, certain IPv4 header fields are legitimately modified by routers at every hop during normal internet routing. If those mutable fields were included in the sender's MAC calculation, the receiver's MAC would never match, causing every valid packet to be dropped!

2.Immutable IPv4 Header Fields (Covered by Authentication):

–Version (4), Header Length (IHL), Total Length (adjusted to include the IPsec header), Identification, Protocol (updated to 51 for AH or 50 for ESP), Source IP Address, and Destination IP Address.

3.Mutable IPv4 Header Fields (Zeroed Out / Excluded During MAC Calculation):

a)TTL (Time-To-Live): Decremented by 1 at every router hop to prevent infinite routing loops (when TTL == 0, the packet is discarded).

b)Header Checksum: Recomputed at every router because TTL changes.

c)Type of Service (TOS) / DSCP, Flags, and Fragmentation Offset.

Real-World Example:

When an authenticated IPsec packet travels across 14 internet routers from Bhubaneswar to Frankfurt, its TTL drops from 64 to 50 and its IP Header Checksum is recalculated 14 times. Because IPsec Authentication Header zeroes out TTL and Header Checksum before computing the SHA-256 HMAC, the Frankfurt server computes the exact same HMAC as the Bhubaneswar sender and validates the packet cleanly.

🧪 Lab 6.3 · IPsec Modes (Transport vs. Tunnel) & Protocols (AH vs. ESP)

Detailed Conceptual Explanation:

1.IPsec operates in two modes (Transport vs. Tunnel) and uses two protocols (AH vs. ESP), yielding four possible combinations:

2.Mode 1: Transport Mode (End-to-End Host-to-Host):

a)Designed primarily for direct host-to-host communication (e.g., workstation to internal server).

b)Packet Layout: [Original IP Header] + [IPsec Header (AH/ESP)] + [TCP/UDP + Data]

c)Characteristics: Adds minimal header overhead (high bandwidth efficiency), but leaves the original IP header exposed in clear—passive eavesdroppers can see which source and destination IP addresses are communicating.

3.Mode 2: Tunnel Mode (Gateway-to-Gateway / Site-to-Site VPN & Remote Access):

a)Designed primarily for firewall-to-firewall / gateway-to-gateway VPNs (Case 2) or remote laptop-to-gateway VPNs (Case 3).

b)Packet Layout: [New Outer IP Header] + [IPsec Header (AH/ESP)] + [Original Inner IP Header + TCP/UDP + Data]

c)Encapsulates the entire original IP packet inside a brand-new outer IP datagram whose source/destination IPs are the two VPN gateways (and sets the IPsec Next Header field to 4 for IP-in-IP encapsulation).

d)Characteristics: Higher header overhead, but completely hides internal private host IP addresses behind the public gateway IPs.

4.Protocol A: Authentication Header (AH - RFC 4302, IP Protocol Number 51):

a)Services Provided: Connectionless integrity, data origin authentication, and anti-replay protection.

b)AH Header Structure:

Next Header (8 bits)Protocol of the encapsulated payload (6 = TCP in Transport Mode; 4 = IPv4 in Tunnel Mode).
Payload Length (8 bits)Length of AH header in 32-bit words minus 2.
Reserved (16 bits)Set to all zeros.
SPI (32 bits)Security Parameters Index.
Sequence Number (32 bits)Monotonically increasing counter for anti-replay sliding window verification.
Authentication Data (Variable)Cryptographic HMAC/ICV computed over all immutable IP header fields + AH header + entire payload.

c)Critical Limitation 1 (NO Confidentiality): AH does not encrypt data; all payloads travel in plaintext.

d)Critical Limitation 2 (NAT / PAT Incompatibility): AH breaks when passing through a Network Address Translation (NAT) router because NAT rewrites the Source IP (and TCP/UDP ports in PAT) inside the packet, invalidating the receiver's HMAC verification over the IP header.

5.Protocol B: Encapsulating Security Payload (ESP - RFC 4303, IP Protocol Number 50):

a)Services Provided: Confidentiality (Encryption) plus optional data origin authentication, connectionless integrity, anti-replay protection, and traffic-flow padding.

b)Packet Structure (Surrounds Payload with Header + Encrypted Trailer + Auth):

1.ESP Header (Unencrypted): SPI (32 bits) + Sequence Number (32 bits).

2.Encrypted Payload: Encrypted data (plus optional Initialization Vector).

3.ESP Trailer (Encrypted along with Payload):

Padding (0–255 bytes)Aligns payload to block cipher size (e.g., 16-byte AES blocks) and obscures true message length.
Pad Length (8 bits)Tells receiver how many padding bytes to strip.
Next Header (8 bits)6 (TCP) in Transport Mode; 4 (IPv4) in Tunnel Mode.

4.Authentication Data (Optional, Unencrypted): ICV/MAC computed over ESP Header + Encrypted Payload + ESP Trailer (notice it does NOT cover the outer IP header!).

c)ESP Transport vs. ESP Tunnel Mode:

1.ESP Transport Mode: Encrypts and authenticates the TCP/UDP header + payload, while leaving the original IP header unencrypted and unauthenticated.

2.ESP Tunnel Mode (Standard Industry VPN): Encrypts and authenticates the entire original IP datagram (inner IP header + TCP/UDP + data) + ESP trailer, wrapped inside a new unencrypted outer IP header. Because the outer IP header is excluded from ESP's MAC, ESP Tunnel Mode works cleanly across NAT routers.

6.Anti-Replay Window Mechanics (Explained in Lecture Q&A):

a)Receiver maintains a sliding sequence number window (e.g., packets 50 to 80).

b)If a packet arrives with sequence number 55 for the first time, it is accepted and slot 55 is marked received. If an attacker replays 55 later—or replays an old packet 42 below the left edge of the window—the receiver immediately discards it.

Real-World Example:

When a software engineer works from a coffee shop and connects to their company's VPN (using strongSwan, Cisco AnyConnect, or AWS Site-to-Site VPN), the tunnel uses IPsec ESP with Authentication in Tunnel Mode. Even though the coffee shop's Wi-Fi router performs NAT on the engineer's packets, ESP Tunnel Mode traverses NAT seamlessly while encrypting both the engineer's internal 10.x.x.x IP addresses and all internal Git/SSH/database traffic.

⚠ Correction: "ESP tunnel mode works cleanly across NAT" holds only with NAT-Traversal (ESP encapsulated in UDP 4500): plain ESP has no ports, so PAT cannot demultiplex it. Also note: the Identification field is immutable, Flags/Fragment Offset are mutable.

↑ Back to contents

PART FOUR
Forensics, Attack Graphs & Blockchain
Chapter 13

Lab 4 — File forensics & EnCase

🧪 Lab 4.1 · File Forensics, Magic Numbers, File Carving, & Steganography

Detailed Conceptual Explanation:

1.What is File Forensics?

a)The practice of extracting, analyzing, and preserving digital evidence from files stored on electronic media without altering the original data.

b)Critical in network security for: (1) Malware payload analysis, (2) Data exfiltration tracing (identifying stolen files), and (3) Incident response timeline reconstruction.

2.Magic Numbers (Hexadecimal File Signatures):

a)Operating systems rely on filename extensions (.jpg, .pdf, .exe) to choose which program opens a file. Attackers routinely rename malicious executables (e.g., trojan.exe -> invoice.jpg) to bypass user suspicion.

b)Forensic tools inspect the Magic Number—the fixed hexadecimal signature bytes at the very start (header) and end (footer) of the raw file binary ("Extensions may lie, but magic numbers always tell the truth"):

Windows Executable (.exe / .dll)4D 5A (ASCII: MZ)
PDF Document (.pdf)25 50 44 46 (ASCII: %PDF)
JPEG Image (.jpg / .jpeg)Header FF D8 FF | Footer FF D9
PNG Image (.png)89 50 4E 47

•ZIP Archive / Office Open XML (.docx, .xlsx, .pptx): 50 4B 03 04 (ASCII: PK..)

3.System Metadata vs. Application Metadata ("Data About Data"):

a)System Metadata (Managed by the OS File System): MAC timestamps (Modified, Accessed, Created), file permissions, Owner SIDs, and logical vs. physical size.

b)Application Metadata (Embedded inside the file itself): EXIF camera settings and GPS coordinates in photos; author names, company templates, and revision histories in Word/PDF documents.

4.File Carving (Recovering Deleted Files):

a)How OS Deletion Works: When a user deletes a file and empties the Recycle Bin, the OS does NOT wipe the file's data sectors; it simply updates the directory index (e.g., flipping the NTFS Master File Table record status flag from 0x01 "In Use" to 0x00 "Available Space"). The raw payload remains intact in unallocated clusters until overwritten by new files.

b)Carving Process: Forensic carving tools (Scalpel, Foremost) scan raw unallocated disk sectors directly without relying on file system tables—locating a file header (e.g., FF D8 FF), reading continuously until the matching footer (FF D9), and extracting the bytes into a recovered file. ExifTool reads and edits embedded file metadata via CLI.

5.Anti-Forensics (Steganography):

–Unlike encryption (which scrambles data into obvious ciphertext), steganography conceals the very existence of secret data inside an innocent carrier file:

1.LSB (Least Significant Bit) Insertion: Alters the lowest-order bit of pixel color values in an image to store hidden bits without visible color distortion.

2.Append Hiding: Appends secret data after a legitimate file's EOF footer (e.g., after FF D9 in a JPEG). Image viewers stop rendering at FF D9, while raw hex editors reveal the appended payload.

Real-World Example:

During an intellectual property theft investigation, a departing engineer renames chip_design.pdf to wallpaper.jpg and deletes it from their USB stick. Investigators carve the deleted file from unallocated clusters, see the %PDF (25 50 44 46) magic header inside a .jpg filename, and flag deliberate anti-forensic concealment.

🧪 Lab 4.2 · EnCase Digital Forensics Workflow (Courtroom-Grade Investigation Suite)

Detailed Conceptual Explanation:

1.The Forensic Golden Rule & Write-Blocking:

a)Core Rule: "Never alter data on the original evidence media." Modifying even a single file access timestamp destroys judicial chain-of-custody.

b)Write-Blockers:

1.Hardware Write-Blocker (e.g., Tableau): Physically blocks write signals on the storage bus while allowing read commands.

2.Software Write-Blocker (FastBloc SE): Built-in EnCase utility that mounts suspect USB/storage drives in strict read-only mode on Windows.

2.Anatomy of an Expert Witness File (.E01 / .Ex01):

Case HeaderImmutable audit metadata (Case ID, acquisition timestamp, examiner name/badge, notes).
Data BlocksBitstream divided into strict 64-sector blocks (32 KB each), each tagged with an individual cryptographic block hash.
Global Footer ChecksumMaster cryptographic hash (MD5, SHA-1, SHA-256, or SHA-512) verifying end-to-end integrity of the entire evidence image.

3.Three-Volume Directory Management Framework (Structural Separation):

–Never store running case files, temporary indexes, or exported reports on the evidence drive:

1.Master Evidence (Read-Only drive, e.g., E:\LabEvidence): Stores raw .E01 images.

2.Processing Cache (Fast local SSD, e.g., C:\EnCaseCache): Stores temporary parsing caches.

3.Export Output (Read/Write drive, e.g., D:\LabOutputs): Stores extracted files and PDF reports.

4.EnCase Forensic Processor Engine Capabilities:

Signature AnalysisCompares internal hex magic numbers against file extensions and flags mismatches (e.g., a PDF disguised as .txt).
Keyword IndexingBuilds rapid search indexes across allocated and unallocated space.
Entropy AnalysisMeasures byte randomness (0 to 8 bits/byte) to detect hidden encrypted containers or packed malware.
MFT Deleted File RecoveryEvaluates unallocated NTFS Master File Table records (0x00) and displays recoverable deleted files with a Red 'X' overlay icon.
GREP Regular Expression ScanningSearches raw unallocated disk sectors for structured sensitive patterns:

a)Credit Card Numbers: \d{4}-\d{4}-\d{4}-\d{4}

b)Email Addresses: [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}

6.Windows Registry Artifact Forensics:

a)USB Device History (HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR):

Extracts hardware vendor strings, device models, and unique USB serial numbers.

b)User Execution Profiles (HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist):

Tracks application execution counts and last-run timestamps (obfuscated with a basic ROT13 substitution cipher).

5.Step-by-Step EnCase Lab Workflow:

1.Launch FastBloc SE write-blocker -> insert target USB drive (confirm write-blocked status).

2.Create New Case -> choose template (Basic) -> enter Case Number, Examiner Name, Description, and separate output directory.

3.Add Evidence -> select Local Device -> check "Only show write-blocked devices" -> select USB drive.

4.Acquire Image -> choose .Ex01 / .E01 format, verification hash (MD5/SHA-1), compression, and 64-sector block size.

5.Process, Bookmark, & Report -> inspect allocated (blue) vs. unallocated (gray) disk clusters, flag signature anomalies, bookmark evidence with analyst notes, and export a tamper-evident courtroom PDF portfolio.

Real-World Example:

In a corporate ransomware investigation, forensic examiners image an infected Windows server using EnCase, extract UserAssist registry keys proving an attacker ran mimikatz.exe at 02:14 AM, verify USB exfiltration via USBSTOR serial logs, and present SHA-256 verified .E01 evidence in court.

⚠ Correction: .E01 data chunks carry a per-chunk checksum (Adler-32/CRC), not a cryptographic hash each; the image-level MD5/SHA-1 (or SHA-256) is stored once for the whole image.

↑ Back to contents

Chapter 14

Lab 7 — Formal attack graphs & trust-score propagation

🧪 Lab 7.1 · Formal Attack Graphs & Trust Score Propagation

Detailed Conceptual Explanation:

1.Why Isolated Vulnerability Scans Are Insufficient:

a)Vulnerability scanners (such as Nessus or OpenVAS) report software bugs on individual hosts in isolation, missing how an intruder chains multiple minor vulnerabilities across interconnected machines ("stepping stones") to breach a heavily firewalled target server.

b)An Attack Graph is a formal directed state-transition graph depicting every possible multi-stage exploit sequence an attacker can execute to violate a target security property.

2.Formal Attack Model (Finite State Automaton):

–Modeled as a 3-tuple M = (S, tau, s_0):

1.S (Global State Space): Formed by the Cartesian product of individual agent states (S = S_1 x S_2 x ... x S_n) across three agent classes I = {E, D, N}:

E (Attacker / Intruder)Modeled by knowledge store and privileges.
D (Defender)Security administrator / Intrusion Detection System (IDS).
N (Network System)Modeled by hosts H, connectivity C, and trust T.

2.tau subseteq (S x S) (Transition Relation): Valid state transitions (s_i, s_{i+1}) triggered by an attacker action or a defender IDS alarm.

3.s_0 in S (Initial State): Root state before any action occurs.

3.Executions, Security Properties, & Attack Graph Definition:

Finite ExecutionA finite sequence of valid transitions alpha = s_0, s_1, ..., s_n where (s_i, s_{i+1}) in tau.
Infinite ExecutionAn unbounded sequence beta = s_0, s_1, ....
Security Property (P)A subset of safe executions in L(M) (e.g., G(intruder.privilege[Linux_DB] < root)—"intruder never gains root on the Linux database host").
Correct vs. Failing Executionalpha in P is correct (safe); alpha not in P is failing (violates P).
Attack GraphDefined formally as L(M) \ P—the exact set of all failing executions that compromise the security property.

4.Six Network Model Inputs & Action Rule Anatomy:

H (Hosts)Tuple (id, svcs [service/port pairs], sw [OS/apps], vuls [CVEs]).
C (Connectivity)Ternary relation C(h_1, h_2, p) encoding whether h_1 can reach h_2 on port p (reflecting physical links and firewall ACLs).
T (Trust)Inter-host trust relation (T(h_1, h_2)).
I (Intruder Model)Knowledge variables (e.g., boolean scan) and privilege function plvl(host) in {none, user, root} (none < user < root).
A (Action Rules / Exploits)Triples (rule, h_source, h_target) defined by four clauses:
Intruder PreconditionsRequired knowledge (scan) and privilege on h_source and h_target.
Network PreconditionsTarget service active and port reachability C(h_source, h_target, p) open.
Intruder EffectsUpdated privilege plvl(h_target) or knowledge.
Network EffectsChanges to network/host configuration.

6.Ids (Intrusion Detection Visibility): Function ids(h_1, h_2, a) -> {d, s, b} marking whether action a between h_1 and h_2 is detectable (d), stealthy (s), or both (b).

5.Defense Optimization (Minimum Hitting Set / Set Cover):

–Once generated, administrators run an approximation algorithm to find the Critical Action Set (Minimum Hitting Set)—the smallest set of vulnerabilities to patch or firewall rules to enable that completely disconnects s_0 from all compromised goal states.

6.Worked DMZ + Internal Network Attack Scenario (Sheyner & Wing, CMU):

a)Network Topology: External Intruder -> [External Firewall] -> DMZ (Windows IIS Web Server on port 80) -> [Internal Firewall] -> Internal LAN (Windows Host + Linux Host running Squid Proxy on port 80, LICQ Chat on port 5190, and Database) + Network IDS.

b)Shortest Attack Path (4 Exploits to Root on Linux DB):

1.IIS Buffer Overflow (CAN-2002-0364) on port 80 -> gains remote root on the DMZ Windows IIS Web Server.

2.Squid Port Scan (CVE-2001-1030) via misconfigured Squid proxy -> discovers internal Linux services (scan := true).

3.LICQ Remote-to-User (CVE-2001-0439) on port 5190 -> sends crafted URL to gain user shell on Linux.

4.Local Setuid Buffer Overflow in 'at' (CVE-2002-0004) -> escalates from user to root on Linux DB.

c)IDS Evasion Path: Because the IDS monitors traffic between the DMZ Web Server and Linux, the attacker avoids triggering an alarm by pivoting through an unmonitored internal link: after taking the IIS Web Server, the attacker uses Client Scripting Exploit (CAN-2002-0193) to gain user access on the internal Windows host, then launches the LICQ exploit from Windows to Linux (where no IDS is watching) and escalates to root.

7.Trust Score Propagation Calculations:

–Each edge in a trust-weighted attack graph carries a probability T_i in [0, 1] indicating how readily an exploit succeeds across that link:

1.Series Connection (Sequential Multi-Hop Path):

Multiply edge trust values along the path:

T_series = T_1 * T_2 * ... * T_k

•Worked Example: User0 -> FTP (0.8) -> RSH (0.9) => T_series = 0.8 * 0.9 = 0.72.

2.Parallel Connection (Alternative Paths Converging on Same Node):

Combine using the probabilistic union (OR-gate) formula:

T_parallel = T_A + T_B - (T_A * T_B)

•Worked Example: Path A (0.72) and Path B (0.10) converge into a node that leads via a final hop (0.8) to the goal:

a)Parallel combination: 0.72 + 0.10 - (0.72 * 0.10) = 0.82 - 0.072 = 0.748.

b)Final series hop: 0.748 * 0.8 = 0.5984 (~0.60).

Real-World Example:

In the infamous 2013 Target retail breach, external firewalls completely blocked direct internet access to Target's point-of-sale payment servers. Attackers built a multi-hop chain: (1) Phished a third-party HVAC refrigeration contractor (T_1), (2) Pivoted through the contractor's trusted vendor VPN portal into Target's internal corporate network (T_2), and (3) Exploited an unpatched Windows server to reach the payment card database (T_3). An Attack Graph immediately shows that isolating vendor VPN access from internal payment VLANs (a single firewall rule) cuts every path to the payment servers.

↑ Back to contents

Chapter 15

Lab 7 — Hyperledger Fabric chaincode (pharma batch traceability)

🧪 Lab 7.2 · Hyperledger Fabric Java Chaincode Lab (Pharmaceutical Batch Traceability)

Detailed Conceptual & Hands-On Explanation:

1.Permissioned Blockchain Architecture vs. Public Blockchains:

a)Unlike public permissionless blockchains (Bitcoin, Ethereum) where anonymous participants mine blocks via Proof-of-Work, Hyperledger Fabric is an enterprise permissioned blockchain where every organization, peer, and user holds a verified X.509 cryptographic identity issued by a Membership Service Provider (MSP).

b)Five Core Fabric Components:

1.Peers (peer0.org1.example.com, peer0.org2.example.com): Store the immutable blockchain ledger and current CouchDB/LevelDB World State, simulate transaction proposals, sign endorsements, validate blocks, and commit state updates.

Ordering Service (orderer.example.com)Receives endorsed transaction envelopes, orders them chronologically into blocks, and broadcasts blocks to all peers. *(Crucial distinction: The Ordering Service does NOT execute chaincode or inspect business logic.)*
Channel (mychannel)A private logical subnet/ledger shared exclusively by authorized channel organizations (Org1 and Org2).
Chaincode (pharma)Smart contract written in Java (ContractInterface) defining valid asset schemas (Asset.java) and state-transition rules (AssetTransfer.java).
MSP IdentitiesOrg1MSP (Pharmaceutical Manufacturer) and Org2MSP (Quality Assurance Lab & Receiving Organization).

2.Execute-Order-Validate Transaction Lifecycle:

Endorsement (Execute)Client submits a transaction proposal to endorsing peers (peer0.org1 and peer0.org2). Both peers simulate the Java chaincode against their local world state and return cryptographically signed Read/Write sets.
OrderingClient bundles the signed endorsements and sends them to orderer.example.com, which packages transactions into a block.
Validation & CommitEvery peer independently verifies endorsement signatures against the channel endorsement policy and performs a Multi-Version Concurrency Control (MVCC) read-set version check before committing valid transactions to the ledger.
*Golden Rule*A successful endorsement response alone does NOT guarantee a transaction committed; always run peer chaincode query afterward to verify the updated world state.

3.Pharmaceutical Batch Lifecycle & Authorization Rules (BATCH-1001, Vaccine-X, qty 500):

1.CreateBatch("BATCH-1001", "Vaccine-X", 500) [Caller: Org1MSP]:

a)Rejects empty/duplicate batchID, blank product, or quantity <= 0.

b)Creates asset with ownerOrg = "Org1MSP", status = "CREATED".

2.ReadBatch("BATCH-1001") [Transaction.TYPE.EVALUATE]:

–Queries world state on a single peer without creating a block.

3.ReleaseBatch("BATCH-1001") [Caller: Org2MSP]:

a)Enforces caller.equals("Org2MSP") (only QA org can release) and status.equals("CREATED").

b)Updates status = "QA_RELEASED" (ownerOrg remains "Org1MSP").

4.TransferBatch("BATCH-1001", "Org2MSP") [Caller: Org1MSP]:

a)Enforces caller.equals(old.getOwnerOrg()), status.equals("QA_RELEASED"), and newOwnerOrg != caller.

b)Updates ownerOrg = "Org2MSP" and status = "IN_TRANSIT".

5.ReceiveBatch("BATCH-1001") [Caller: Org2MSP]:

a)Enforces caller.equals(old.getOwnerOrg()) (Org2MSP) and status.equals("IN_TRANSIT").

b)Updates status = "RECEIVED" (final state).

4.Complete Step-by-Step Lab Execution Commands (macOS & Ubuntu Linux):

1.Install Prerequisites (Git, Java 21 JDK, Docker Desktop / Docker Engine):

a)macOS: brew install git && brew install --cask temurin@21 docker

b)Ubuntu: sudo apt update && sudo apt install -y ca-certificates curl git gnupg openjdk-21-jdk docker-ce docker-ce-cli containerd.io docker-compose-plugin

2.Download Fabric Samples, Binaries, & Docker Images:

mkdir -p ~/fabric-lab && cd ~/fabric-lab curl -sSLO https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/install-fabric.sh chmod +x install-fabric.sh && ./install-fabric.sh docker samples binary

3.Start Test Network & Create mychannel:

cd ~/fabric-lab/fabric-samples/test-network ./network.sh up createChannel -ca docker ps

4.Smoke-Test with Official Java Sample:

./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-java -ccl java

5.Build Custom Java Pharma Chaincode:

cd ~/fabric-lab/fabric-samples cp -R asset-transfer-basic/chaincode-java pharma-chaincode-java cd pharma-chaincode-java # Replace AssetTransfer.java & Asset.java in src/main/java/org/hyperledger/fabric/samples/assettransfer/ ./gradlew build

6.Deploy Custom pharma Chaincode:

cd ~/fabric-lab/fabric-samples/test-network ./network.sh deployCC -ccn pharma -ccp ../pharma-chaincode-java -ccl java

7.Export CLI Paths & Define useOrg1() / useOrg2() Identity Helpers:

export PATH="${PWD}/../bin:$PATH" export FABRIC_CFG_PATH="${PWD}/../config" export ORDERER_CA="${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem" export ORG1_CA="${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" export ORG2_CA="${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt" useOrg1() { export CORE_PEER_TLS_ENABLED=true; export CORE_PEER_LOCALMSPID=Org1MSP; export CORE_PEER_ADDRESS=localhost:7051; export CORE_PEER_TLS_ROOTCERT_FILE="$ORG1_CA"; export CORE_PEER_MSPCONFIGPATH="${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp"; } useOrg2() { export CORE_PEER_TLS_ENABLED=true; export CORE_PEER_LOCALMSPID=Org2MSP; export CORE_PEER_ADDRESS=localhost:9051; export CORE_PEER_TLS_ROOTCERT_FILE="$ORG2_CA"; export CORE_PEER_MSPCONFIGPATH="${PWD}/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp"; }

8.Invoke & Query Workflow:

useOrg1 peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "$ORDERER_CA" -C mychannel -n pharma --peerAddresses localhost:7051 --tlsRootCertFiles "$ORG1_CA" --peerAddresses localhost:9051 --tlsRootCertFiles "$ORG2_CA" -c '{"function":"CreateBatch","Args":["BATCH-1001","Vaccine-X","500"]}' peer chaincode query -C mychannel -n pharma -c '{"function":"ReadBatch","Args":["BATCH-1001"]}'

9.Clean Shutdown:

./network.sh down

5.Negative Test Matrix (Verifying Smart Contract Business Rule Enforcement):

TC-02Re-invoke CreateBatch with "BATCH-1001" -> Rejected (duplicate batch ID).
TC-03Invoke CreateBatch with quantity "0" -> Rejected (positive quantity required).
TC-04Query ReadBatch for "BATCH-9999" -> Rejected (batch not found).
TC-05Invoke ReleaseBatch while using useOrg1 -> Rejected (only Org2MSP QA can release).
TC-06Invoke TransferBatch before ReleaseBatch -> Rejected (batch must be QA_RELEASED).
TC-07Invoke ReceiveBatch before TransferBatch -> Rejected (batch must be IN_TRANSIT).
TC-08Invoke TransferBatch from a non-owner MSP -> Rejected (only current owner can transfer).

Real-World Example:

In global pharmaceutical supply chains (such as the FDA DSCSA-compliant MediLedger network built on permissioned blockchain), drug manufacturers, independent Quality Assurance labs, wholesalers, and hospital pharmacies share a tamper-evident ledger. Even if a compromised warehouse insider tries to ship unapproved or counterfeit vaccine vials, the smart contract rejects any transfer lacking a valid cryptographic QA_RELEASED signature from the accredited testing lab's MSP.

↑ Back to contents

Appendix

Corrections & clarifications

Errors found while compiling, in slides, lecture notes and lab text. Each also appears as a red box at the point where it occurs.

#WhereAs writtenCorrect
1Slides 5.Network_ProtocolsARP request multicast, reply broadcastRequest broadcast, reply unicast (the notes have it right)
2L07 notesSYN = 0, ACK = 0 "not possible"Exists for RST and NULL/FIN/Xmas scan probes
3L09 notesSource Quench sent back to R₁Sent to the original source host; deprecated
4L09 notesEvery discarding router must send ICMPExceptions: ICMP errors, non-first fragments, multicast/broadcast
5L11 slide (DHCP)0.208 min = 12.5 minutes12.48 seconds
6Lab 1.2UDP up to 65,500 B65,507 B payload
7Lab 3.1A = 5 ⇒ exp 6, K = 18a = 4, K = 11
8Lab 4.2Each E01 block hashedPer-chunk checksum + one image hash
9Lab 5.2tcp-syn != 0 = SYN filterAlso matches SYN-ACK; use tcp[13] & 0x12 == 0x02
10Lab 5.5--mode inline-Q with interface pair
11Lab 6.1"Partial data privacy"Access control (RFC 4301)
12Lab 6.3ESP tunnel crosses NAT cleanlyNeeds NAT-T (UDP 4500)
13Sym-crypto slidesCryptanalysis "without knowledge of encryption"; "mode 26"Without knowledge of the key; mod 26

↑ Back to contents



No comments :

Post a Comment

Comments will appear on the post after moderation.