0% found this document useful (0 votes)
43 views85 pages

Application Layer Paradigms Explained

Computer networks notes applications

Uploaded by

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

Application Layer Paradigms Explained

Computer networks notes applications

Uploaded by

Deepankar Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER NETWORKS - MODULE 5: APPLICATION LAYER

Complete Exam-Focused Pedagogical Notes

SECTION 5.1: APPLICATION LAYER PARADIGMS


Introduction
The Fundamental Question: How should two application programs on different
computers interact with each other?
Two Possible Approaches: 1. Both programs are equal partners 2. One provides service,
the other requests it
Answer: The Internet has evolved two primary paradigms to answer this: 1. Client-Server
Paradigm 2. Peer-to-Peer (P2P) Paradigm

PARADIGM 1: CLIENT-SERVER ARCHITECTURE


Core Definitions

Server (Service Provider)


Aspect Details
Type Application program (server
process)
Availability Always-on (24/7/365) - Continuous
operation
Status Must be running before any client
connects
Behavior Waits passively for client requests
Hardware Powerful computer designed for
heavy load
Capacity Handles many clients
simultaneously
Examples Web servers, email servers, DNS
servers

Client (Service Requester)


Aspect Details
Type Application program (client
Aspect Details
process)
Availability Starts only when user needs service
Status Active, temporary operation
Behavior Actively initiates connection to
server
Hardware Any computer (laptop, desktop,
phone)
Capacity Connects to one server at a time
(typically)
Examples Web browsers, email clients, FTP
clients

Relationship Between Client and Server


• Pattern: Many-to-One
• Description: Many clients request services from a few servers
• Roles: Fixed and unchangeable - client always client, server always server
• Direction: Client always initiates; server always responds

Operational Flow (Step by Step)


Step 1: Server process starts and initializes - Binds to well-known port number - Waits for
incoming requests
Step 2: Client process starts (triggered by user action) - User needs a service
Step 3: Client initiates connection through Internet - Sends request to server’s IP:Port
Step 4: Server processes request and sends response - Client receives response -
Connection typically closes (or continues based on protocol)

Real-World Analogy: Telephone Directory


The Metaphor: - Server = Telephone directory center - Must be open all the time -
Available to answer queries 24/7 - Cannot go offline without affecting service
• Client = Subscriber seeking information
– Only calls when they need something
– Temporary interaction
– Cannot provide the service themselves
Key Distinction: The subscriber never becomes the directory center, and vice versa. Roles
are permanently fixed.
Limitations of Client-Server Paradigm
Limitation Explanation Impact
Load Concentration All work on single server Single point of
failure
Server Bottleneck If 1000s connect at once, server Performance
overwhelmed degrades
Hardware Requirements Must be powerful machine Very expensive
equipment
Scalability Issues Cannot easily handle more clients Growth is limited
Cost Burden Provider pays for infrastructure High operational
costs
Business Model Needed Service must generate revenue Not feasible for all
services

Common Client-Server Applications


Protocol Application Port
HTTP World Wide Web 80
HTTPS Secure Web 443
FTP File Transfer 21 (control), 20 (data)
SMTP Email Sending 25
POP3 Email Retrieval 110
IMAP Email Access 143
SSH Secure Shell 22
Telnet Remote Login 23
DNS Domain Name 53
Resolution

PARADIGM 2: PEER-TO-PEER (P2P) ARCHITECTURE


Core Concepts

Definition
• No Central Authority: No required always-on server process
• Distributed Service: Responsibility for service spread among all peers
• Dual Roles: Each computer acts as both client AND server simultaneously
• Direct Communication: Peers communicate directly without intermediary
Key Characteristic: Dual Roles
A single computer can: - Request a service from one peer (acting as CLIENT) - Provide a
service to another peer (acting as SERVER) - Do both simultaneously without
contradiction
Example: - Computer A downloads file from Computer B (A is client, B is server) - While
uploading file to Computer C (A is server, C is client) - Both happen at the same time!

Operational Flow
Step 1: Peers connect to Internet - Any peer can join at any time
Step 2: Peers locate other peers (Peer Discovery) - Query indexing service (if exists) - Or
broadcast to find peers - Or connect to known peer
Step 3: Direct peer-to-peer communication - No central server needed - Peers exchange
data directly - Each handles their own requests/responses

Advantages of P2P Architecture


Advantage Explanation Business Impact
Scalability More peers = More System grows automatically
capacity
Cost-Effective No expensive servers Lower infrastructure costs
needed
Resilience Peer failure doesn’t stop No single point of failure
system
Bandwidth No bottleneck at server Distributed load
Efficiency
User Resources Leverages client Free computational power
computers

Scalability Detail: In client-server, new users = more load (bad). In P2P, new peers = more
resources (good!).

Challenges and Limitations of P2P


Challenge Explanation Impact
Security Distributed nodes hard to secure Malware, attacks
harder to prevent
Incentive Problem Users may not share resources Bandwidth/storage
reluctantly given
Fairness How to reward sharers? Free-riders exploit
system
Limited Applicability Not all apps fit model Search engines need
centralization
Challenge Explanation Impact
Complexity Peer discovery difficult More complex
implementation
Reliability Peers unreliable (can go offline) No guaranteed
availability
Authentication Hard to verify peer identity Trust issues in
system

Characteristics Comparison
Feature Client-Server Peer-to-Peer
Central Server Required Not required
Server Role Dedicated, always-on Any peer, intermittent
Client Initiates Yes, always Any peer can initiate
Scalability Limited (server bottleneck) High (peers add capacity)
Security Easier (centralized) Harder (distributed)
Cost High (expensive server) Low (user hardware)
Reliability Single point of failure Redundancy built-in
Complexity Simpler More complex

Common P2P Applications


Application Purpose Example
File Sharing Distribute large files BitTorrent
VoIP Voice over Internet Skype
Streaming Video/Audio delivery P2P-IPTV
Distributed Harness idle CPU SETI@home
Computing
Cryptocurrencies Decentralized ledger Bitcoin, Ethereum
Messaging Direct communication Some instant
messengers

PARADIGM 3: HYBRID (MIXED) ARCHITECTURE


Concept
Definition: Combines best of both paradigms - Use client-server where it’s efficient - Use
P2P where it’s beneficial

Implementation Strategy
Two-Tier Approach:
Tier 1 - Client-Server: For Discovery/Lookup - Use centralized server - Light-weight
operations - Fast lookups - Server manages directory/index
Tier 2 - Peer-to-Peer: For Data Transfer - Direct P2P connections - Heavy-weight
operations - Efficient bandwidth usage - No server involvement

Real-World Example: Voice Calling


Scenario: Alice wants to call Bob via Internet
Step 1 (Client-Server): Discovery
Alice → Central Server: "Find Bob's address"
Central Server → Alice: "Bob is at IP [Link]"

Step 2 (P2P): Actual Communication


Alice ↔ Bob: Direct voice call
(No server involvement)

Why Hybrid Works: - Discovery/Authentication (light load) → Centralized server


handles efficiently - Data Transfer (heavy load) → P2P handles efficiently - Best of both
worlds → Cost-effective and scalable

More Examples
Application Discovery (C-S) Communication (P2P)
Skype Locate user in Direct video/voice call
directory
BitTorrent Tracker finds peers Direct file transfer
Streaming Find available sources Stream from nearby
peer

CLIENT-SERVER PROGRAMMING FUNDAMENTALS


Processes vs. Computers
Important Distinction: - Communication occurs between processes, not computers - A
process is a running program - A computer can run multiple processes simultaneously -
Client process ≠ Client computer; Server process ≠ Server computer
Example: One computer can run: - Chrome (client process) - Apache (server process) -
Both communicating with each other

Client Process Lifecycle


Phase Details
Birth Starts when user needs service
Active Initiates connection to server
Phase Details
Finite Sends limited requests
Death Terminates after getting responses
Duration Seconds to minutes (temporary)

Server Process Lifecycle


Phase Details
Birth Starts at system boot or manually
Setup Prepares to accept connections
Active Waits for client requests indefinitely
Infinite Ideally runs forever
Death Only stops for
maintenance/shutdown
Duration Days, months, years (permanent)

Pre-requisite for Communication


CRITICAL: Server must start BEFORE client attempts connection.
Why: Client has no way to connect if server isn’t listening on the well-known port.

APPLICATION PROGRAMMING INTERFACE (API)


What is an API?

Definition
• Set of instructions/functions provided by operating system
• Enables application programs to use network services
• Bridge between Application Layer and OS/TCP-IP stack
• Language-independent specification

Purpose
Application programs written in C, Java, Python, etc. do not have built-in network
knowledge. These languages have math, string, I/O operations but lack network operations.
API Solution: Provides standardized functions for network operations.

What APIs Enable


APIs allow programs to: 1. Open a connection to remote host 2. Send data across network
3. Receive data from network 4. Close the connection gracefully 5. Handle errors during
communication
Common API Types
API Origin Use Status
Socket UC Berkeley, UNIX Most common Current standard
Interface
Transport System V UNIX Standardizatio Less used
Layer n
Interface
(TLI)
Winsock Microsoft Windows Windows Legacy
systems
XTI POSIX standard Portable Alternative
systems

Focus of this course: Socket Interface (most important)

SOCKET INTERFACE
What is a Socket?

Definition
• Abstraction: Software object representing communication endpoint
• Purpose: Endpoint for sending/receiving data across network
• Metaphor: Just like reading from a file or writing to terminal

Key Analogy
Standard I/O Network I/O
Program reads from FILE Program reads from SOCKET
Program writes to FILE Program writes to SOCKET
File = Source/sink of data Socket = Source/sink of network
data
OS manages file I/O OS manages socket I/O

Unifying Principle: Treat network operations like file operations. Standard read/write
operations work with sockets too!

Socket Architecture
Basic Setup:
Client Program Server Program
| |
└─→ Create Socket ←──────────┘
| |
└─ Socket ─────────┘
|
Communication Link

Communication Flow: 1. Client creates socket 2. Server creates socket 3. Sockets connect
(appears as direct link to application) 4. Application reads/writes to socket as if it’s a file 5.
OS handles actual network transmission

SOCKET ADDRESSES
The Fundamental Problem
Goal: Process-to-process communication
Question: How do we address a specific process on a specific computer?
Challenge: - Computer address alone (IP) not sufficient - multiple processes per computer
- Process identification alone not sufficient - needs to know which computer
Solution: Socket Address = IP Address + Port Number

Socket Address Components

IP Address (32-bit for IPv4)


• Purpose: Identifies unique computer on Internet
• Example: [Link]
• Provided by: Operating system (computer’s network interface)
• Scope: Globally unique

Port Number (16-bit)


• Purpose: Identifies unique process on that computer
• Range: 0 to 65,535
• Example: 80 (HTTP), 443 (HTTPS), 22 (SSH)
• Scope: Unique within single computer
• Size: 16 bits = 2^16 = 65,536 possible ports

Socket Address Formula


Socket Address = IP Address : Port Number

Example: [Link]:80
↑ ↑
Computer Process

Uniqueness: This combination uniquely identifies a process on the Internet.

Socket Address in Practice


Complete Endpoint:
[Link]
│ │
Computer Process
IP:Port
[Link]:443

FINDING SOCKET ADDRESSES


Challenge
The Asymmetry: Client and Server have different address discovery problems.
Server knows: Its own address and well-known port
Server doesn’t know: Client’s address and port (varies per client)
Client knows: Server’s address and port (well-known)
Client doesn’t know: Its own port (assigned by OS)

SERVER SIDE: Address Discovery

Local Socket Address (Server’s own)


Component Details Who provides Who chooses
IP Server OS Not applicable
computer’s IP
Port Well-known Standard/IANA Application specifies
port for
service

Well-Known Ports (Examples): - Port 80: HTTP - Port 25: SMTP (Email) - Port 53: DNS -
Port 443: HTTPS - Port 22: SSH - Port 110: POP3
Key Point: Server port is fixed and known in advance so clients know where to find it.

Remote Socket Address (Client’s address)


Server’s Perspective: - Doesn’t know client address beforehand - Client address varies
with each client connection - Solution: Extract from incoming request packet
How it works: 1. Client sends request with its IP and port in header 2. Server reads request
header 3. Server extracts client’s IP and port 4. Server uses these to send response back

CLIENT SIDE: Address Discovery

Local Socket Address (Client’s own)


Component Details
IP OS provides automatically
Component Details
Port OS assigns ephemeral port

Ephemeral Port: - Definition: Temporary port number assigned by OS - Range: Typically


49,152 - 65,535 (depends on OS) - Example: 52,847 (random selection) - Duration: Lasts
for connection lifetime only - Purpose: No need for fixed port (client initiates connections)
- Advantage: Any port works; no conflicts possible

Remote Socket Address (Server’s address)


Component Problem How Solved
Server Port Client must know Well-known: Standardized
(e.g., 80 for HTTP)
Server IP Humans remember DNS (Domain Name System)
names, not IPs

The Domain Name System (DNS) Solution


The Problem: Humans know [Link], not [Link]
The Solution: Client uses DNS to lookup
How DNS Works:
Client Application
|
v
"What's IP of [Link]?"
|
v
DNS Resolver (library function)
|
v
"IP is [Link]"
|
v
Client can now connect to [Link]:80

