Complete Protocols Master Part 5: Session & Presentation Layers
January 31, 2026Wasil Zafar40 min read
Explore the crucial middle layers that handle encryption, session management, and data representation. Master TLS/SSL, certificates, PKI, and learn how data is serialized, compressed, and secured for transmission.
In Part 4, we explored how TCP and UDP deliver data between applications. Now we examine Layers 5 and 6 of the OSI model—often overlooked but critically important for secure, efficient communication.
OSI Layers 5 and 6: Session and Presentation layers bridge the gap between transport and application
Series Context: This is Part 5 of 20 in the Complete Protocols Master series. We're bridging transport and application layers with security and data handling.
OSI Layer 5 - Session Layer:
├── Session establishment, maintenance, termination
├── Dialog control (who speaks when)
├── Synchronization (checkpoints for recovery)
├── Authentication negotiation
└── Examples: RPC sessions, NetBIOS, PPTP
OSI Layer 6 - Presentation Layer:
├── Data translation (format conversion)
├── Encryption/Decryption
├── Compression/Decompression
├── Character encoding (ASCII, UTF-8)
└── Examples: SSL/TLS, MIME, JPEG, MPEG
Reality Check:
┌────────────────────────────────────────────────────────┐
│ In TCP/IP, Layers 5-6 are merged into the │
│ Application Layer. TLS operates between TCP and │
│ HTTP, handling both session and presentation duties. │
│ │
│ Modern stacks: App ↔ TLS ↔ TCP ↔ IP ↔ Network │
└────────────────────────────────────────────────────────┘
Why Study These Layers? While pure OSI layers 5/6 protocols are rare, their functions are everywhere: TLS handles encryption (presentation) and session keys (session), JSON/XML handle data representation, and gzip handles compression. Understanding these concepts is essential for secure application development.
TLS/SSL Fundamentals
TLS (Transport Layer Security) is the cryptographic protocol that secures most internet traffic. When you see the padlock in your browser, TLS is at work.
The three pillars of TLS: confidentiality, integrity, and authentication
Forward Secrecy: (TLS 1.3) Past sessions can't be decrypted if keys compromised
Historical Note: SSL (Secure Sockets Layer) was developed by Netscape. After SSL 3.0, it was renamed TLS. SSL is now deprecated and insecure—always use TLS 1.2+.
TLS Version History
Version Timeline
TLS/SSL Evolution
Version
Year
Status
Key Features
SSL 2.0
1995
❌ Deprecated
First public version, many flaws
SSL 3.0
1996
❌ Deprecated
POODLE vulnerability
TLS 1.0
1999
⚠️ Deprecated
Renamed from SSL, BEAST vulnerability
TLS 1.1
2006
⚠️ Deprecated
Fixed BEAST, still weak
TLS 1.2
2008
✅ Supported
SHA-256, AEAD ciphers, most common
TLS 1.3
2018
✅ Recommended
Faster, simpler, mandatory forward secrecy
Security Advisory: TLS 1.0 and 1.1 were deprecated by browsers in 2020. Major sites dropped support. Always configure servers for TLS 1.2+ and prefer TLS 1.3.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: ClientHello + key_share + supported_versions
S->>C: ServerHello + key_share
Note over C,S: Handshake Keys Derived
S->>C: EncryptedExtensions
S->>C: Certificate
S->>C: CertificateVerify
S->>C: Finished
C->>S: Finished
Note over C,S: Application Keys Derived
C->>S: Application Data (encrypted)
S->>C: Application Data (encrypted)
# Examine TLS handshake with Python ssl module
import ssl
import socket
import pprint
def analyze_tls_connection(hostname, port=443):
"""Analyze TLS connection details"""
# Create SSL context
context = ssl.create_default_context()
# Connect and wrap socket
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(f"TLS Connection Analysis: {hostname}")
print("=" * 60)
# Protocol version
print(f"Protocol Version: {ssock.version()}")
# Cipher suite
cipher = ssock.cipher()
print(f"\nCipher Suite:")
print(f" Name: {cipher[0]}")
print(f" Protocol: {cipher[1]}")
print(f" Key Bits: {cipher[2]}")
# Certificate info
cert = ssock.getpeercert()
print(f"\nCertificate Info:")
print(f" Subject: {dict(x[0] for x in cert['subject'])}")
print(f" Issuer: {dict(x[0] for x in cert['issuer'])}")
print(f" Valid From: {cert['notBefore']}")
print(f" Valid Until: {cert['notAfter']}")
# Subject Alternative Names
if 'subjectAltName' in cert:
sans = [x[1] for x in cert['subjectAltName']]
print(f" SANs: {sans[:5]}{'...' if len(sans) > 5 else ''}")
return cert
# Example usage
print("Analyzing TLS connection to google.com...")
print("(This requires network access)")
print()
# Uncomment to run:
# analyze_tls_connection('google.com')
# Show available ciphers
print("\nDefault cipher list on this system:")
context = ssl.create_default_context()
ciphers = context.get_ciphers()
for i, cipher in enumerate(ciphers[:5]):
print(f" {i+1}. {cipher['name']}")
print(f" ... and {len(ciphers) - 5} more")
Certificates & PKI
X.509 certificates are digital documents that bind a public key to an identity. They're the foundation of internet trust.
X.509 certificate chain of trust: from root CA to intermediate CA to end-entity certificate
X.509 Structure
Certificate Contents
X.509 v3 Certificate Structure:
┌─────────────────────────────────────────────────────────────┐
│ Version: 3 │
│ Serial Number: Unique identifier │
│ Signature Algorithm: e.g., SHA256withRSA │
├─────────────────────────────────────────────────────────────┤
│ Issuer: CA that signed this certificate │
│ CN=DigiCert Global Root G2, O=DigiCert Inc, C=US │
├─────────────────────────────────────────────────────────────┤
│ Validity: │
│ Not Before: Jan 01 00:00:00 2024 GMT │
│ Not After: Jan 01 00:00:00 2025 GMT │
├─────────────────────────────────────────────────────────────┤
│ Subject: Entity this certificate identifies │
│ CN=www.example.com, O=Example Inc, L=City, C=US │
├─────────────────────────────────────────────────────────────┤
│ Subject Public Key Info: │
│ Algorithm: RSA (2048 bits) or ECDSA (P-256) │
│ Public Key: [binary data] │
├─────────────────────────────────────────────────────────────┤
│ X.509v3 Extensions: │
│ Key Usage: Digital Signature, Key Encipherment │
│ Extended Key Usage: TLS Web Server Authentication │
│ Subject Alternative Name: DNS:www.example.com, │
│ DNS:example.com │
│ Basic Constraints: CA:FALSE │
│ Authority Key Identifier: [CA's key ID] │
│ CRL Distribution Points: [URL to CRL] │
│ Authority Info Access: OCSP - [URL] │
├─────────────────────────────────────────────────────────────┤
│ Signature: CA's signature over all the above │
└─────────────────────────────────────────────────────────────┘
Certificate Chain of Trust
Trust Chain
How Certificate Validation Works
Certificate Chain (Chain of Trust):
┌─────────────────────────────────┐
│ Root CA Certificate │ ← Self-signed, pre-installed
│ (e.g., DigiCert Root CA) │ in browser/OS trust store
│ Validity: 20+ years │
└────────────────┬────────────────┘
│ Signs
▼
┌─────────────────────────────────┐
│ Intermediate CA Certificate │ ← Signed by Root CA
│ (e.g., DigiCert TLS RSA) │ Stored on server
│ Validity: 5-10 years │
└────────────────┬────────────────┘
│ Signs
▼
┌─────────────────────────────────┐
│ End-Entity Certificate │ ← Your website's cert
│ (e.g., www.example.com) │ Signed by Intermediate
│ Validity: 1-2 years │
└─────────────────────────────────┘
Validation Process:
1. Server sends: End-Entity + Intermediate cert(s)
2. Browser verifies End-Entity signature with Intermediate's public key
3. Browser verifies Intermediate signature with Root's public key
4. Root is in browser's trust store → TRUSTED
5. Check validity dates, revocation status (CRL/OCSP)
6. Check hostname matches certificate's CN or SAN
Certificate Chain of Trust
graph TD
Root["Root CA Self-Signed"]
Inter["Intermediate CA Signed by Root"]
End["End-Entity Certificate Website / Server"]
TS["Browser / OS Trust Store"]
Root -->|Signs| Inter
Inter -->|Signs| End
End -.->|Validates up to| Inter
Inter -.->|Validates up to| Root
Root -.->|Pre-installed in| TS
style Root fill:#BF092F,stroke:#132440,color:#fff
style Inter fill:#16476A,stroke:#132440,color:#fff
style End fill:#3B9797,stroke:#132440,color:#fff
style TS fill:#e8f4f4,stroke:#3B9797
Issues and signs certificates. Root CAs are trusted by default.
Registration Authority (RA)
Verifies identity before CA issues cert (domain validation, org validation).
Certificate Revocation List (CRL)
List of revoked certificates. Published periodically by CA.
OCSP (Online Certificate Status Protocol)
Real-time certificate status checking. More efficient than CRL.
OCSP Stapling
Server includes OCSP response in TLS handshake. Better privacy.
Certificate Transparency (CT)
Public logs of all issued certificates. Detects rogue CAs.
Let's Encrypt Revolution: Since 2015, Let's Encrypt has issued billions of free certificates, making HTTPS accessible to everyone. They automated Domain Validation (DV) via the ACME protocol, which tools like Certbot use.
Cryptography Basics
Understanding cryptographic primitives helps you make informed security decisions and debug TLS issues.
Symmetric vs. asymmetric encryption: shared key speed versus public-private key security
Symmetric Encryption
Symmetric (Secret Key) Cryptography
Same key for encryption and decryption. Fast, used for bulk data.
Symmetric Encryption:
Plaintext ─────► [Encrypt with Key K] ─────► Ciphertext
│
│ Same key
▼
Ciphertext ────► [Decrypt with Key K] ─────► Plaintext
Common Algorithms:
┌────────────────┬─────────────┬─────────────────────────────────┐
│ Algorithm │ Key Size │ Notes │
├────────────────┼─────────────┼─────────────────────────────────┤
│ AES-128 │ 128 bits │ Fast, secure, hardware support │
│ AES-256 │ 256 bits │ Quantum-resistant key size │
│ ChaCha20 │ 256 bits │ Fast on mobile (no AES-NI) │
│ 3DES │ 168 bits │ Legacy, avoid │
└────────────────┴─────────────┴─────────────────────────────────┘
Block Cipher Modes:
- GCM (Galois/Counter Mode): AEAD, parallelizable, preferred
- CBC (Cipher Block Chaining): Vulnerable to padding oracle, avoid
- CTR (Counter Mode): Streaming, needs separate MAC
Asymmetric (Public Key) Cryptography
Asymmetric Encryption
Public/Private Key Pairs
Asymmetric Encryption:
For Encryption (confidentiality):
Plaintext ─────► [Encrypt with Public Key] ─────► Ciphertext
Ciphertext ────► [Decrypt with Private Key] ────► Plaintext
For Digital Signatures (authentication):
Message ────────► [Sign with Private Key] ──────► Signature
Message+Sig ────► [Verify with Public Key] ─────► Valid/Invalid
Key Exchange (Diffie-Hellman):
Alice: a (private), g^a (public)
Bob: b (private), g^b (public)
Both compute: g^(ab) = shared secret
Common Algorithms:
┌────────────────┬─────────────────┬────────────────────────────┐
│ Algorithm │ Key Size │ Use Case │
├────────────────┼─────────────────┼────────────────────────────┤
│ RSA │ 2048-4096 bits │ Encryption, signatures │
│ ECDSA │ 256-384 bits │ Signatures (P-256, P-384) │
│ Ed25519 │ 256 bits │ Modern signatures, fast │
│ ECDH │ 256-384 bits │ Key exchange │
│ X25519 │ 256 bits │ Modern key exchange │
└────────────────┴─────────────────┴────────────────────────────┘
Why Both?
- Asymmetric: Solves key distribution (can share public key openly)
- Symmetric: Much faster (1000x) for bulk encryption
- TLS uses asymmetric to exchange symmetric keys, then symmetric for data
Hashing and MACs
Hash Functions
Cryptographic Hash Functions
Hash Function Properties:
- Deterministic: Same input → same output
- One-way: Cannot reverse hash to get input
- Collision-resistant: Hard to find two inputs with same hash
- Avalanche effect: Small input change → completely different hash
Common Hash Functions:
┌─────────────┬────────────┬───────────────────────────────────┐
│ Algorithm │ Output │ Status │
├─────────────┼────────────┼───────────────────────────────────┤
│ MD5 │ 128 bits │ ❌ Broken, collisions found │
│ SHA-1 │ 160 bits │ ❌ Deprecated, collisions found │
│ SHA-256 │ 256 bits │ ✅ Secure, widely used │
│ SHA-384 │ 384 bits │ ✅ Secure │
│ SHA-512 │ 512 bits │ ✅ Secure │
│ SHA-3 │ Variable │ ✅ Secure, backup to SHA-2 │
│ BLAKE2/3 │ Variable │ ✅ Fast, secure │
└─────────────┴────────────┴───────────────────────────────────┘
MAC (Message Authentication Code):
- Hash + Secret Key = MAC
- Verifies integrity AND authenticity
- HMAC-SHA256: HMAC(key, message) = hash
- Modern: Use AEAD modes (GCM) which include MAC
The Presentation Layer handles converting data between application format and network format. Serialization formats determine efficiency and interoperability.
Protocol Buffers (Google):
// .proto schema file
message User {
string name = 1;
int32 age = 2;
bool active = 3;
repeated string roles = 4;
}
Pros: Very compact, fast, schema-based, code generation
Cons: Not human-readable, requires schema, Google ecosystem
MessagePack:
Similar to JSON but binary-encoded
Pros: JSON-compatible, compact, fast, no schema needed
Cons: Less tooling than Protobuf
Apache Avro:
Schema embedded or separate, dynamic typing
Pros: Schema evolution, compact, Hadoop ecosystem
Cons: More complex, less common outside big data
Apache Thrift (Facebook):
RPC framework with serialization
Pros: Multi-language, includes RPC, flexible
Cons: Complex, heavy
FlatBuffers (Google):
Zero-copy deserialization
Pros: Extremely fast access, no parsing needed
Cons: Complex schemas, larger than Protobuf
Cap'n Proto:
Zero-copy, no encoding step
Pros: Fastest serialization (none needed)
Cons: Less portable, complex
Compression reduces data size for faster transmission and lower bandwidth costs. The Presentation Layer handles compression/decompression transparently.