Analogy: Phone directory - you look up person’s name to find their number.

Socket Address Discovery Summary Table


Parameter Server Client
Local IP OS provides OS provides
Local Port Well-known (fixed) Ephemeral (random)
Remote IP Extracted from request DNS lookup
Remote Port Extracted from request Well-known (fixed)
When known Partially pre-known Partially pre-known
How obtained Request packet DNS + knowledge
Parameter Server Client

SECTION 5.2: STANDARD CLIENT-SERVER PROTOCOLS - WORLD WIDE WEB


(WWW)
Introduction to WWW

Historical Context
• Inventor: Tim Berners-Lee at CERN (1989)
• Innovation: Revolutionary distributed information system
• Impact: Transformed the Internet from research network to mainstream

Two Key Concepts


1. Distributed Information - Web pages not stored in one location - Documents hosted on
thousands of servers worldwide - Prevents overloading any single server - Enables global
accessibility
2. Hypertext and Hypermedia
Hypertext: - Documents contain links to other documents - Click link → automatically
retrieve referenced document - Works across networks and servers - Transparent to user
Hypermedia: - Extension of hypertext - Includes not just text but also: - Images - Audio -
Video - Animations - Interactive content

Architecture of the Web

Components
Component Role Examples
Web Client Retrieves & Chrome, Firefox, Safari, Edge
displays pages
Web Server Stores & serves Apache, Nginx, IIS
pages
Site Collection of [Link], [Link]
related pages on
one server
Web Page File with content HTML file with text, images
& links
Link Pointer to <a href="...">
another resource

Client-Server Model
• Client (Browser): Requests documents
• Server: Provides documents
• Protocol: HTTP (HyperText Transfer Protocol)
• Transport: TCP/IP

Example Scenario: Complex Web Page Retrieval


Scenario: User loads page with text, image, and link
Architecture:
Server I contains:
- File A (HTML with text)
- Image B (JPG)

Server II contains:
- File C (another HTML document)

Process:
Transaction 1: Fetch HTML - User types URL or clicks link to File A - Browser requests File
A from Server I - Server I sends File A (HTML)
Transaction 2: Auto-fetch embedded image - Browser parses HTML - Finds <img
src="[Link]"> - Browser automatically requests Image B from Server I - Server I
sends Image B
Transaction 3: User clicks link - User reads page, clicks link to File C - Browser requests
File C from Server II - Server II sends File C
Key Point: Each file is a separate transaction with separate request/response.

Web Page Components

Static Web Pages


Aspect Details
Definition Fixed content stored on server
Created Beforehand, doesn’t change
Content Same for every client
Technologies HTML, XML, XHTML
Database Not used
Performance Very fast (no processing needed)
Examples Blog posts, news articles,
documentation

Dynamic Web Pages


Aspect Details
Definition Created by server when requested
Aspect Details
Created At request time
Content Changes based on parameters/time
Technologies CGI, PHP, JSP, ASP, [Link]
Processing Server processes request
Examples Weather forecasts, stock quotes,
search results

Example:
User 1 requests: [Link]?city=NYC
Server generates: Weather for NYC today

User 2 requests: [Link]?city=LA


Server generates: Weather for LA today

Same URL, different content!

Active Documents
Aspect Details
Definition Program/script executed at client
Location Runs in browser (client-side)
Purpose Interactive features, animations
Technologies Java Applets, JavaScript,
WebAssembly
Server Load None (client does work)
Examples Games, maps, real-time chat

Why Active Documents: - Server cannot handle processing load - User experiences better
interactivity - Reduces bandwidth (only logic sent, not rendered output)

Web Components

Web Client (Browser)


Structure (3-part architecture): 1. Controller - Takes user input (clicks, URL typing) -
Coordinates other components - Manages flow
2. Client Protocols (HTTP, FTP, etc.)
– Handles communication with servers
– Sends requests, receives responses
– Implements protocol rules
3. Interpreters (HTML, CSS, JavaScript)
– Parses received documents
– Renders content for display
– Executes scripts
– Displays images
How They Work Together:
User types URL

Controller: "Fetch this"

HTTP Protocol: Sends request

Server responds with HTML, images, CSS, JavaScript

HTML Interpreter: Parses structure
CSS Interpreter: Applies styling
JavaScript Interpreter: Runs scripts

Result: Rendered web page in browser window

Web Server
Responsibilities: - Stores web pages/documents - Listens for client requests - Processes
requests - Sends responses
Features: - Caching: Cache memory for frequently accessed pages - Threading: Handle
multiple simultaneous requests - Logging: Record all accesses - Security: Enforce
permissions
Common Examples: - Apache HTTP Server - Nginx - Microsoft IIS - [Link] - Flask/Django
(Python)

URL (Uniform Resource Locator)


Purpose: Unique identifier for every resource on web
Components: 4 pieces of information required
protocol://host:port/path

[Link]
│ │ │ │
│ │ │ └─ Path/Filename
│ │ └─ Port number (default 80 for HTTP)
│ └─ Host (domain or IP)
└─ Protocol (how to access)

Detailed Breakdown:

Component Example Details Optional


Protocol http, https, ftp Vehicle for access Required
Component Example Details Optional
Host [Link] Domain name or Required
or [Link] IP
Port 80, 443, 8080 Server port Optional (defaults to
protocol’s well-
known port)
Path /images/[Link] File location on Often optional
server (defaults to
[Link] or /)

Examples:
[Link]
[Link]
[Link]
[Link]

SECTION 5.3: HYPERTEXT TRANSFER PROTOCOL (HTTP)


Introduction to HTTP

Definition
• Full Name: HyperText Transfer Protocol
• Type: Text-based, request-response protocol
• Layer: Application layer
• Transport: TCP (reliable delivery)
• Port: 80 (HTTP), 443 (HTTPS)
• Standard: RFC 7230-7235

Key Characteristics
Feature Details
Protocol Type Request-Response
Text Format Messages are human-readable text
Connection Uses TCP on port 80
Reliability Reliable (TCP ensures this)
State Stateless (each request
independent)
Standard Defined in RFCs
HTTP Versions and Connection Types

HTTP/1.0 (Legacy)
Connection Model: Nonpersistent - One TCP connection per object - Limited efficiency
Example: Loading a web page with 1 HTML + 10 images
Connection 1: Request HTML → Response HTML → Close
Connection 2: Request Image1 → Response Image1 → Close
Connection 3: Request Image2 → Response Image2 → Close
...
Connection 11: Request Image10 → Response Image10 → Close

Total: 11 separate TCP connections!

Overhead: - Each connection needs 3-way handshake - Each close needs teardown -
Significant latency and resource usage

HTTP/1.1 (Current Standard - DEFAULT)


Connection Model: Persistent (Default) - One TCP connection for multiple objects - High
efficiency - Can send requests pipelined
Same Example with HTTP/1.1:
Connection 1:
→ Request HTML
← Response HTML
→ Request Image1
← Response Image1
→ Request Image2
← Response Image2
...
→ Request Image10
← Response Image10
→ Close connection

Total: 1 TCP connection for all requests!

Advantages: - Fewer handshakes (major latency reduction) - Lower CPU usage - Less
memory per server - Much faster page loads
Key Point: HTTP/1.1 DEFAULT is persistent. To disable: Connection: close header

HTTP Messages: Request Format

Structure
REQUEST LINE
HEADERS (multiple lines)
[BLANK LINE]
[BODY - optional, usually empty]
Request Line
Format: METHOD URL HTTP/VERSION
Example: GET /images/[Link] HTTP/1.1
Components:

Component Examples Details


METHOD GET, POST, HEAD, PUT, Action to perform
DELETE, PATCH
URL /[Link], Resource path
/api/users?id=5
VERSION HTTP/1.1, HTTP/2.0 Protocol version

Common HTTP Methods


GET (Most Common) - Purpose: Request a document - Use: Retrieve web pages, images,
files - Body: No body - Safe: Yes (doesn’t modify server state) - Example: GET
/[Link] HTTP/1.1

HEAD - Purpose: Like GET but response has NO body - Use: Check if resource exists, get
metadata - Body: No body - Advantage: Faster (no data transfer overhead) - Example:
HEAD /[Link] HTTP/1.1

POST (Second Most Common) - Purpose: Send data to server for processing - Use: Form
submissions, API requests - Body: Contains form data or JSON - Safe: No (modifies server
state) - Example: Form submission with username/password
PUT - Purpose: Upload a document to server - Use: Update resources, upload files - Body:
The file or resource content - Safe: No (creates/modifies) - Example: REST API updates
DELETE - Purpose: Delete a resource on server - Use: API operations, file deletion - Body:
Usually empty - Safe: No (destructive) - Example: DELETE /api/users/123 HTTP/1.1
PATCH - Purpose: Partial update of resource - Use: REST APIs, partial modifications -
Difference from PUT: PUT replaces entire resource; PATCH modifies parts

HTTP Request Headers


Purpose: Additional information about request
Common Headers:

Header Purpose Example


Host Server domain Host: [Link]
User-Agent Client browser info User-Agent: Mozilla/5.0…
Accept Content types client wants Accept: text/html,
application/json
Header Purpose Example
Accept-Language Preferred languages Accept-Language: en-US, fr
Accept-Encoding Compression methods OK Accept-Encoding: gzip,
deflate
Cookie Session identifier Cookie: sessionId=abc123
Connection Keep-alive or close Connection: keep-alive
Content-Length Size of request body Content-Length: 256
Content-Type Type of request body Content-Type:
application/json
If-Modified-Since Conditional request If-Modified-Since: Wed, 21
Oct 2025
Referer Previous page URL Referer: [Link]

HTTP Request Body


Purpose: Data being sent to server
When Used: - POST requests (form data) - PUT requests (file content) - Some DELETE
requests
Format Depends On Content-Type:
Content-Type: application/x-www-form-urlencoded
username=john&password=secret

Content-Type: application/json
{"username": "john", "email": "john@[Link]"}

Content-Type: multipart/form-data
(file upload with boundaries)

Example Complete POST Request:


POST /login HTTP/1.1
Host: [Link]
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
Connection: keep-alive

username=john&password=secret

HTTP Messages: Response Format

Structure
STATUS LINE
HEADERS (multiple lines)
[BLANK LINE]
[BODY - the actual document/data]
Status Line
Format: HTTP/VERSION STATUS-CODE REASON-PHRASE
Example: HTTP/1.1 200 OK

HTTP Status Codes


Format: 3-digit number where first digit indicates category
1xx - Informational (Rarely seen in practice) - 100 Continue: Proceed with body - 101
Switching Protocols
2xx - Success (Request succeeded!) | Code | Meaning | When | |——|———|——| | 200 |
OK | Successful request, body contains data | | 201 | Created | Resource created (POST/PUT
success) | | 202 | Accepted | Request accepted for processing | | 204 | No Content | Success
but no data in body |
3xx - Redirection (Need to go elsewhere) | Code | Meaning | When | |——|———|——| |
300 | Multiple Choices | Multiple versions available | | 301 | Moved Permanently | URL
changed permanently, update bookmarks | | 302 | Found | URL temporarily moved | | 304 |
Not Modified | Cached version still valid |
4xx - Client Error (Client did something wrong) | Code | Meaning | When | |——|———|
——| | 400 | Bad Request | Malformed syntax | | 401 | Unauthorized | Authentication
required | | 403 | Forbidden | Authenticated but no permission | | 404 | Not Found |
Document doesn’t exist | | 408 | Request Timeout | Client took too long | | 414 | URI Too
Long | URL too long |
5xx - Server Error (Server problem) | Code | Meaning | When | |——|———|——| | 500 |
Internal Server Error | Server crashed or exception | | 501 | Not Implemented | Method not
supported | | 502 | Bad Gateway | Upstream server error | | 503 | Service Unavailable |
Server overloaded or down | | 504 | Gateway Timeout | Upstream took too long |
Most Common Status Codes: - 200: Success ✓ - 404: Not Found ✗ - 500: Server Error ✗ -
301: Moved - 302: Temporary redirect

HTTP Response Headers


Header Purpose Example
Server Web server software Server: Apache/2.4.41
Content-Type Type of response body Content-Type: text/html
Content-Length Size of response body Content-Length: 1024
Content-Encoding Compression used Content-Encoding: gzip
Last-Modified When resource last changed Last-Modified: Wed, 21 Oct
2025
ETag Version identifier ETag: “33a64df”
Cache-Control Caching instructions Cache-Control: max-
Header Purpose Example
age=3600
Set-Cookie Store cookie at client Set-Cookie: session=abc123
Location New URL (for redirects) Location:
[Link]
Expires When content expires Expires: Wed, 21 Oct 2026

HTTP Response Body


Purpose: The actual resource requested
Common Types: - HTML page - Image (JPEG, PNG, GIF) - PDF document - JSON data - CSS
stylesheet - JavaScript file - Video stream
Example Complete Response:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 256
Last-Modified: Wed, 21 Oct 2025 14:30:00 GMT
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body>
<h1>Hello World</h1>
</body>
</html>

Conditional Requests

Problem: Bandwidth Waste


Scenario: Client requests same page frequently - Every time: Full page downloaded - Even
if unchanged - Wastes bandwidth - Slows browsing

Solution: Conditional Requests


How It Works:
Client’s Request with Condition:
GET /[Link] HTTP/1.1
Host: [Link]
If-Modified-Since: Wed, 21 Oct 2025 14:30:00 GMT

Translation: “Send me [Link], but ONLY if it’s been modified since this date”
Server Response - Case 1: Modified
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 256

<full page content>

Server Response - Case 2: NOT Modified


HTTP/1.1 304 Not Modified
<No body - headers only>

Benefit of 304: - Client can use cached version - Only headers transmitted (tiny) - Massive
bandwidth saving - Fast page load

Implementation:
Client Side: 1. Cache page on local disk 2. Send If-Modified-Since with cached timestamp 3.
If 304: Use cached version 4. If 200: Download new version, update cache
Server Side: 1. Check if-Modified-Since header 2. Compare with file’s Last-Modified
timestamp 3. Send 304 if not modified 4. Send 200 with data if modified

HTTP COOKIES: STATE MANAGEMENT


The Problem: HTTP is Stateless

Definition of Stateless
• Each request treated as independent
• Server doesn’t remember previous requests
• No “memory” between interactions
• Fresh start for each request

Why Stateless Causes Problems


Scenario: Online Shopping
Request 1: Browse jeans
→ Server: "Here are jeans"
→ Server forgets user

Request 2: Add jeans to cart


→ Server: "Who are you? What cart?"
→ No context!

Other Problems: - Can’t track user login - Can’t maintain shopping cart - Can’t personalize
content - Can’t track user preferences
Real-World Consequence
Without cookies: - Every page load feels like first visit - Can’t stay logged in - Can’t
remember preferences - Same ads shown repeatedly (no tracking)

Cookie Solution

What is a Cookie?
Definition: Small text file stored on client computer, sent with each request
Contains: User identifier, session ID, or preference data
Size: Typically 100 bytes to 4 KB
Format: Name=Value pairs
Example Cookie:
sessionId=9f84ab6c2b3e4d7f
username=john_doe
preferences=dark_mode,large_font

How Cookies Work: 4-Step Process

Step 1: Creation (First Visit)


Scenario: User visits server for first time
Server’s Action: 1. Recognizes first-time visitor 2. Generates unique identifier (cookie
value) 3. Creates database entry for this user 4. Prepares response with Set-Cookie header
Response Header:
HTTP/1.1 200 OK
Set-Cookie: sessionId=abc12345xyz789
Content-Type: text/html
...

Step 2: Storage (Client Side)


Browser’s Action: 1. Receives response with Set-Cookie header 2. Extracts cookie value
(sessionId=abc12345xyz789) 3. Stores cookie locally: - Session Cookies: In memory (lost
when browser closes) - Persistent Cookies: On disk (survives browser restart) 4. Stores
until expiration date (if set)
Storage Location (depends on browser): - Firefox: profiles/default/[Link] -
Chrome: Local Storage folder - Safari: Library/Safari/[Link]

Step 3: Usage (Automatic Transmission)


Scenario: Same user visits same website again
Browser’s Automatic Action: 1. User types URL or clicks link 2. Browser prepares request
3. Automatically checks for cookies matching this domain 4. Includes all matching cookies
in request header 5. User never sees this (transparent)
Request Header:
GET /shopping HTTP/1.1
Host: [Link]
Cookie: sessionId=abc12345xyz789
...

Key Point: Cookie sent automatically and transparently - user doesn’t need to do
anything!

Step 4: Recognition (Server Side)


Server’s Action: 1. Receives request with Cookie header 2. Extracts cookie value
(sessionId=abc12345xyz789) 3. Looks up in database using this session ID 4. Retrieves
associated user data: - Login status - Shopping cart items - User preferences - Purchase
history - Browsing history 5. Uses this info to customize response
Result: Server “remembers” user and maintains state!

Cookie Uses

1. Electronic Commerce
Purpose: Shopping cart persistence
How It Works: - User adds item to cart - Server stores item in database linked to sessionId
- Cookie maintains sessionId across pages - User can browse different products - Server
always knows what’s in cart - Checkout retrieves cart from database
Benefit: Can leave and return later, cart still there (within session timeout)

2. Web Portals and Personalization


Purpose: Remember user preferences and login
Examples: News portals, email services, dashboards
Personalization Options: - Language choice (English, Spanish, Chinese, etc.) - Theme
selection (light, dark, high contrast) - Layout preferences (sidebar position, font size) -
Widget selections (which news categories to show) - Bookmarked content (saved articles,
favorites) - Login status (stay logged in)
How It Works: 1. User logs in → Server sets cookie 2. User customizes preferences →
Server stores in database 3. Next visit: Cookie identifies user 4. Server retrieves
preferences from database 5. Page rendered with user’s choices automatically
3. Advertising and Analytics
Purpose: Track user behavior across websites
What Gets Tracked: - Pages visited - Time spent on each page - Clicks (which links user
follows) - Search queries - Products viewed - Purchases made
Data Uses: - Advertising: Show relevant ads based on interests - Analytics: Understand
user behavior, improve website - Recommendations: “Users who viewed X also viewed Y”
- Performance: Identify slow pages, track errors
Privacy Concern: Cross-site tracking (ads follow you everywhere)
Regulation: GDPR, CCPA require explicit consent for tracking cookies

4. Authentication and Session Management


Purpose: Keep user logged in across visits
Flow: 1. User logs in with credentials 2. Server validates credentials 3. Server creates
session in database 4. Server issues session cookie 5. User visits any page on site → Cookie
sent automatically 6. Server checks session exists → User authenticated 7. No need to login
again!
Timeout: Session expires after inactivity (e.g., 30 minutes)

Cookie Anatomy
Basic Format:
Set-Cookie: name=value; [attributes]

Example:
Set-Cookie: sessionId=abc123; Domain=.[Link]; Path=/;
Max-Age=86400; Secure; HttpOnly

Components:

Component Example Meaning


Name sessionId Cookie identifier
Value abc123 Data stored
Domain .[Link] Which sites can access
Path / Which paths can access
Max-Age 86400 (seconds) How long until expires
Expires Date string Alternative to Max-Age
Secure Flag Only send over HTTPS
HttpOnly Flag JavaScript cannot
access
Component Example Meaning
SameSite Strict/Lax/None CSRF attack prevention

WEB CACHING: PROXY SERVERS


Problem: Repetitive Downloads
Scenario: Many users repeatedly request same content - [Link] requested millions of
times daily - Same file downloaded every time - Wastes network bandwidth - Slows
browsing - Server overloaded
Solution: Cache frequently-accessed content locally

What is a Proxy Server?

Definition
• Intermediary computer between client and web server
• Acts as both server (to client) and client (to web server)
• Sits at network gateway (campus, company, ISP)
• Caches frequently accessed pages

Architecture
Client 1 ─┐
Client 2 ─┤─→ Proxy Server ←→ Original Web Server
Client 3 ─┘

Proxy server is the "middleman"

How Proxy Caching Works

First Request (Cache Miss)


Scenario: First user on network requests [Link]
User's Browser

"Get [Link]"

Proxy Server checks cache

"Not in cache" (MISS)

Proxy acts as CLIENT, requests from [Link]

Google's server responds

Proxy stores copy in cache

Proxy sends to user

User receives page

Second Request (Cache Hit)


Scenario: Another user requests same page
User's Browser

"Get [Link]"

Proxy Server checks cache

"Found in cache!" (HIT) ← INSTANT!

Proxy sends cached copy to user

No need to contact [Link]

User receives page (FAST!)

Proxy Server Benefits


Benefit Explanation Result
Bandwidth Saving Don’t download same file repeatedly Reduce ISP costs
Speed Improvement Local cache is fast Faster page loads
Server Load Reduction Fewer requests reach origin server Server less
overwhelmed
Latency Reduction No need to cross Internet Instant response
Offline Access Can serve cached content even if Partial functionality
internet down

Proxy Cache Update Strategy

Problem: Stale Data


Scenario: Original website updates, but cache has old version
Solution Options:
1. TTL (Time-To-Live) - Cache item valid for X hours - After X hours: Check with origin
server for updates - Prevents very stale content - Common: 24 hours for most content
2. Last-Modified Header - Server sends Last-Modified date with content - Proxy sends If-
Modified-Since with cached date - Server responds 304 (not modified) or 200 (new
content) - Accurate but requires server communication
3. ETag (Entity Tag) - Server assigns version ID to content - Proxy checks if ETag changed
- Efficient validation
4. Freshness-Dependent Lists - Admin specifies frequently-updated content (news) -
Proxy refreshes these often - Less-updated content cached longer

SECTION 5.4: FILE TRANSFER PROTOCOL (FTP)


Introduction to FTP

Definition
• Standard TCP/IP protocol for copying files between computers
• Application layer protocol
• Older but still widely used
• Specialized for file transfer (vs HTTP which is general-purpose)

Why FTP When HTTP Can Transfer Files?


Advantages of FTP: 1. Specialized: Designed specifically for file transfer 2. Binary
Support: Handles binary files efficiently 3. Directory Operations: List files, change
directories, make folders 4. Resume Capability: Can resume interrupted transfers 5.
Performance: Optimized for large files 6. Control Commands: Separate control channel
for advanced operations
When to Use FTP: - Large file transfers - Directory operations needed - Batch operations
(multiple files) - Network software distribution - Server administration and updates

The Challenge of File Transfer


Heterogeneous Systems Require Solutions:

Challenge Examples Solution


File naming UNIX: lowercase; FTP negotiates format
Windows: uppercase; Mac:
special chars
Data representation ASCII vs EBCDIC; line FTP specifies type
endings (LF vs CRLF)
Directory structure /path/to/file vs C: FTP abstracts paths
Permissions Read/Write/Execute FTP checks permissions
attributes
Binary vs Text Different handling needed FTP type negotiation
FTP Architecture: Control vs. Data Separation

Unique Feature of FTP: Two Parallel Connections


Why Two Connections? - Control: Lightweight, text-based commands - Data: Heavy file
transfer - Separation: One can operate independently of other - Efficiency: Control
connection stays open, data connections open/close per file

Client Components
Component Purpose
User Interface CLI or GUI for human user
Client Control Process Sends commands, receives
responses
Client Data Transfer Process Handles actual file data

Server Components
Component Purpose
Server Control Process Listens for commands, executes them
Server Data Transfer Process Manages data connection, transfers
files

FTP Connections

Connection 1: The Control Connection


Aspect Details
Purpose Send commands (login, get, put) and
receive responses
Lifetime Entire FTP session (remains open)
Server Port Well-known port 21
Client Port Ephemeral port (random, assigned
by OS)
Protocol Text-based command/response
using NVT ASCII
Format 3-4 letter commands + optional
arguments
Responses 3-digit codes + explanatory text

Opening:
Client connects to server:21
Server responds: 220 Service ready
Client: HELO
Server: 250 OK

Closing:
Client: QUIT
Server: 221 Goodbye
Connection closes

Duration: Open for entire session, even while transferring data

Connection 2: The Data Connection


Aspect Details
Purpose Exclusively for transferring actual file data
Lifetime Transient - opened per file transfer, closed
when done
Server Port Well-known port 20 (standard, depends on
mode)
Client Port Ephemeral port
Protocol Binary or ASCII stream (depends on file type)
Multiple Transfers Data connection open/close multiple times
per session
Control During Transfer Control connection remains open

Lifecycle:
File transfer initiated

Data connection opened

File data transferred

Data connection closed

Control connection still active

Next file transfer can begin

FTP Control Connection: Commands and Responses

FTP Commands (Client → Server)


Format: 3-4 uppercase letters, optional arguments
Access Control Commands:

Command Full Form Purpose


USER USER username Send username
PASS PASS password Send password (after
USER)
QUIT QUIT Close session
File Management Commands:

Command Full Form Purpose


RETR RETR filename Retrieve (download)
file
STOR STOR filename Store (upload) file
DELE DELE filename Delete file
RNFR RNFR oldname Rename from (step 1)
RNTO RNTO newname Rename to (step 2)
APPE APPE filename Append to file

Directory Management:

Command Full Form Purpose


CWD CWD dirname Change working
directory
CDUP CDUP Change up one
directory
PWD PWD Print working
directory
LIST LIST [dirname] List directory contents
NLST NLST [dirname] List names only
MKD MKD dirname Make directory
RMD RMD dirname Remove directory

Data Connection Mode:

Command Full Form Purpose


PASV PASV Passive mode (server
opens port)
PORT PORT Active mode (client
h1,h2,h3,h4,p1,p2 port)
TYPE TYPE A/I/E Set file type
(ASCII/Image/EBCDIC)
MODE MODE S/B/C Set mode
(Stream/Block/Compr
essed)

FTP Responses (Server → Client)


Format: 3-digit code + explanatory text
Code Structure: - First digit: Success level - Second digit: Category - Third digit: Specific
condition
2xx - Success:
200 Command OK
220 Service ready
230 User logged in
226 Transfer complete

3xx - Positive intermediate (more info needed):


331 Username OK; password required
350 Requested file action pending further information

4xx - Transient negative (try again later):


421 Service not available
425 Cannot open data connection
450 Requested file action not taken (file unavailable temporarily)

5xx - Permanent negative (don’t try again):


500 Syntax error
530 User not logged in
550 Requested action not taken (file unavailable)

FTP Data Connection: Active vs. Passive Mode

PROBLEM: How is data connection initiated?


Question: Who initiates the data connection - client or server?
Two solutions with different security implications.

Solution 1: ACTIVE MODE (Default, Standard)


How It Works:
Step 1: Client chooses an available ephemeral port (e.g., 50000)
Step 2: Client sends PORT command over control connection
Control Connection:
Client → Server: PORT 192,168,1,100,195,80
(Means: Client IP [Link], port 50000 = 195*256+80)

Step 3: Server sends acknowledgment


Control Connection:
Server → Client: 200 Command OK

Step 4: Server initiates data connection


Server (port 20) → Client (port 50000)
Server opens connection from its port 20 to client's port 50000

Step 5: File data flows over data connection


Data Connection (bidirectional):
Server ↔ Client
File transferred

Step 6: Data connection closes


After file transfer complete, connection closes
Control connection remains open

Diagram:
CLIENT SERVER
:50000 ←─────────────────────── :20 (Data)
Port for data listening connects here

:60000 ─────────────────────→ :21 (Control)


Sends PORT 192,168,1,100,195,80 over this

Problem with ACTIVE mode: Client must accept incoming connection (firewall blocks)

Solution 2: PASSIVE MODE (PASV)


How It Works:
Step 1: Client sends PASV command over control connection
Control Connection:
Client → Server: PASV

Step 2: Server opens an ephemeral port (e.g., 60000)


Step 3: Server sends response with port number
Control Connection:
Server → Client: 227 Entering Passive Mode (192,168,1,50,234,96)
(Means: Server IP [Link], port 60000 = 234*256+96)

Step 4: Client initiates data connection


Client (ephemeral port) → Server (port 60000)
Client opens connection to server's port 60000

Step 5: File data flows


Data Connection (bidirectional):
Client ↔ Server
File transferred

Step 6: Data connection closes


Control connection remains open

Diagram:
CLIENT SERVER
:50001 ──────────────────────→ :60000
Client initiates to server's listening port

:50002 ←──────────────────────────→ :21


Control connection

Advantage: Avoids firewall issues (client initiates, not server)

Comparison
Aspect ACTIVE PASSIVE
Initiator Server connects to client Client connects to server
Client Port Listen and accept Connect and send
Firewall Issues Client firewall blocks Usually passes through
Modern Default Rarely used Most common
Why Passive Clients often behind Client outbound works better
firewalls

FTP File Attributes and Transfer Parameters


Before Transfer: Agreement on Attributes
Question: How should file be transferred?
Answer: Client and server agree on three attributes.

Attribute 1: File Type


Type Name Use Special Handling
ASCII Text Text files, Line-ending conversion (LF ↔ CRLF)
code
EBCDIC EBCDIC IBM Legacy systems
mainframe
s
IMAGE Binary Executable No conversion - bit-exact copy
s, images,
video,
archives

Examples:
TYPE A → Text file, convert line endings
TYPE I → Binary file (image), exact copy
TYPE E → IBM EBCDIC file

Attribute 2: Data Structure


Structure Description Use
File Continuous stream Default, most common
Record Records separated Text files, fixed-record
formats
Page Indexed pages Rare, special systems

Attribute 3: Transmission Mode


Mode Description Use
Stream Bytes flow continuously, TCP handles delivery Default, most
common
Block Data divided into blocks with 3-byte headers Reliable
detection
Compressed Data compressed (e.g., run-length encoding) Save bandwidth

Complete FTP Session Example

Scenario: User downloads file named “[Link]”


Step 1: Control Connection Establishment
Client connects to Server:21

Server: 220 Service ready (FTP server running)
Client: USER john
Server: 331 Username OK; password required
Client: PASS secret123
Server: 230 User logged in

Step 2: Navigate to Correct Directory


Client: CWD /documents
Server: 250 Directory changed
Client: PWD
Server: 257 "/documents" is current directory

Step 3: Set Transfer Parameters


Client: TYPE I (Binary mode for PDF)
Server: 200 Command OK
Client: MODE S (Stream mode)
Server: 200 Command OK

Step 4: Initiate Data Connection (Passive Mode)


Client: PASV
Server: 227 Entering Passive Mode (192,168,1,50,234,96)
(Server listening on [Link]:60000)

Step 5: Request File Transfer


Client: RETR [Link]
Server: 150 Opening data connection
[Data connection opens]
[PDF file data flows over data connection]
[Data connection closes]
Server: 226 Transfer complete (over control connection)

Step 6: Logout
Client: QUIT
Server: 221 Goodbye
[Control connection closes]

FTP Security Issues

Problem 1: Plaintext Passwords


Vulnerability:
Client: PASS secret123

Network packet sniffed

Attacker reads password plaintext

Attacker gains access

Risk: High - login credentials easily stolen

Problem 2: Plaintext Data


Vulnerability:
Client uploads financial_data.csv

File transmitted unencrypted

Attacker packet sniffs

Attacker reads sensitive data

Risk: High - all file contents exposed

Problem 3: Man-in-the-Middle Attacks


Vulnerability: Attacker intercepts and modifies files during transfer
Risk: Medium to High - file integrity compromised

FTP Security Solutions

Solution 1: SSL/TLS Wrapper (FTPS)


Mechanism: - Add SSL/TLS encryption between FTP and TCP - Encrypts all FTP commands
and data - Transparent to FTP protocol - Uses port 990 (implicit) or 21 (explicit with
STARTTLS)
Advantages: - Standard FTP commands work - Full encryption - Authentication of server
certificate
Example Flow:
FTP Protocol

SSL/TLS Encryption Layer ← Secures everything

TCP

Network

Solution 2: SFTP (SSH File Transfer Protocol)


Mechanism: - Completely different protocol (not FTP + SSL) - Runs over SSH (Secure Shell)
- SSH provides encryption + authentication - Port 22 (same as SSH)
Advantages: - More modern - SSH integration - Better security model - Works through
firewalls better
When to Use: - New systems prefer SFTP - Compatibility with SSH infrastructure - Better
security posture

SECTION 5.5: ELECTRONIC MAIL (EMAIL)


Introduction to Electronic Mail

Characteristics
Different from HTTP/FTP: - HTTP/FTP: Synchronous - Client initiates - Server responds
immediately - Two-way real-time interaction
• Email: Asynchronous
– Sender and receiver not online simultaneously
– Sender doesn’t need recipient’s computer on
– Recipient retrieves when ready
– Days can pass between send and read
Architecture Difference: - HTTP: Direct client-server - Email: Sender → Intermediate
Server → Recipient - Indirect (through mail servers) - One-way push (initially) - Recipient
pulls when ready

Email Architecture: Three Agent Types

Component 1: User Agent (UA)


What It Is: Email client program
Examples: Outlook, Thunderbird, Gmail web interface, Apple Mail
Functions: - Compose messages - Read messages - Reply to messages - Organize folders -
Configure account
Types: - Desktop Clients: Standalone programs - Web-based: Access via browser -
Mobile: Smartphone apps

Component 2: Message Transfer Agent (MTA)


What It Is: Mail server program that moves email
Role: Transfers email between servers (network to network)
Protocol Used: SMTP (Simple Mail Transfer Protocol)
Examples: Sendmail, Postfix, Exim, Microsoft Exchange
Function: - Receive from sender’s UA - Route across Internet - Deliver to recipient’s server
- Handle bounces and errors

Component 3: Message Access Agent (MAA)


What It Is: Protocol/service for recipient to retrieve mail
Role: Allows recipient to pull messages from server
Protocols: - POP3: Simple download - IMAP: Advanced management
Port Numbers: - POP3: Port 110 - IMAP: Port 143
Secure Versions: - POP3S: Port 995 (with SSL/TLS) - IMAPS: Port 993 (with SSL/TLS)

Email Delivery Scenario

Complete Email Journey


Step 1: Alice Composes Message
Alice (User) → Outlook (UA)
Compose: "Hello Bob"
To: bob@[Link]
From: alice@[Link]
Step 2: Alice Sends
Outlook (UA) → LocalMailServer (MTA Client)
Deposits in local queue

Step 3: Intermediate Delivery


LocalMailServer (MTA Client)
↓ SMTP
InternetDNS: "Where is [Link]'s mail server?"

Locate [Link] mail server
↓ SMTP
Send to [Link] (MTA Server)

Step 4: Server Reception


[Link] (MTA Server) receives message

Checks: Is bob@[Link] valid?

Yes → Places in Bob's mailbox

Step 5: Bob Retrieves (Days Later)


Bob (User) → Outlook (UA)
"Check mail"

Outlook contacts [Link] (MAA Server)
↓ POP3 or IMAP
Retrieves messages from Bob's mailbox

Messages display in Outlook

Step 6: Bob Reads and Replies


Bob reads Alice's message
Bob clicks Reply
Composess response
Bob clicks Send
Process repeats (now Bob is sender)

Email Protocols: Push vs. Pull

PUSH Protocol: SMTP (Simple Mail Transfer Protocol)


When Used: - Sender → Sender’s Server: UA pushes to MTA client - Sender’s Server →
Recipient’s Server: MTA client pushes to MTA server
Directionality: One-way (client → server only)
Port: 25 (standard), 587 (submission port with auth)
Characteristic: Client initiates, server accepts

PULL Protocol: POP3/IMAP


When Used: Recipient pulls messages from mail server
Directionality: One-way (client → server for commands, server → client for data)
Port: - POP3: 110 - IMAP: 143
Characteristic: Client retrieves when ready

EMAIL MESSAGE STRUCTURE


Anatomy of an Email
Two Parts:

Part 1: Envelope
Purpose: Routing information for MTAs
Contains: - Sender address (from) - Recipient address (to) - CC, BCC fields - Routing
information
Used By: Mail servers for delivery
Visible To: Typically hidden from user

Part 2: Message
Two Sections:
A. Header: - Sender info - Recipient info - Subject - Date sent - Message-ID - References (for
threading) - Content type
B. Body: - Actual message text - HTML content - Attachments metadata
Visible To: User sees header and body

Email Addressing
Format: local-part@domain-name
Examples:
[Link]@[Link]
alice_smith@[Link]
support+bug123@[Link]

Components:
Component Example Details
Local Part [Link] Mailbox identifier on
the server
**@** Separator Literal @ symbol
Domain [Link] Mail server domain

Local Part Rules: - Up to 64 characters - Alphanumeric, dots, underscores, hyphens -


Cannot start/end with dot - Case-insensitive (but often preserved)
Domain Part: - Must be valid domain - Must have MX (Mail eXchange) record in DNS -
Case-insensitive

SMTP (SIMPLE MAIL TRANSFER PROTOCOL)


Introduction to SMTP

Definition
• Standard protocol for sending emails
• Push protocol (client pushes message to server)
• Port: 25 (relay), 587 (submission with auth)
• Text-based: Human-readable commands

Uses
Context Details
Sender → Server UA sends mail to sender’s MTA
Server → Server MTAs relay mail across Internet
Cannot Use For Recipient to retrieve mail (that’s
POP3/IMAP)

SMTP Connection Phases

Phase 1: Connection Establishment


Client connects to Server:25

Server: 220 [Link] ESMTP Postfix (Service Ready)

Client: HELO [Link]
(or EHLO for Extended SMTP)

Server: 250 Hello [Link], pleased to meet you

Phase 2: Message Transmission


Step 1: Identify Sender
Client: MAIL FROM:<alice@[Link]>
Server: 250 2.1.0 OK

Step 2: Identify Recipient


Client: RCPT TO:<bob@[Link]>
Server: 250 2.1.5 OK

Note: Can have multiple RCPT TO for multiple recipients


Step 3: Send Message
Client: DATA
Server: 354 Start mail input; end with <CRLF>.<CRLF>

Client sends message line by line:
From: Alice <alice@[Link]>
To: Bob <bob@[Link]>
Subject: Meeting Tomorrow
Date: Tue, 21 Oct 2025 10:30:00 +0000

Hello Bob,
Let's meet tomorrow at 10 AM.
Thanks,
Alice
.

Server: 250 2.0.0 OK: Message queued as ABC123

Key Details: - Message body ends with . on its own line (period, CR, LF) - This signals end
of message to server - Server responds with message ID

Phase 3: Connection Termination


Client: QUIT
Server: 221 2.0.0 Bye
Connection closes

SMTP Response Codes


Format: 3-digit code + text
2xx (Success):
220 Service ready
250 Requested action OK, completed

3xx (Positive Intermediate):


354 Start mail input, end with <CRLF>.<CRLF>

4xx (Transient Failure - Retry Later):


421 Service not available
450 Requested action not taken (mailbox busy)

5xx (Permanent Failure - Don’t Retry):


500 Syntax error
550 Requested action not taken (user not found)

SMTP Commands
Command Example Purpose
HELO HELO myhost Identify client
EHLO EHLO myhost Extended SMTP
MAIL FROM MAIL Specify sender
FROM:sender@exampl
[Link]
RCPT TO RCPT Specify recipient
TO:recipient@example.
com
DATA DATA Start message
transmission
QUIT QUIT End session
RSET RSET Reset session
NOOP NOOP No operation (keep
alive)
VRFY VRFY user Verify user exists
EXPN EXPN mailinglist Expand distribution list

POP3 AND IMAP4: MESSAGE ACCESS PROTOCOLS


POP3 (Post Office Protocol Version 3)

Overview
Aspect Details
Purpose Simple mail retrieval from server to
client
Port 110 (clear) or 995 (SSL/TLS)
Model Download-and-delete (by default)
Complexity Simple
Features Basic (no folder management)
Use Case Single-device mail access
How POP3 Works
Two Modes:
Delete Mode (Default):
Step 1: Connect and login
Step 2: Retrieve messages
Step 3: Delete messages from server
Result: Client has copy, server is empty
Good for: Single device (laptop)
Bad for: Multiple devices (can't sync)

Keep Mode:
Step 1: Connect and login
Step 2: Retrieve messages
Step 3: Messages stay on server
Result: Both client and server have copy
Good for: Reference, multiple devices (limited)
Bad for: Server storage fills up

POP3 Commands
Command Purpose
USER Send username
PASS Send password
STAT Get mailbox status (number of
messages, total size)
LIST List message numbers and sizes
RETR Retrieve specific message
DELE Delete message
QUIT Close connection (commit
deletions)

POP3 Limitations
• No folder management: Can’t organize on server
• No searching: Must download all to search
• Synchronization: Difficult with multiple devices
• Bandwidth: Must download entire message
• Limited control: Can only download or delete

IMAP4 (Internet Mail Access Protocol Version 4)

Overview
Aspect Details
Purpose Advanced mail management on
Aspect Details
server
Port 143 (clear) or 993 (SSL/TLS)
Model Manage on server
Complexity More complex
Features Comprehensive
Use Case Multi-device mail access

Key Difference from POP3


POP3: Download messages to client (delete from server)
IMAP: Manage messages on server (client sees server state)
Metaphor: - POP3: Library book - you take it home, library no longer has it - IMAP: Card
catalog - you look at catalog entries on server, server keeps master copy

IMAP4 Features
Feature Description Example
Folder Management Create, delete, rename folders on Create “Projects” folder
server
Message Flags Mark messages (read, important, Flag important emails
deleted, etc.)
Server Search Search on server before Find all from “John”
downloading
Partial Download Get header without body Preview before
download
Multiple Devices Consistent view across devices Check mail on phone,
laptop, desktop
IDLE Server notifies of new mail Real-time notifications

Why IMAP for Modern Users


Scenario: User has three devices (phone, laptop, desktop)
With POP3: - Phone downloads → emails gone from server - Laptop downloads → emails
gone from server - Desktop sees nothing! - Disconnected experience
With IMAP: - Phone accesses server folder structure → reads email - Laptop accesses same
folders → sees same messages - Desktop accesses same folders → sees same messages -
Consistent across all devices! - Synchronized state

IMAP4 Commands (Selection)


Command Purpose
LOGIN Authenticate
Command Purpose
CREATE Create mailbox
DELETE Delete mailbox
RENAME Rename mailbox
LIST List mailboxes
SELECT Open mailbox
SEARCH Search for messages
FETCH Retrieve message
STORE Set flags
EXPUNGE Delete marked messages
LOGOUT Disconnect

POP3 vs IMAP4 Comparison


Feature POP3 IMAP4
Folder Management No Yes
Server-side folders No Yes
Multiple devices Poor Excellent
Search capability Client-side only Server-side
Download options Full message only Partial (header, body)
Real-time sync No Yes (IDLE)
Server storage Minimal More (keeps copies)
Complexity Simple Complex
When to use Single device Multiple devices

MIME (MULTIPURPOSE INTERNET MAIL EXTENSIONS)


The Problem: 7-bit ASCII Limitation

Original SMTP Limitation


SMTP designed for: 7-bit NVT ASCII text only
Cannot send: - Non-English text (French accents, Chinese characters, Arabic) - Binary files
(Images, Videos, Audio, Executables) - Rich formatting (Bold, italics, colors) - Complex
structures
Real-world Problem: - Company wants to send customer logo in email (binary image) -
SMTP says: “No, I only handle ASCII text” - Solution needed!
What MIME Does

Translation Service
MIME acts as translator:
Non-ASCII Data

MIME Encoding (at sender)

7-bit ASCII representation

SMTP Transfer (works perfectly)

MIME Decoding (at receiver)

Original Non-ASCII Data

Mechanism: Transforms binary into safe ASCII subset

MIME Process

Sender Side: Encoding


Original Data
(e.g., JPEG image file)

MIME Encoder
(transforms into ASCII)

Temporary ASCII representation
(safe for SMTP)

Added to email body

Transmission
SMTP transfers the ASCII representation
(no issues, it's plain ASCII)

Receiver Side: Decoding


ASCII representation received

MIME Decoder
(transforms back to binary)

Original data recovered
(e.g., JPEG viewable as image)

MIME Headers
Purpose: Tell receiver how to decode
Added to email message:

Header 1: MIME-Version
MIME-Version: 1.1
(Indicates MIME usage and version)

Header 2: Content-Type
Content-Type: type/subtype; parameters

Examples:
Content-Type: text/plain
Content-Type: text/html
Content-Type: image/jpeg
Content-Type: audio/mpeg
Content-Type: video/mp4
Content-Type: application/pdf
Content-Type: multipart/mixed (for multiple parts)

Tells receiver: What kind of data is attached

Header 3: Content-Transfer-Encoding
Specifies HOW data was converted to ASCII

Values:
- 7bit: No conversion (already 7-bit ASCII)
- 8bit: No conversion (has 8-bit chars)
- binary: No conversion (binary data)
- quoted-printable: Text-heavy, few non-ASCII chars
- base64: General binary data

Most Common: base64 (universal, ~33% overhead)

Header 4: Content-Id
Content-Id: <unique-identifier>
(Uniquely identifies this MIME part)

Header 5: Content-Description
Content-Description: My Picture
(Human-readable description)

Base64 Encoding (Most Common)

Purpose
• Encode any binary data into safe ASCII
• Most universal MIME encoding

How It Works
Input: Binary data (any bytes)
Process: 1. Take 24 bits (3 bytes) of binary data 2. Divide into four 6-bit chunks 3. Map
each 6-bit value to Base64 character set
Base64 Character Set (64 characters):
A-Z (26) + a-z (26) + 0-9 (10) + +, / (2) = 64 characters

Output: ASCII characters representing original

Example
Original: 3 bytes of binary data
Binary: 01001000 01100001 01101100
Hex: 48 61 6C (represents "Hal")

Conversion:
Split into 6-bit chunks:
010010 000110 000101 101100

Map to Base64:
010010 = S (index 18)
000110 = G (index 6)
000101 = F (index 5)
101100 = s (index 44)

Result: "SGFs" (4 ASCII characters)

3 bytes → 4 ASCII characters (overhead: 33%)

Padding
If input not multiple of 3: - Add padding zeros - Pad output with = signs - Receiver knows
to ignore

Example Complete Email with MIME


From: alice@[Link]
To: bob@[Link]
Subject: Picture attached
MIME-Version: 1.1
Content-Type: multipart/mixed; boundary="----boundary"

------boundary
Content-Type: text/plain

Hi Bob, here's the picture you wanted.

------boundary
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-Description: My vacation photo

/9j/4AAQSkZJRgABAQEAYABgAAD...
(hundreds of base64 characters)
...lQWEBAEBAQEBAQEBAf/Z
------boundary--

WEB-BASED MAIL
Traditional vs. Web-Based Email

Traditional Email
Setup: - User installs email client (Outlook, Thunderbird) - Client connects to mail server
(POP3, IMAP) - Mail downloaded and stored locally
Access: Desktop/Laptop only (where client is installed)
Example: Microsoft Outlook

Web-Based Email
Setup: - No installation needed - Access via any web browser - Mail stays on server - Server
provides web interface
Access: Any computer with internet (phone, tablet, internet cafe)
Examples: Gmail, Yahoo Mail, [Link], ProtonMail

Case 1: Only Receiver Uses Web-Based Mail


Scenario: - Alice: Traditional email client (Outlook) - Bob: Web-based email (Gmail)
Architecture:
Alice (Outlook)
↓ SMTP
Alice's server
↓ SMTP
↓ (Internet relay)
Gmail's server

Bob's mailbox (on Gmail server)

Bob's Browser
↓ HTTP
Gmail web interface

Protocols Used: - Alice → Server: SMTP - Server → Server: SMTP (inter-server relay) -
Bob → Gmail: HTTP/HTTPS (web browser)
Key Point: SMTP still handles server-to-server transfer

Case 2: Both Use Web-Based Mail


Scenario: - Alice: Web-based email (Gmail) - Bob: Web-based email ([Link])
Architecture:
Alice's Browser
↓ HTTP/HTTPS
Gmail's server
↓ SMTP (internal)
↓ Sends message
↓ SMTP (inter-server relay)
↓ (Internet)
[Link]'s server

Bob's mailbox

Bob's Browser
↓ HTTP/HTTPS
[Link] web interface

Protocols Used: - Alice → Gmail: HTTP/HTTPS - Gmail → Gmail internal: SMTP - Gmail
→ Outlook: SMTP (relay) - Bob → Outlook: HTTP/HTTPS
Key Point: Even web-based, servers still use SMTP to relay

Advantages of Web-Based Mail


Advantage Explanation
Accessibility Access from any device, anywhere
No Installation No software to install or update
Backup Mail automatically backed up on
server
Sync Same view across all devices
Features Server provides rich features
(folders, filters)
Storage Large server storage (Gmail: 15GB
free)

Disadvantages of Web-Based Mail


Disadvantage Explanation
Privacy Server operator has access to emails
Internet Required Cannot work offline
Speed Web interface slower than native
client
Disadvantage Explanation
Third-party Dependent on service provider
reliability
Storage Server storage limited (quota)

EMAIL SECURITY
Insecurity of Basic Email

Problems
SMTP Vulnerability: - Plaintext passwords (USER, PASS sent unencrypted) - Plaintext
body (anyone sniffing network can read) - No authentication (anyone can claim to be
sender)
POP3/IMAP Vulnerability: - Plaintext authentication - Unencrypted mail download
Consequences: - Login credentials stolen - Mail intercepted and read - Spoofed emails
(fake sender) - Malicious attachments added in transit

Security Solutions: PGP and S/MIME

Solution 1: PGP (Pretty Good Privacy)


Method: Encryption and digital signatures
What it does: - Encryption: Scrambles message (only recipient with key can read) -
Digital Signatures: Proves sender identity, ensures message unchanged - Key
Management: User manages own keys
How used: - Encrypt message before sending - Send encrypted text via email - Recipient
decrypts with private key - Verify signature with sender’s public key

Solution 2: S/MIME (Secure/Multipurpose Internet Mail Extensions)


Method: Industry standard encryption
What it does: - Same as PGP (encryption + signatures) - More standardized - Better
integration with email clients - Certificate-based (trust hierarchy)
Advantage over PGP: - Easier certificate management (CAs) - Better compatibility - More
enterprise-friendly

Modern Email Security


Current Standard: S/MIME certificates or encryption at rest
In Transit Security: TLS/SSL (encrypted connections)
At Rest: Server-side encryption (Gmail, Outlook, etc. all encrypt stored mail)
SECTION 5.6: TELNET (TERMINAL NETWORK)
Introduction to TELNET

Purpose
• Allows user on one computer to log into another computer remotely
• Access another computer’s resources and programs
• As if sitting directly at the remote keyboard
• Thousands of miles away

Example Scenarios
Scenario 1: System administrator in New York manages server in Tokyo - Logs into Tokyo
server from NYC - Runs commands remotely - Administers as if present
Scenario 2: Researcher accesses university’s powerful computer from home - Connects
from personal laptop - Runs computations on university server - Gets results back

Terminology
• Remote Logging or Remote Access: The concept
• Client (Telnet Client): User’s computer
• Server (Telnet Server): Remote computer being accessed

THE CHALLENGE: HETEROGENEOUS SYSTEMS


The Problem
Operating Systems are Different:

Aspect DOS UNIX Mac


EOF Signal Ctrl+Z Ctrl+D Command key+D
Line Ending CRLF LF CR or LF
Case Sensitivity No Yes No
Path Format C: /dir/file /dir/file

Keyboard Differences: - Different keyboards - Different character encodings - Different


terminal modes
Terminal Displays: - Different screen sizes - Different capabilities (color, graphics) -
Different escape sequences
The Core Problem
Incompatibility: - Mac user types keystroke - UNIX server doesn’t understand Mac’s
keystroke - No communication
Solution Needed: Universal language both sides understand

LOCAL VS. REMOTE LOGGING


Local Logging (Figure 26.23a)
Setup: User at physical terminal connected directly to computer
Process:
User Types → Terminal Hardware

Terminal Driver (kernel module)

Operating System

Interprets command

Launches application

Application sends output

Terminal displays result

Characteristics: - Direct connection - No network - Immediate interaction - Hardware


specific

Remote Logging (Figure 26.23b)


Setup: User wants to control remote computer over network
Process (TRADITIONAL - without TELNET):
User Types → Local Terminal Driver

Local OS (doesn't interpret, just passes through)

Network send "raw keystroke"

Remote OS receives raw keystroke

???
Problem: Remote OS doesn't understand!
(Different keystroke format)
Solution (WITH TELNET):
User Types → Local Terminal Driver

TELNET Client

Translates to universal format (NVT)

Network sends NVT byte

TELNET Server (Remote)

Translates NVT → Remote OS format

Pseudo-terminal Driver

Remote OS receives standard keystroke

OS interprets, runs application

Application output

Pseudo-terminal Driver captures

TELNET Server translates to NVT

Network sends NVT bytes

TELNET Client receives

Translates NVT → Local terminal format

Local terminal displays result

Network Virtual Terminal (NVT)

Definition
• Universal 8-bit character format
• Bridge between heterogeneous systems
• Client side: Local → NVT
• Server side: NVT → Remote OS format

NVT Character Set


Structure: 8 bits per character
Data Characters: - Based on NVT ASCII - 7 lowest bits: Standard US ASCII - Highest bit: 0
(for data) - Range: Characters 0-127 - Examples: ‘A’ (65), ‘b’ (98), ‘1’ (49)
Control Characters: - Highest bit: 1 (marks as control) - 7 lower bits: Command code -
Examples: - Interrupt process (Ctrl+C) - Are you there (telnet command) - Abort output -
Erase character/line

NVT Advantages
• Standardized
• Simple (just bytes)
• Works across all systems
• Handles both data and control

TELNET OPTIONS AND NEGOTIATION


Why Options?
Different Terminals Have Different Capabilities:
Terminal 1: Dumb terminal (basic) - 80x24 character display - Basic text only - Minimal
features
Terminal 2: Advanced terminal (sophisticated) - 120x50 character display - Colors and
graphics - Advanced cursor control - Function keys
Problem: How does server know terminal capabilities?
Solution: Negotiation

Negotiation Process
Before/during connection: 1. Client tells server: “I support colors, function keys, 8-bit
chars” 2. Server tells client: “I support echo mode, line editing” 3. Both agree on options to
use 4. Rest of session uses those options
Example:
Server: "Do you support 8-bit mode?"
Client: "Yes, 8-bit mode supported"
[Both now use 8-bit for this session]

TELNET SECURITY ISSUES


Major Vulnerability: Plaintext Transmission
Everything sent in clear: - Username: Visible to anyone sniffing network - Password:
Visible to anyone sniffing network - All commands: Visible - All output: Visible
Attack Scenario:
1. Attacker on network runs packet sniffer
2. User connects via TELNET
3. User types: login john
4. Attacker reads from network: "john"
5. User types: password secret123
6. Attacker reads from network: "secret123"
7. Attacker logs in as john!

Risk Level: CRITICAL - NEVER USE FOR SENSITIVE DATA

Why Study TELNET?


Despite Security Issues: 1. Historical: Foundation for understanding remote access 2.
Conceptual: Demonstrates fundamental problems solved 3. Learning: NVT concept
important for networking 4. Practical: Still used occasionally: - Debugging (manual HTTP
requests to port 80) - Legacy systems - Network testing (telnet [Link] 80)

TELNET COMPONENTS SUMMARY


Component Function Location
TELNET Client Translates local keystrokes User’s machine
to NVT
TELNET Server Translates NVT to remote Remote machine
OS commands
Network Virtual Terminal Universal 8-bit character Wire (transmission)
(NVT) format
Pseudo-terminal Driver Software that mimics Remote OS kernel
physical terminal
TELNET Protocol Defines options, Both sides
commands, control codes

SECTION 5.7: SECURE SHELL (SSH)


Introduction to SSH

Definition
• Secure application-layer protocol
• For remote logging and file transfer
• REPLACES: Insecure protocols (TELNET, rsh, rlogin)
• Port: 22 (standard SSH port)
• Modern Standard: SSH-2 (SSH-1 deprecated)

Design Goal
• Encrypt everything (unlike TELNET)
• Authenticate both parties
• Ensure data integrity
• Replace insecure remote access tools

Versions
Version Status Issues
SSH-1 Deprecated Security vulnerabilities
SSH-2 Current Standard Robust, incompatible
with SSH-1

SSH Architecture: Three-Layer Protocol Suite


Key Concept: SSH is NOT one monolithic protocol
Instead: Layered architecture (three protocols stacked)
╔════════════════════════════════════════════╗
║ Applications (Remote login, File transfer)║ Layer 3
╠════════════════════════════════════════════╣
║ SSH-CONN: Connection Protocol ║ Layer 2 (Upper)
║ Multiplexes channels, port forwarding ║
╠════════════════════════════════════════════╣
║ SSH-AUTH: Authentication Protocol ║ Layer 2 (Lower)
║ User authentication ║
╠════════════════════════════════════════════╣
║ SSH-TRANS: Transport Protocol ║ Layer 1
║ Encryption, integrity, key exchange ║
╠════════════════════════════════════════════╣
║ TCP (Port 22) ║ Transport Layer
╚════════════════════════════════════════════╝

Build Order: Bottom-up 1. TRANS creates secure channel 2. AUTH authenticates user
through that channel 3. CONN multiplexes applications over that channel

LAYER 1: SSH TRANSPORT PROTOCOL (SSH-TRANS)


Purpose
Goal: Create secure, encrypted tunnel on top of insecure TCP
Input: TCP (reliable but not secure)
Output: Encrypted, integrity-protected channel
SSH-TRANS Process

Step 1: TCP Connection


Client connects to Server:22
Standard TCP three-way handshake

Step 2: Protocol Negotiation


Client sends: "I support these algorithms"
Server sends: "I support these algorithms"

Negotiate:
- Encryption algorithm (AES-128, AES-256, etc.)
- Integrity algorithm (SHA-256, MD5, etc.)
- Key exchange method (Diffie-Hellman, ECDH)
- Compression method

Step 3: Key Exchange


Client and server exchange information
Compute shared secret key (unknown to eavesdroppers)
Both derive same encryption keys from secret

Step 4: Secure Channel Established


All subsequent messages encrypted
All messages integrity-checked
Channel ready for higher layers

SSH-TRANS Services Provided

1. Privacy/Confidentiality
What it does: Encrypts all messages
How: - Messages scrambled using negotiated cipher - Only recipient can decrypt (has key) -
Eavesdropper sees gibberish
Example:
Original: "password=secret123"
Encrypted: "x7#k9@m2$l8%p3&qR9()"
(meaningless to eavesdropper)

2. Data Integrity
What it does: Detects if message modified in transit
How: - Calculate cryptographic checksum of message - Send checksum with message -
Recipient recalculates checksum - Compare checksums
If Different: - Message was modified - Attacker tried to alter it - Message rejected
3. Server Authentication
What it does: Client verifies server identity
Purpose: Prevent “Man-in-the-Middle” attacks
Attack It Prevents:
Attacker on network

Intercepts client connection

Pretends to be server (impersonation)

Client connects to attacker, thinking it's server

Attacker relays to real server

Attacker sees all traffic!

SSH Solution: - Server has public key certificate - Server proves its identity using
certificate - Client verifies certificate - Attacker cannot impersonate without certificate

4. Compression
Optional service: - Compress messages before encryption - Reduce bandwidth - Side
benefit: Makes certain attacks harder

SSH-TRANS Summary
Service Provides Against
Encryption Confidentiality Eavesdropping
Integrity Data integrity Modification
Server Auth Authentication Man-in-the-middle
Compression Efficiency Bandwidth waste

LAYER 2A: SSH AUTHENTICATION PROTOCOL (SSH-AUTH)


Purpose
Question: Who is the client?
Answer: SSH-AUTH verifies client identity

Process

Prerequisite: Secure Channel Exists


SSH-TRANS has created encrypted, authenticated channel
Step 1: Client Sends Credentials
Over the secure SSH-TRANS channel:

Client sends:
{
username: "john_doe",
service: "ssh-userauth", // What service (usually SSH)
method: "password", // How to authenticate
password: "secret123" // The credential
}

Method Options: - password: Traditional username/password - publickey: Public key


cryptography - keyboard-interactive: Challenge-response - hostbased: Host-based
authentication

Step 2: Server Verifies Credentials


For password method:
Server:
1. Looks up username in user database
2. Retrieves stored password hash
3. Compares with provided password (hashed)
4. Match? → Authenticate
No match? → Deny

For public key method:


Server:
1. Looks up username
2. Finds user's public key on file
3. Uses client's signature to verify private key ownership
4. Client must have private key to create valid signature

Step 3: Server Responds


Success:
Server: "SSH_MSG_USERAUTH_SUCCESS"
Client: User is now authenticated!

Failure:
Server: "SSH_MSG_USERAUTH_FAILURE"
Client: Invalid credentials

SSH-AUTH Significance
Difference from SSL: - SSL authenticates server (server certificate) - SSH-AUTH
authenticates client (user credentials) - Complementary: Both parties authenticated
Security: - Authentication happens OVER secure channel - Credentials encrypted - No
plaintext password on wire - Even if compromised connection, attacker sees only
encrypted creds

LAYER 3: SSH CONNECTION PROTOCOL (SSH-CONN)


Purpose
Now that both parties are secure and authenticated: - What useful things can be done?
Answer: Multiplex multiple logical channels

What is Channel Multiplexing?


Problem: One TCP connection, multiple applications needed
Solution: Create multiple logical channels over one connection
Advantage: - Only one encrypted tunnel needed - Multiple applications work
simultaneously - More efficient than separate connections

Types of Channels

Channel 1: Session Channel (Remote Login)


Purpose: Interactive shell session
Use:
Client: telnet [Link]
(but now over SSH)

Secure, encrypted remote login

Example:
User types: ls -la
Server sends: List of files
User sees: File listing

Channel 2: File Transfer Channel (SFTP)


Purpose: Secure file transfer
Protocol: SFTP (SSH File Transfer Protocol)
Features: - List directories on remote - Upload files - Download files - Delete files - All
encrypted
Advantages over FTP: - Encrypted (no password sniffing) - Integrated with SSH (one
connection) - Runs over port 22 (easier through firewalls)
Channel 3: Port Forwarding/Tunneling
Purpose: Secure other applications through SSH tunnel
How It Works:
Insecure Application

Sends data to local SSH client

SSH client encrypts

Sends through SSH tunnel to server

SSH server decrypts

Forwards to destination application

Application sends response

SSH server encrypts

Sends back through tunnel

SSH client decrypts

Application receives response

Example: Securing insecure database access


Database Client (insecure)

SSH tunnel

Database Server (exposed)

Data encrypted in transit


Connection appears as SSH, not database

SSH-CONN Services
Service Description
Multiple Channels Many apps over one SSH connection
Window Size Control Flow control to prevent buffer
overflow
Channel Closure Graceful shutdown of individual
channels
Global Requests Network-level requests
SSH PACKET FORMAT
Structure
Each SSH packet has defined format:
┌─────────────────────────────────────┐
│ Length (4 bytes) │ Packet size
├─────────────────────────────────────┤
│ Padding (1-8 bytes) │ For alignment & security
├─────────────────────────────────────┤
│ Type (1 byte) │ Packet type
├─────────────────────────────────────┤
│ Data (variable) │ Actual content
├─────────────────────────────────────┤
│ CRC (4 bytes) │ Error detection
└─────────────────────────────────────┘

Field Details

Length (4 bytes)
• Specifies packet size (excluding padding)
• Receiver knows how much to read

Padding (1-8 bytes)


• Improves security
• Makes pattern analysis harder
• Aligns to block size of cipher

Type (1 byte)
• Identifies packet category
• Examples:
– SSH_MSG_CHANNEL_DATA
– SSH_MSG_CHANNEL_REQUEST
– SSH_MSG_CHANNEL_CLOSE
– SSH_MSG_GLOBAL_REQUEST

Data (Variable)
• Actual payload
• Structure depends on packet type

CRC (4 bytes)
• Cyclic Redundancy Check
• Error detection (not integrity check)
• Quick corruption detection
SSH APPLICATIONS
1. Remote Logging

Use Case: SSH replaces TELNET


Before SSH:
telnet [Link]
(everything plaintext)

With SSH:
ssh john@[Link]
(everything encrypted)

Advantages: - Secure login - Encrypted commands and output - No password sniffing -


True security

2. File Transfer (SFTP)

What is SFTP?
Definition: SSH File Transfer Protocol
Subset of SSH: Runs as subsystem over SSH connection
How It Works:
SFTP Client

SSH Connection to Server

SSH Server spawns SFTP subsystem

SFTP Server

Operations: - List files on remote (ls) - Change directory (cd) - Upload file (put) -
Download file (get) - Delete file (rm) - Create directory (mkdir)
All encrypted through SSH tunnel

Why SFTP?
Feature FTP SFTP
Encryption No Yes
Port 21 (may be blocked) 22 (usually open)
Passwords Plaintext Encrypted
Files Plaintext Encrypted
Installation FTP server SSH server
Firewall Often blocked Usually open
3. Port Forwarding/Tunneling

Use Case: Secure insecure applications


Problem: Database client sends passwords in plaintext
Solution: SSH tunnel
Setup:
Create SSH tunnel:
ssh -L 3306:localhost:3306 [Link]

Local machine
Port 3306 (client connects here)

SSH tunnel (encrypted)

Remote server
Port 3306 (database server)

How Client Uses It:


Database Client: Connect to localhost:3306

Encrypted tunnel carries data

Database Server: Receives request

Database Server response



Encrypted tunnel carries response

Database Client: Receives response

Result: Database connection secured with SSH encryption!

SSH Security Best Practices


Practice Reason
Use SSH-2 SSH-1 has known vulnerabilities
Public Key Auth Better than passwords (no
keystroke sniffing)
Disable Root Login Prevents root compromise
Disable Password Auth Force key-based auth
Change Port 22 Reduces SSH brute-force attempts
Firewall Port 22 Limit who can connect
Keep Keys Secure Private keys are critical
Key Rotation Periodic key changes
SECTION 5.8: DOMAIN NAME SYSTEM (DNS)
Introduction to DNS

The Problem: Names vs. Numbers


Computers need: IP addresses (numbers) - IPv4: 32-bit number (e.g., [Link]) -
IPv6: 128-bit number (e.g., 2001:4860:4860::8888)
Humans prefer: Domain names (words) - e.g., [Link], [Link], [Link]
Disconnect: How do we bridge from names to numbers?
Solution: Domain Name System (DNS)

Purpose of DNS
Primary Function: Translate domain names to IP addresses
Analogy: Telephone directory - Look up: Person’s name - Get: Phone number - DNS
version: Look up domain name, get IP address

Why DNS Matters


Without DNS: - Users must remember: [Link] = [Link] - Impossible to
remember hundreds of IPs - Internet unusable by humans
With DNS: - Remember domain names (easy) - DNS does the translation - Humans can use
Internet

The Challenge: Centralization vs. Distribution

Early Internet Solution: [Link]


Concept: Single file with all name-to-address mappings
Format:
[Link] [Link]
[Link] [Link]
[Link] [Link]
...
(thousands of entries)

Problem: As Internet grew, became unmanageable

Why Centralization Failed


Problem Why
Traffic Single server can’t handle billions of
queries
Problem Why
Reliability Server fails → entire name
resolution fails
Latency Single server can’t be close to all
users
Maintenance Can’t update in real-time for all
changes
Scale Millions of new domains daily

Solution: Distribute the database

DNS Architecture: Hierarchical and Distributed


Key Idea: Divide responsibility among many computers
Result: - No single point of failure - Queries handled locally (faster) - Maintenance
distributed - Scalable globally

NAME SPACE
What is a Name Space?
Definition: Mapping of addresses to unique names
Goal: Every IP address (address) maps to unique name (no duplicates)

Two Models

Model 1: Flat Name Space


Structure: Single sequence of characters, no hierarchy
Examples:
printer1
marketing-pc
john-laptop
server01

Problems: - Must be centrally controlled (prevent duplicates) - No organization structure -


Doesn’t scale - Not suitable for Internet

Model 2: Hierarchical Name Space


Structure: Multiple parts, each part organized
Examples:
[Link]
↓ ↓ ↓
↓ ↓ └─ Top-level domain
↓ └──── Domain name
└────── Subdomain (www)

[Link]
↓ ↓ ↓
↓ ↓ └─ Same TLD
↓ └──── Same domain
└────── Different subdomain (mail)

Advantages: - Decentralized Control: - Central authority assigns “[Link]” - Google is


free to create “www”, “mail”, “news”, etc.
• Scalable: Each organization manages its own subdomains

• Organized: Structure reflects organization

Example of Decentralized Benefit:


ICANN (central): Assigns "[Link]" to Google

Google (decentralized): Creates:


- [Link]
- [Link]
- [Link]
- [Link]
- (all without asking ICANN)

DNS Uses Hierarchical Name Space

DOMAIN NAME SPACE


Inverted Tree Structure
Structure: DNS organizes names in inverted tree
. (root)

────┬────────────┼────────────┬────
│ │ │
com edu uk
│ │ │
────┼──── │ ────┼────
│ │ │ │ │ │
google yahoo apple mit bbc cam
│ │
cs www

www

Reading: Read from bottom (leaf) to top (root)


Example: [Link]. - www (host) - cs (subdomain of mit) - mit (domain) - edu
(top-level domain) - . (root)

Components

Root
Aspect Details
Position Top of tree (level 0)
Label Empty string (null)
Notation Just “.”
Servers 13 logical root server clusters
worldwide
Function Directs to TLD servers

Top-Level Domains (TLDs)


Category Examples Details
Generic com, edu, gov, org, net, mil, Based on organization
int type
Country us, uk, fr, in, de, jp, ca Two-letter country codes
Second-level [Link], [Link] Variation by country

Generic TLDs:
.com = Commercial
.edu = Education
.gov = Government
.org = Non-profit
.net = Network infrastructure
.mil = Military
.int = International organization

Country TLDs:
.us = United States
.uk = United Kingdom
.fr = France
.in = India
.de = Germany
.jp = Japan
.ca = Canada
.au = Australia
Nodes and Domains
Node: Single point in tree
Domain: Subtree of the name space
Example:
edu (node and domain)
└── [Link] (node and domain)
└── [Link] (node and domain)
└── [Link] (node - host, also domain if delegated)

Fully Qualified Domain Name (FQDN)

Definition
FQDN: Complete domain name ending with root
Format: Sequence of labels from node to root, separated by dots
Ending: Ends with “.” (represents root)
Example: [Link]. (note the final dot)
Characteristics: - Uniquely identifies a host on Internet - Unambiguous (ending “.” makes
it absolute) - Globally unique

Example FQDNs
[Link].
[Link].
[Link].
[Link].

Practical Note
Browsers hide trailing dot: - User types: [Link] (no dot) - Browser converts to:
[Link]. (adds dot) - Same thing!

Partially Qualified Domain Name (PQDN)

Definition
PQDN: Domain name without reaching root
Format: Doesn’t end with “.”
Scope: Only understood in local context
Example:
If you're at MIT:
- PQDN: "www" means "[Link]"
- Outside MIT: "www" is ambiguous

Full FQDN: "[Link]." (works anywhere)

When PQDNs Work


Within Organization:
At Google, type: "mail"
DNS resolver: "Prepend [Link] → [Link]"
Resolves correctly

Outside Organization:
At home, type: "mail"
DNS doesn't know: "mail" what?
Doesn't resolve

When to Use: - Internal organization networks - For convenience - Risky externally

DISTRIBUTION OF NAME SPACE


The Distribution Problem
Question: How are billions of domains stored and managed?
Answer: NOT on one server
Instead: Distributed across thousands of servers

DNS Hierarchy: Zones and Servers

What is a Zone?
Definition: Specific part of domain for which a server is responsible
Scope: Zone ⊆ Domain (zone is subset of domain it manages)
Responsibility: Server has authority over zone
Analogy: - Domain: Entire organization - Zone: Department within organization (server
responsible for it)

Example: [Link]
Entire Domain: [Link] (includes all subdomains)
Possible Zones: - Zone 1: [Link] (Google’s own servers manage main domain) - Zone
2: [Link] (separate team manages mail) - Zone 3: [Link] (separate
team manages drive)
Each Zone has its own primary and secondary servers

Server Types

Root Servers
Aspect Details
Zone Entire tree (root)
Authority Over all of DNS
Number 13 logical servers (hundreds of physical
machines via anycast)
Distribution Worldwide
Purpose Directs queries to TLD servers

Function:
"Where is [Link]?"
Root server: "I don't know exactly, but ask the .com server"
Client then asks .com server

Top-Level Domain (TLD) Servers


Aspect Details
Zone Each TLD (e.g., .com, .edu, .uk)
Authority All domains under that TLD
Number Multiple per TLD (for redundancy)
Purpose Direct to domain’s authoritative
server

Function:
"Where is [Link]?"
.com TLD server: "Ask Google's nameserver at [Link]"
Client then asks Google's server

Authoritative Servers
Aspect Details
Zone Specific domain
Authority Authoritative for domain’s records
Number Usually 2+ (primary + secondary)
Purpose Provide definitive answers

Function:
"What's IP of [Link]?"
Google's nameserver: "[Link]"
(definitive answer)
Primary Server
Aspect Details
Role Master server for domain
Responsibility Create, maintain, update zone file
Storage Zone file on disk
Updates Primary server updated first
Propagation Changes propagate to secondaries

Secondary Server
Aspect Details
Role Backup/slave server
Copy Zone file copy from primary
Retrieval Zone transfer from primary or other
secondary
Purpose Redundancy and load distribution
Updates Updated from primary (not directly
edited)

Redundancy and Reliability


Example Setup for [Link]:
Primary Server: [Link]
├─ Authoritative zone file
├─ Main source of truth
└─ Updated when DNS records change

Secondary Servers:
├─ [Link] (copy of zone file)
├─ [Link] (copy of zone file)
└─ ... (more secondaries)

Benefits: - If primary fails, secondaries respond - Load distributed (multiple servers) -


Geographically distributed (faster queries) - Reduces single point of failure

DNS IN THE INTERNET


Three-Part Structure
DNS divides address space into three sections:

Part 1: Generic Domains


Purpose: Classify by organization type
Domain Meaning Examples
.com Commercial [Link],
[Link]
.edu Educational [Link], [Link]
.gov Government [Link], [Link]
.org Non-profit [Link], [Link]
.net Network hosting companies,
registrars
.mil Military [Link]
.int International [Link]

Part 2: Country Domains


Purpose: Identify by country

Domain Country Examples


.us United States [Link]
.uk United Kingdom [Link]
.fr France [Link]
.in India [Link]
.de Germany [Link]
.jp Japan [Link]
.ca Canada [Link]
.au Australia [Link]

Subdomain Example: [Link] - uci = organization - ca = California (state) - us =


United States

Part 3: Inverse Domains


Purpose: Reverse mapping (IP → Name)
Use Case: Find domain name given IP address
Structure: .[Link] (reverse address pointer)
Format: IP reversed with .[Link] appended
Example:
IP: [Link]
Reverse domain: [Link].[Link]

Use Cases: - Email server validation (reverse DNS lookup) - Security checks - Logging
(resolve IPs to names)
DNS RESOLUTION
The Process
Goal: Translate name to IP address
Resolver: Client program that initiates resolution
How It Works: Client contacts DNS server, server recursively queries until answer found

Recursive Resolution

What is it?
Burden Placed: On the servers
Flow: Query flows up the hierarchy until answered
Direction: Answer flows back down

Scenario: Client Wants [Link]


Step 1: Client queries Local DNS Server
Client → Local DNS Server:
"What's IP of [Link]?"

Step 2: Local Server queries Root Server


Local DNS → Root Server:
"Where's [Link]?"
Root: "Ask .com server"

Step 3: Local Server queries TLD Server


Local DNS → .com Server:
"Where's [Link]?"
.com: "Ask [Link]"

Step 4: Local Server queries Authoritative Server


Local DNS → [Link]:
"What's IP of [Link]?"
Google: "[Link]"

Step 5: Answer bubbles back


[Link] → Local DNS: "[Link]"
Local DNS → Client: "[Link]"

Key: Local server does all the “running around”


Iterative Resolution

What is it?
Burden Placed: On the client’s resolver
Flow: Each server tells resolver where to ask next
Direction: Resolver keeps asking

Scenario: Client Wants [Link]


Step 1: Client queries Local DNS Server
Local DNS → Root Server:
"What's IP of [Link]?"
Root: "I don't know. Try [Link]"
(provides .com server address instead)

Step 2: Client queries TLD Server


Local DNS → .com Server:
"What's IP of [Link]?"
.com: "I don't know. Try [Link]"
(provides Google's address)

Step 3: Client queries Authoritative Server


Local DNS → [Link]:
"What's IP of [Link]?"
Google: "[Link]"

Step 4: Answer provided


[Link] → Local DNS: "[Link]"

Key: Local server keeps asking, each server directs to next

Comparison: Recursive vs. Iterative


Aspect Recursive Iterative
Burden On servers On client resolver
Work by Servers query servers Client queries servers
Referral Not given (answer expected) Given (told where to ask)
Follow-ups Server does Client does
Common Between servers Client to servers

Caching

Problem: Repeated Queries


Scenario: Many users ask “What’s IP of [Link]?”
Without caching: - Every query goes to root, TLD, authoritative server - Massive traffic -
Slow response - Server overload
With caching: Cache previous answers

How Caching Works


Step 1: Local DNS server makes query, gets answer
Step 2: Stores answer in cache (memory)
Step 3: Next client asks same question
Step 4: Server provides answer from cache (instant!)
No further queries needed

TTL (Time-To-Live)
Problem: Cached data becomes stale
Solution: Set expiration time
TTL: How long (in seconds) cached data is valid
Example:
[Link] A record: [Link], TTL=300

Cached at: 10:00 AM


Expires at: 10:05 AM (300 seconds later)

At 10:05 AM: Cache entry removed, must query again

Common TTL Values: - 300 seconds (5 min): Frequently changing records - 3600
seconds (1 hour): Standard records - 86400 seconds (1 day): Stable records - 43200
seconds (12 hours): Mixed frequency
Low TTL: Always fresh, more queries, more traffic
High TTL: Less fresh, fewer queries, less traffic

Dynamic DNS (DDNS)

Problem: Manual Updates Are Too Slow


Scenario: DHCP assigns new IP to computer
Without DDNS:
1. Computer gets new IP ([Link])
2. Administrator manually updates DNS zone file
3. (Hours or days later)
4. DNS finally points to new IP
5. During delay, old IP returned (host unreachable)

With DDNS: Automatic update

How DDNS Works


Step 1: Computer/DHCP server gets new IP
Step 2: Sends update to primary DNS server
"Update DNS record:
[Link] = [Link]"

Step 3: Primary server updates zone file immediately


Step 4: Secondary servers get update via zone transfer
Step 5: DNS immediately returns new IP
Result: Automated, near-instant updates

Use Cases
• Home networks (dynamic IP from ISP)
• Mobile devices (change networks frequently)
• Virtual machines (constantly spawned/destroyed)
• Cloud infrastructure (auto-scaling)

DNS MESSAGE FORMAT


Single Format for Query and Response
Design: Same message format for both query and response
Difference: Flags field indicates type

Message Structure
┌─────────────────────────────┐
│ Header (12 bytes) │ Identification, Flags, Counts
├─────────────────────────────┤
│ Question Section (variable) │ What are we asking for?
├─────────────────────────────┤
│ Answer Section (variable) │ Answers to question (in response)
├─────────────────────────────┤
│ Authority Section (variable)│ Authority records
├─────────────────────────────┤
│ Additional Section (var) │ Extra info (optional)
└─────────────────────────────┘
Header (12 bytes)
Fields:

Field Size Purpose


Identification 16 bits Match response to
query
Flags 16 bits QR, Opcode, AA, TC, RD,
RA, Z, Rcode
QDCOUNT 16 bits Questions in Question
section
ANCOUNT 16 bits Resource Records in
Answer
NSCOUNT 16 bits Name Server RRs in
Authority
ARCOUNT 16 bits Resource Records in
Additional

Key Flags: - QR (Query/Response): 0=Query, 1=Response - AA (Authoritative Answer): 1 if


from authoritative server - RD (Recursion Desired): 1 if recursive resolution requested -
RA (Recursion Available): 1 if recursive resolution available

Question Section
Contains: What we’re asking for
Example:
Name: [Link]
Type: A (IPv4 address)
Class: IN (Internet)

Answer Section
Contains: Answers to question (only in response)
Format: Resource Records
Example:
[Link] A [Link]
(Name Type IP Address)

Authority Section
Contains: Information about authoritative nameserver
Used for: Directing to next server in resolution chain
Additional Section
Contains: Supplementary information
Example: IP of nameserver mentioned in Authority section

TRANSPORT: UDP PORT 53


Why UDP?
DNS typically uses UDP: - Fast: No connection setup (unlike TCP) - Simple: Lightweight
protocol - Efficient: Low overhead - Standard: Port 53
Drawback: Limited to 512 bytes (can be exceeded)

TCP Port 53 for Large Responses


When: Response exceeds 512 bytes
Example: Zone transfer (all records for domain)
Use: TCP port 53 (reliable, no size limit)
Scenario:
Zone transfer request

Response > 512 bytes

Use TCP (TCP allows larger packets)

REGISTRARS AND REGISTRATION


What is a Registrar?
Definition: Organization that registers domain names
Accreditation: Must be accredited by ICANN
Function: Verifies domain uniqueness, enters into DNS database
Business: Charges fee for registration

Examples of Registrars
• GoDaddy
• Namecheap
• Network Solutions
• 1&1
• Google Domains
• Hostinger

ICANN (Internet Corporation for Assigned Names and Numbers)


Role: Overall authority managing DNS
Responsibilities: - Accredit registrars - Manage TLD assignments - Oversee root servers -
Policy development
Hierarchy:
ICANN (top authority)

Registrars (accredited companies)

Customers (individual/organizations)

Registration Process
Step 1: User chooses registrar
Step 2: User provides: - Desired domain name - Admin contact info - Technical contact info
- Nameserver addresses
Step 3: Registrar: - Checks domain availability (not already registered) - Verifies
uniqueness - Creates DNS zone file - Enters into database
Step 4: User is registered owner
Step 5: Charges annual fee for registration

DNS SECURITY
DNS Vulnerabilities

Problem 1: Reconnaissance
Attack: Read DNS responses to map network
Method: - Query DNS server - Response reveals internal IP addresses - Attacker learns
network structure

Problem 2: DNS Spoofing / Cache Poisoning


Attack: Inject fake DNS response
Scenario:
1. User requests: "What's IP of [Link]?"
2. Attacker sends fake response: "IP = [Link]"
3. DNS cache stores fake response
4. Months later, users directed to attacker's site!

Consequence: - All users cached to fake IP - Users visit attacker’s site thinking it’s bank -
Phishing, credential theft, malware

Problem 3: DoS Attacks


Attack: Flood root servers
Goal: Prevent anyone from resolving names
Impact: Internet largely unusable

DNSSEC (DNS Security Extensions)

What is it?
Solution: Add security to DNS records
Method: Digital signatures on DNS records

What it provides:
1. Data Origin Authentication - Verify answer came from real server - Not spoofed or
intercepted
2. Data Integrity - Verify answer not changed in transit - Ensures data is unchanged
What it does NOT provide:
Confidentiality: Records not encrypted (queries visible)

How it Works
Concept: Sign DNS records with cryptographic key
Process:
Original Record:
[Link] A [Link]

Sign with private key:


(+ signature appended)

Recipient verifies:
Uses public key to validate signature
If valid: Trust the answer
If invalid: Reject (spoofed or tampered)

Benefits
• Prevents cache poisoning
• Prevents spoofing
• Ensures data integrity
• Protects users from malicious redirects

EXAM TIPS AND KEY CONCEPTS


Application Layer Paradigms
Remember: - Client-Server: One server, many clients (HTTP, FTP, SMTP, POP3) - P2P:
Peers act as both client and server (BitTorrent, Skype) - Hybrid: Client-server for
discovery, P2P for data (Skype + tracker)

Socket Addressing
Formula: Socket Address = IP Address + Port Number
Well-Known Ports: - 21: FTP - 25: SMTP - 53: DNS - 80: HTTP - 110: POP3 - 143: IMAP -
443: HTTPS - 22: SSH

HTTP
Methods: GET (retrieve), POST (send), HEAD (metadata), PUT (upload), DELETE (remove)
Status Codes: - 2xx: Success - 3xx: Redirect - 4xx: Client error - 5xx: Server error
Persistent connections (HTTP/1.1 default): One TCP connection for multiple requests

FTP
Two connections: - Control (port 21): Commands - Data (port 20/ephemeral): File data
Modes: - Active: Server connects to client - Passive: Client connects to server

Email
Three agents: - UA (User Agent): Compose/read emails - MTA (SMTP): Relay between
servers - MAA (POP3/IMAP): Recipient retrieves
Protocols: - SMTP (port 25): Send (push) - POP3 (port 110): Download and delete - IMAP
(port 143): Manage on server

TELNET
Problem: Heterogeneous systems speak different languages
Solution: NVT (Network Virtual Terminal) - universal format
Security: Plaintext (NEVER use for sensitive data)
SSH
Three-layer architecture: 1. SSH-TRANS: Encryption and integrity 2. SSH-AUTH: User
authentication 3. SSH-CONN: Multiplexing channels
Uses: Remote login, SFTP (file transfer), port forwarding
Port: 22
Security: Everything encrypted

DNS
Purpose: Translate domain names to IP addresses
Hierarchy: Root → TLD → Authoritative servers
Resolution: - Recursive: Server does queries, client waits - Iterative: Server tells where to
ask next
Caching: TTL (Time-to-Live) determines cache duration
DNSSEC: Digital signatures for security

END OF MODULE 5 COMPLETE NOTES


This comprehensive guide covers all topics in Module 5: Application Layer. Study each section
systematically, memorize well-known ports and formulas, and understand conceptual
frameworks for exam success.

Common questions

Powered by AI

The hierarchical structure of the Domain Name System (DNS) offers significant benefits, including decentralization, scalability, and fault tolerance. By dividing the namespace into different levels (root, TLDs, domains, and subdomains), DNS ensures that no single server bears the entire resolution burden, leading to faster, localized queries and reduced points of failure, enhancing reliability and maintenance flexibility. However, challenges include the complexity of updates and coordination across numerous authoritative servers, potential propagation delays, and the necessity for robust security measures such as DNSSEC to prevent cache poisoning or spoofing attacks. Moreover, dependence on root and TLD servers can create central points of failure or bottlenecks if not resiliently designed and distributed .

Traditional FTP has several vulnerabilities, including the transmission of data and credentials in plaintext, making them susceptible to interception, credentials theft, and man-in-the-middle attacks. An attacker could sniff the network traffic to read passwords or file contents easily. The integration of an SSL/TLS wrapper (creating FTPS) mitigates these risks by encrypting the data and control channels, ensuring that any intercepted traffic is unreadable to an attacker without decryption keys. This encryption also authenticates the server with certificates, adding a layer of trust and integrity to the transfer process. Using SSL/TLS thus transforms FTP into a secure protocol, vastly improving its security posture .

The Session Initiation Protocol (SIP) differs fundamentally from FTP and Email in its communication model and functionality. SIP is designed for establishing, modifying, and terminating real-time communication sessions, such as VoIP or video conferencing. It operates in a peer-to-peer and synchronous manner where both parties must be online simultaneously for interaction. In contrast, FTP is used for file transfers, following a client-server model where the client requests resources from the server in a mostly synchronous interaction. Email, unlike both SIP and FTP, is inherently asynchronous, allowing messages to be sent and stored until the recipient retrieves them at their convenience, often resulting in significant delays between communication acts .

FTPS and SFTP differ fundamentally in how they secure file transfers. FTPS is essentially FTP with an added layer of SSL/TLS for encryption, which secures both commands and data. It uses ports 990 or 21 with STARTTLS for encryption and integrates smoothly into existing FTP infrastructure. On the other hand, SFTP is a different protocol altogether, using SSH (port 22) to provide a secure channel. SFTP offers a more modern security model and is integrated with SSH, providing benefits like easier firewall traversal and better security management, but it may require more setup changes to adopt. SFTP might be preferred for newer systems or where SSH infrastructure is prevalent, offering stronger security posture and simpler configuration through a single port, while FTPS might be useful where compatibility with traditional FTP services is needed .

The FTP passive mode helps overcome firewall issues because it changes the way the data connection is established. Instead of the server connecting back to the client (which could be blocked by the client's firewall), the client initiates the data connection by connecting to a port the server opens and indicates during the control session. This approach is often preferred in modern environments because clients are frequently behind firewalls or NAT, which typically allow outbound connections more readily than accepting inbound ones. This makes passive mode more firewall-friendly and common in current practice .

DNS plays a crucial role in internet infrastructure by translating human-friendly domain names into IP addresses, allowing users to interact with network resources easily without needing to remember complex numerical addresses. It handles the problem of centralization by distributing name resolution across a hierarchical and decentralized network of servers. This hierarchical structure divides the namespace into manageable zones, each of which is handled by authoritative servers. Root servers direct queries to the appropriate top-level domain (TLD) servers, which in turn direct queries to domain-specific authoritative servers. This division of responsibility ensures redundancy, reduces latency by localizing queries, and avoids a single point of failure, making DNS scalable and resilient to network changes and growth .

Authoritative DNS servers play a critical role in the DNS resolution process as they provide definitive answers regarding domain-to-IP mappings. When queried, they supply the requested domain records, establishing the accuracy and reliability of the domain's address information. The benefits of deploying primary and secondary servers are numerous: the primary server maintains the original zone file, while one or more secondary servers hold copies. This setup offers redundancy, ensuring that if the primary server fails, secondary servers can continue to provide DNS services, thus maintaining service availability. Additionally, by distributing queries among multiple servers, the DNS architecture benefits from load balancing, reduced latency, and increased reliability across geographically dispersed locations .

The Message Transfer Agent (MTA) is a crucial component in email delivery, responsible for routing emails from the sender's system to the recipient's mail server over the Internet. It operates by receiving emails from the sender's User Agent (UA), and using the Simple Mail Transfer Protocol (SMTP) to transfer these messages network-to-network until they reach the recipient's MTA server. SMTP ensures that the emails are appropriately routed by specifying the sender, recipient, and message content in a format that can be forwarded between MTAs across different mail servers. The MTA uses DNS to resolve the recipient's domain to its mail server address and handles email queuing, retries, and error management, ensuring delivery consistency .

The SSH protocol provides several advantages for secure communications compared to SSL/TLS, particularly regarding the model of client-server authentication. SSH inherently supports bidirectional authentication, with the server and client both verifying each other. SSH uses mechanisms like public key cryptography, password-based, and host-based authentication, allowing flexible and robust credential verification without exposing raw credentials over the network. Unlike SSL/TLS, which primarily authenticates the server to the client (and optionally the reverse in some setups), SSH starts each session with mutual authentication, ensuring both parties' identities and encrypting the entire session. This setup not only offers a simpler firewall traversal (using port 22) but also integrates easily with other services like SFTP under one protocol suite, enhancing security management and efficiency .

A Fully Qualified Domain Name (FQDN) is a complete domain name that specifies its absolute position in the DNS hierarchy, ending with a dot that represents the root. For example, 'www.example.com.' is an FQDN, ensuring global uniqueness and unambiguity. Conversely, a Partially Qualified Domain Name (PQDN) doesn't specify the entire path to the root, making it ambiguous without additional context. PQDNs are typically used within local networks or organizational contexts where the surrounding domain can be assumed. For example, within an organization called 'example.com,' a user might type 'www' to refer to 'www.example.com.' FQDNs are essential for internet-wide communication, while PQDNs offer convenience and brevity in internal settings where the context is implicit .

You might also like